parent
f1f4e99dab
commit
3f5ddfa346
96 changed files with 3202 additions and 96 deletions
@ -1 +1,7 @@ |
|||||||
# What is react native |
# React Native |
||||||
|
|
||||||
|
React Native is a popular open-source framework developed by Facebook for building mobile applications using JavaScript and React. It enables developers to build native mobile apps for iOS and Android platforms using a single codebase, which significantly speeds up development without compromising on the performance and usability of the apps. |
||||||
|
|
||||||
|
With React Native, you write components with JSX, a syntax that combines JavaScript and XML. These components can map to native UI elements like views, text, images, and more. |
||||||
|
|
||||||
|
For more in-depth information about React Native, I recommend visiting the [official documentation](https://reactnative.dev/docs/getting-started). |
@ -1 +1,9 @@ |
|||||||
# Why react native |
# Why React Native? |
||||||
|
|
||||||
|
React Native is a widely popular framework for building native mobile applications using JavaScript and React. There are plenty of reasons why you would want to choose React Native for your next mobile app development project: |
||||||
|
|
||||||
|
- **Code Reusability:** React Native allows you to share a significant amount of your codebase between iOS and Android platforms. This not only reduces the development time but also makes it easier to maintain the app. |
||||||
|
- **Familiar React Concepts:** If you're already familiar with ReactJS, React Native will feel right at home for you. Since it's based on React, the same principles of components and state management apply in React Native too. |
||||||
|
- **Native Performance:** React Native apps deliver near-native performance as the framework works directly with native components like Views and Text, thus eliminating the need for WebView or other similar intermediaries. |
||||||
|
- **Vast Ecosystem:** React Native enjoys a huge community and vast ecosystem that includes a wide range of libraries and tools that simplify and accelerate the development process. Additionally, Facebook and other major companies actively contribute to the growth and improvement of React Native. |
||||||
|
- **Hot Reloading:** React Native supports hot-reloading, which means you can see the changes you make in your code directly on the device/emulator without having to recompile or rebuild the app entirely. This makes for a faster and more efficient development process. |
@ -1 +1,7 @@ |
|||||||
# React native alternatives |
# React Native Alternatives |
||||||
|
|
||||||
|
React Native is a popular choice for cross-platform application development, but there are other options available. Some of the common alternatives to React Native are Flutter, Ionic and Xamarin. Flutter being the most popular alternative to React Native. |
||||||
|
|
||||||
|
- [Flutter Official Website](https://flutter.dev/) |
||||||
|
- [Ionic Official Website](https://ionicframework.com/) |
||||||
|
- [Xamarin Official Website](https://dotnet.microsoft.com/apps/xamarin) |
@ -1 +1,10 @@ |
|||||||
# Introduction |
# Introduction |
||||||
|
|
||||||
|
React Native is an open-source framework developed by Facebook that allows developers to build mobile applications using JavaScript and React. It enables building apps for both iOS and Android platforms by offering a shared codebase, which significantly reduces development time and effort. |
||||||
|
|
||||||
|
Visit the following resources to learn more: |
||||||
|
|
||||||
|
- [Official Website](https://reactnative.dev/) |
||||||
|
- [Official Getting Started to React Native](https://reactnative.dev/docs/getting-started) |
||||||
|
- [Build a React Native App by Mosh](https://www.youtube.com/watch?v=0-S5a0eXPoc) |
||||||
|
- [Learn React Native by CodeAcademy](https://www.codecademy.com/learn/learn-react-native) |
@ -1 +1,5 @@ |
|||||||
# Javascript |
# JavaScript Basics |
||||||
|
|
||||||
|
There's a lot more to learn in JavaScript but my recommendation is to learn the basics and then learn as you go. You'll learn a lot more by building things than by reading about them. |
||||||
|
|
||||||
|
- [Learn Beginner Topics in JavaScript Roadmap](/javascript) |
@ -1 +1,5 @@ |
|||||||
# Css |
# CSS Basics |
||||||
|
|
||||||
|
CSS is a stylesheet language used for describing the look and formatting of a document written in HTML or XML. It is primarily used for styling web pages and user interfaces written in HTML and XHTML. React native uses CSS to style its components. You can learn some CSS basics to get started with React Native and learn more as you go. |
||||||
|
|
||||||
|
- [W3Schools CSS Tutorial](https://www.w3schools.com/css/) |
@ -1 +1,6 @@ |
|||||||
# Components |
# Components |
||||||
|
|
||||||
|
React components are the building blocks of the user interface (UI) in a React application. They are used to break down the UI into reusable, isolated, and manageable pieces. Components handle rendering the UI and managing the logic and behavior. |
||||||
|
|
||||||
|
- [Components](https://react.dev/learn/your-first-component) and [Props](https://react.dev/learn/passing-props-to-a-component) |
||||||
|
|
||||||
|
@ -1 +1,51 @@ |
|||||||
# State |
# State |
||||||
|
|
||||||
|
State is an object that holds data managed within a React component. It allows components to become dynamic and interactive by keeping track of its data changes. When the state of a component changes, React re-renders the component and updates the DOM accordingly. |
||||||
|
|
||||||
|
In a functional component, utilize the `useState` hook to initialize state: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React, { useState } from 'react'; |
||||||
|
|
||||||
|
function App() { |
||||||
|
const [text, setText] = useState('Hello, World!'); |
||||||
|
//... |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## Accessing State |
||||||
|
|
||||||
|
|
||||||
|
In functional components, access the state by utilizing the first variable from the `useState` hook: |
||||||
|
|
||||||
|
```javascript |
||||||
|
function App() { |
||||||
|
const [text, setText] = useState('Hello, World!'); |
||||||
|
return <div>{text}</div>; |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## Updating State |
||||||
|
|
||||||
|
Utilize the second variable returned from the `useState` hook (which is a function) to update the state: |
||||||
|
|
||||||
|
```javascript |
||||||
|
function App() { |
||||||
|
const [text, setText] = useState('Hello, World!'); |
||||||
|
|
||||||
|
function handleClick() { |
||||||
|
setText('State updated!'); |
||||||
|
} |
||||||
|
|
||||||
|
return ( |
||||||
|
<div> |
||||||
|
<div>{text}</div> |
||||||
|
<button onClick={handleClick}>Update State</button> |
||||||
|
</div> |
||||||
|
); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
Remember: do not modify the state directly; always use the `setState()` method or updater function provided by the `useState` hook. |
||||||
|
|
||||||
|
- [Component State](https://react.dev/learn/managing-state) |
@ -1 +1,5 @@ |
|||||||
# Props |
# Props |
||||||
|
|
||||||
|
In React, **props** are short for _properties_ and are used to pass data from a parent component to a child component. They are similar to function arguments, and they help make components reusable and maintainable. |
||||||
|
|
||||||
|
- [Components](https://react.dev/learn/your-first-component) and [Props](https://react.dev/learn/passing-props-to-a-component) |
@ -1 +1,77 @@ |
|||||||
# Jsx |
# JSX |
||||||
|
|
||||||
|
JSX is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript code. It was developed to be used with React and has become an integral part of working with React. |
||||||
|
|
||||||
|
## Basic Syntax |
||||||
|
|
||||||
|
JSX looks similar to HTML, and you can mix it with JavaScript expressions within curly braces `{}`. |
||||||
|
|
||||||
|
Here's an example with a simple JSX element: |
||||||
|
|
||||||
|
```jsx |
||||||
|
const element = <h1>Hello, world!</h1>; |
||||||
|
``` |
||||||
|
|
||||||
|
## JavaScript Expressions in JSX |
||||||
|
|
||||||
|
You can embed JavaScript expressions within JSX by wrapping them in curly braces `{}`. |
||||||
|
|
||||||
|
Here's an example: |
||||||
|
|
||||||
|
```jsx |
||||||
|
const name = 'John Doe'; |
||||||
|
const element = <h1>Hello, {name}!</h1>; |
||||||
|
``` |
||||||
|
|
||||||
|
## Attributes in JSX |
||||||
|
|
||||||
|
You can use JSX to define attributes for your elements, similar to how you would in HTML. However, some attribute names in JSX are slightly different from their HTML counterparts due to conflicts with reserved JavaScript keywords (for example, `className` instead of `class`). |
||||||
|
|
||||||
|
Here's an example: |
||||||
|
|
||||||
|
```jsx |
||||||
|
const className = 'my-class'; |
||||||
|
const element = <h1 className={className}>Hello, world!</h1>; |
||||||
|
``` |
||||||
|
|
||||||
|
## Children in JSX |
||||||
|
|
||||||
|
You can nest JSX elements by enclosing them within the opening and closing tags of a parent element. |
||||||
|
|
||||||
|
Here's an example: |
||||||
|
|
||||||
|
```jsx |
||||||
|
const element = ( |
||||||
|
<div> |
||||||
|
<h1>Hello, world!</h1> |
||||||
|
<p>This is an example of nested JSX elements.</p> |
||||||
|
</div> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
## JSX Represents Objects |
||||||
|
|
||||||
|
Under the hood, JSX represents JavaScript objects called "React elements". When you use JSX, your JavaScript code gets automatically transformed into these React elements. |
||||||
|
|
||||||
|
Here's an example of a JSX element and its corresponding JavaScript object: |
||||||
|
|
||||||
|
```jsx |
||||||
|
const elementJSX = ( |
||||||
|
<h1 className="greeting"> |
||||||
|
Hello, world! |
||||||
|
</h1> |
||||||
|
); |
||||||
|
|
||||||
|
const elementJSObject = React.createElement( |
||||||
|
'h1', |
||||||
|
{className: 'greeting'}, |
||||||
|
'Hello, world!' |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
Both `elementJSX` and `elementJSObject` represent the same thing and will produce the same result when rendered. |
||||||
|
|
||||||
|
That's a brief summary of JSX. You'll find that it becomes an essential part of working with React as you continue learning about React Native. |
||||||
|
|
||||||
|
- [Writing Markup with JSX](https://react.dev/learn/writing-markup-with-jsx) |
||||||
|
- [JavaScript in JSX with Curly Braces](https://react.dev/learn/javascript-in-jsx-with-curly-braces) |
@ -1 +1,12 @@ |
|||||||
# React |
# React Basics |
||||||
|
|
||||||
|
React Native uses React, a JavaScript library for building user interfaces. You should have a basic understanding of React concepts before proceeding with React Native. Some of the concepts you should be familiar with include: |
||||||
|
|
||||||
|
- [Components](https://react.dev/learn/your-first-component) and [Props](https://react.dev/learn/passing-props-to-a-component) |
||||||
|
- [Component State](https://react.dev/learn/managing-state) |
||||||
|
- [Writing Markup with JSX](https://react.dev/learn/writing-markup-with-jsx) |
||||||
|
- [JavaScript in JSX with Curly Braces](https://react.dev/learn/javascript-in-jsx-with-curly-braces) |
||||||
|
|
||||||
|
Once you have a basic understanding of React, start with React Native. |
||||||
|
|
||||||
|
- [React Native Basics](https://reactnative.dev/docs/getting-started) |
@ -1 +1,6 @@ |
|||||||
# Pre requisites |
# Learn the Pre-requisites |
||||||
|
|
||||||
|
Before you start learning React Native, you should have a basic knowledge of [JavaScript](/javascript) and [React](/react). You don't need to fully master these topics, but you should be familiar with them. Learn the basics of JavaScript (e.g. topics marked for beginners in [JavaScript Roadmap](/javascript) and continue with React Native. I have heard good things about official React Native documentation, so you can start there and pick up the relevant topics wherever needed. |
||||||
|
|
||||||
|
- [Learn Beginner Topics in JavaScript](/javascript) |
||||||
|
- [React Native Basics](https://reactnative.dev/docs/getting-started) |
@ -1 +1,5 @@ |
|||||||
# Create expo app |
# Create Expo App |
||||||
|
|
||||||
|
`create-expo-app` is a command line tool that generates a React Native project that works out of the box with Expo. It is the easiest way to get started building a new React Native application. |
||||||
|
|
||||||
|
- [Official Expo Documentation](https://docs.expo.dev/tutorial/create-your-first-app/) |
@ -1 +1,5 @@ |
|||||||
# Expo snack |
# Expo Snack |
||||||
|
|
||||||
|
Expo Snack is an online playground and development environment for creating and testing React Native projects. With Snack, you can easily edit and preview your code changes directly in your browser or on a mobile device using the Expo Go app. It offers a fast, easy, and convenient way to develop, test, and share your projects without needing to set up a local development environment. |
||||||
|
|
||||||
|
- [Expo Snack Website](https://snack.expo.dev/) |
@ -1 +1,29 @@ |
|||||||
# Expo tradeoffs |
# Expo Tradeoffs |
||||||
|
|
||||||
|
Expo is a powerful tool that simplifies the React Native development process, but it has some limitations. Here's a summary of the tradeoffs you may face when using Expo. |
||||||
|
|
||||||
|
## Limited native modules |
||||||
|
|
||||||
|
Expo offers a set of pre-built native modules, which are really helpful but might not cover all the functionalities required for your specific app. If you need a custom native module or a third-party library that is not supported by Expo, you'll have to eject from the Expo managed workflow and switch to the bare-workflow or create a custom native module (native code) yourself. |
||||||
|
|
||||||
|
## Performance |
||||||
|
|
||||||
|
Expo adds an extra layer to your React Native app, which can cause performance issues, especially for large or complex apps. The bare-workflow may provide better performance as you have more control over the native libraries and app optimization. |
||||||
|
|
||||||
|
## App size |
||||||
|
|
||||||
|
Expo apps tend to have a larger app size because they include the entire Expo SDK, regardless of which modules you use in your app. In contrast, non-Expo apps can optimize their size by including only the required native modules. |
||||||
|
|
||||||
|
## Updates and upgrades |
||||||
|
|
||||||
|
When you rely on Expo, you depend on their release cycle for updates and upgrades. If React Native adds a new feature or fixes a bug, you have to wait for an updated Expo version to implement it. This may cause delays or limitations in your app development process. |
||||||
|
|
||||||
|
## Ejecting complications |
||||||
|
|
||||||
|
If you start a project with Expo and later decide to eject and use regular React Native, you might face challenges migrating your code and adjusting to the new configuration. You may need to rewrite some parts of your code or manually migrate dependencies. |
||||||
|
|
||||||
|
## Limited customizability |
||||||
|
|
||||||
|
Expo abstracts various aspects of customization and configuration, which can be a double-edged sword. If you need additional customizations that are not supported by Expo, you'll have to eject or switch to a bare-workflow project, which gives you more control over the native code. |
||||||
|
|
||||||
|
In summary, while Expo offers great tooling and simplifies the development process, it has certain limitations that you should consider before choosing it for your app development. |
@ -1 +1,5 @@ |
|||||||
# Expo |
# Expo |
||||||
|
|
||||||
|
Expo is a framework and a platform that allows you to develop, build, and deploy React Native applications easily and quickly. It simplifies the development process and provides a set of useful tools and services, including its own CLI (Command Line Interface), a managed workflow, and an SDK (Software Development Kit) with pre-built modules for common features. |
||||||
|
|
||||||
|
Visit the [Expo CLI Quickstart](https://reactnative.dev/docs/environment-setup) page for detailed instructions on how to set up your environment. |
@ -1 +1,5 @@ |
|||||||
# React native cli |
# React Native CLI |
||||||
|
|
||||||
|
React Native CLI is the official command-line interface for building native mobile apps using React Native. This method requires you to manually set up the native development environment and tools needed for iOS and Android app development. |
||||||
|
|
||||||
|
Visit the [React Native CLI Quickstart](https://reactnative.dev/docs/environment-setup?guide=native) page for detailed instructions on how to set up your environment. |
@ -1 +1,5 @@ |
|||||||
# Metro bundler |
# Metro Bundler |
||||||
|
|
||||||
|
Metro Bundler is the default bundler for React Native applications. It's a JavaScript module bundler that takes all your application code and dependencies, and bundles them together into a single JavaScript file or multiple files (based on platform). |
||||||
|
|
||||||
|
Visit the [Metro Bundler](https://facebook.github.io/metro/) website for more information. |
@ -1 +1,15 @@ |
|||||||
# Environment setup |
# Environment Setup |
||||||
|
|
||||||
|
In React Native, setting up the development environment is a crucial step. The environment setup process includes installing and configuring various tools and packages required for developing, building, and launching a React Native application. There are two main approaches when setting up your React Native development environment: |
||||||
|
|
||||||
|
## Expo CLI |
||||||
|
|
||||||
|
Expo CLI is a command-line tool built for creating and managing React Native projects easily. It streamlines your development process by providing an entire development environment, including building and deploying your app to both iOS and Android platforms. |
||||||
|
|
||||||
|
Visit the [Expo CLI Quickstart](https://reactnative.dev/docs/environment-setup) page for detailed instructions on how to set up your environment. |
||||||
|
|
||||||
|
## React Native CLI |
||||||
|
|
||||||
|
React Native CLI is the official command-line interface for building native mobile apps using React Native. This method requires you to manually set up the native development environment and tools needed for iOS and Android app development. |
||||||
|
|
||||||
|
Visit the [React Native CLI Quickstart](https://reactnative.dev/docs/environment-setup?guide=native) page for detailed instructions on how to set up your environment. |
@ -1 +1,3 @@ |
|||||||
# Running on device |
# Running on Device |
||||||
|
|
||||||
|
It's always a good idea to test your app on an actual device before releasing it to your users. [This document](https://reactnative.dev/docs/running-on-device) will guide you through the necessary steps to run your React Native app on a device and to get it ready for production. |
@ -1 +1,8 @@ |
|||||||
# Dev menu |
# In-App Developer Menu |
||||||
|
|
||||||
|
React Native provides an in-app developer menu which offers several debugging options. You can access the Dev Menu by shaking your device or via keyboard shortcuts: |
||||||
|
|
||||||
|
- Android: `Cmd + M` or `Ctrl + M` |
||||||
|
- iOS: `Cmd + D` or `Ctrl + D` |
||||||
|
|
||||||
|
Visit the [React Native docs](https://reactnative.dev/docs/debugging) for more information. |
@ -1 +1,5 @@ |
|||||||
# Fast refresh |
# Enabling Fast Refresh |
||||||
|
|
||||||
|
Fast Refresh is a React Native feature that allows you to get near-instant feedback while making changes in your code. It achieves this by reloading only the portion of the app that was changed, without losing the current state. This makes the development process a lot smoother as you don't have to wait for the entire app to rebuild after making a change. |
||||||
|
|
||||||
|
Learn more about Fast Refresh and how to enable it in the [React Native documentation](https://reactnative.dev/docs/fast-refresh). |
@ -1 +1,13 @@ |
|||||||
# Logbox |
# LogBox |
||||||
|
|
||||||
|
LogBox is a new feature added to React Native to improve how logs are displayed and managed in your development environment. It provides better visualization and organization of logs, warnings, and errors, making it easier for developers to address issues in their code. |
||||||
|
|
||||||
|
- **Better Error Formatting**: Errors are displayed in a more understandable format with clear syntax highlighting and relevant information regarding the error and the specific code that caused it. |
||||||
|
|
||||||
|
- **Improved Warnings**: Warnings now come with filtering and sorting options, allowing you to control which warnings you want to prioritize or ignore during development. |
||||||
|
|
||||||
|
- **Component Stacks**: Instead of displaying the raw call stack, LogBox provides a component stack that shows component hierarchy, allowing you to pinpoint the exact component causing the issue. |
||||||
|
|
||||||
|
- **Customizable**: You can disable LogBox, customize its behavior, or even extend it with your own code to tailor your debugging experience. |
||||||
|
|
||||||
|
Read more about LogBox in the [official documentation](https://reactnative.dev/docs/debugging#logbox). |
@ -1 +1,12 @@ |
|||||||
# Sourcemaps |
# Sourcemaps |
||||||
|
|
||||||
|
Sourcemaps are files that map the original source code of a project to its minified or transpiled version. This is especially useful in environments, like React Native, where the code may be transformed before being executed in the device/emulator. Sourcemaps help developers to debug their code more easily by mapping errors in the transformed code back to their original location in the source code. |
||||||
|
|
||||||
|
There are various types of sourcemaps which give different levels of detail to the debugging process: |
||||||
|
|
||||||
|
- `eval`: Uses `eval` function to generate the sourcemaps. This is faster but provides less detailed information than other options. |
||||||
|
- `cheap-source-map`: Simple line-to-line mapping without column information. Faster than `source-map` but less accurate. |
||||||
|
- `cheap-module-source-map`: Similar to `cheap-source-map` but with support for modules. |
||||||
|
- `source-map`: Full source mapping with both line and column information. It is accurate, though slower compared to other options. |
||||||
|
|
||||||
|
After generating sourcemaps, you can use them to debug errors more efficiently, as they will reference the original locations in the source code. The browser's developer tools, like Google Chrome, have built-in support for sourcemaps, providing the ability to navigate and debug errors with ease. |
@ -1 +1,5 @@ |
|||||||
# Devtools |
# React Native - DevTools |
||||||
|
|
||||||
|
|
||||||
|
You can use the [standalone version of React Developer Tools](https://github.com/facebook/react/tree/main/packages/react-devtools) to debug the React component hierarchy. Visit the [React Native Documentation](https://reactnative.dev/docs/react-devtools) for more information. |
||||||
|
|
||||||
|
@ -1 +1,3 @@ |
|||||||
# Debugging |
# Debugging |
||||||
|
|
||||||
|
Debugging is an essential aspect of the development workflow in React Native. Learn all about debugging in React Native in the [Debugging section of the React Native documentation](https://reactnative.dev/docs/debugging). |
@ -1 +1,3 @@ |
|||||||
# Development workflow |
# Development Workflow |
||||||
|
|
||||||
|
React native has a decent guide on how to get started with development workflow. Visit the [Workflow section](https://reactnative.dev/docs/running-on-device) of the official documentation to learn about different topics. |
@ -1 +1,39 @@ |
|||||||
# Text |
# Text Component |
||||||
|
|
||||||
|
The `Text` component is a basic element in React Native used to display text content on the screen. While it has some basic styling properties, you usually nest it inside other components (e.g., `View`) to create more complex UIs. |
||||||
|
|
||||||
|
Some common properties of the `Text` component include: |
||||||
|
|
||||||
|
- `style`: Apply a set of styling rules to the text, such as font size, color, and font family. |
||||||
|
- `numberOfLines`: Limit the number of lines shown in the text. This can be especially useful for long paragraphs or truncating a long title. |
||||||
|
- `onPress`: Add a function that gets called when the user taps on the text. |
||||||
|
- `allowFontScaling`: Specify whether to allow font scaling based on user's font settings. |
||||||
|
|
||||||
|
Here's a simple example using the `Text` component: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { Text, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const SimpleText = () => { |
||||||
|
return ( |
||||||
|
<Text style={styles.text} numberOfLines={2} onPress={() => alert('Hello')}> |
||||||
|
This is an example of a Text component in React Native. Tap on me! |
||||||
|
</Text> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
text: { |
||||||
|
fontSize: 16, |
||||||
|
color: 'blue', |
||||||
|
textAlign: 'center', |
||||||
|
margin: 10, |
||||||
|
fontFamily: 'Arial', |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default SimpleText; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, we create a `Text` element with some text content, apply styling, limit it to two lines, and add an `onPress` event. |
@ -1 +1,37 @@ |
|||||||
# Text input |
# Text Input |
||||||
|
|
||||||
|
`TextInput` is a core component in React Native that allows the user to enter text. It is commonly used to collect user data, like emails or passwords. You can customize the appearance of `TextInput` by using various props such as `placeholder`, `multiline`, `maxLength`, and more. |
||||||
|
|
||||||
|
Here's a basic example of using `TextInput`: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React, { useState } from 'react'; |
||||||
|
import { TextInput, View, Button } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
const [text, setText] = useState(''); |
||||||
|
|
||||||
|
const handleSubmit = () => { |
||||||
|
alert('You entered: ' + text); |
||||||
|
}; |
||||||
|
|
||||||
|
return ( |
||||||
|
<View> |
||||||
|
<TextInput |
||||||
|
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }} |
||||||
|
onChangeText={text => setText(text)} |
||||||
|
value={text} |
||||||
|
placeholder="Enter text here" |
||||||
|
/> |
||||||
|
<Button |
||||||
|
onPress={handleSubmit} |
||||||
|
title="Submit" |
||||||
|
/> |
||||||
|
</View> |
||||||
|
); |
||||||
|
}; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, the `TextInput` component is styled with a border, and there's a placeholder text to show the user the expected input. The `onChangeText` prop is used to manage the state of the input text, and a "Submit" button is provided to process the input data. |
||||||
|
|
||||||
|
For more advanced use cases, you can explore the [official documentation](https://reactnative.dev/docs/textinput). |
@ -1 +1,34 @@ |
|||||||
# Button |
# Button |
||||||
|
|
||||||
|
A `Button` is a built-in React Native component used to create clickable buttons. It is a simple, customizable and easy-to-use component that captures touches and triggers an `onPress` event when pressed. |
||||||
|
|
||||||
|
Here's a simple example of how to create a Button in React Native: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { Button } from 'react-native'; |
||||||
|
|
||||||
|
const MyButton = () => { |
||||||
|
const onPressHandler = () => { |
||||||
|
alert('Button Pressed'); |
||||||
|
}; |
||||||
|
|
||||||
|
return ( |
||||||
|
<Button |
||||||
|
title="Click me" |
||||||
|
color="#841584" |
||||||
|
onPress={onPressHandler} |
||||||
|
/> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
export default MyButton; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, we import the Button component from 'react-native', create a functional component `MyButton`, and define an `onPressHandler` function that will be called when the button is pressed. We then use the `Button` component and pass in the following props: |
||||||
|
|
||||||
|
- `title`: The text to display on the button. |
||||||
|
- `color`: The background color of the button. |
||||||
|
- `onPress`: The function to call when the button is pressed. |
||||||
|
|
||||||
|
When the button is pressed, the `onPressHandler` function will be called, and an alert will pop up saying "Button Pressed". |
@ -1 +1,51 @@ |
|||||||
# Image |
# Image |
||||||
|
|
||||||
|
The `Image` component is used to display images in a React Native application. It allows you to load and display local as well as remote images, providing essential props and methods for better image handling and customization. |
||||||
|
|
||||||
|
To use the `Image` component, you need to import it from 'react-native': |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { Image } from 'react-native'; |
||||||
|
``` |
||||||
|
|
||||||
|
To display a local image in the application, you have to require it in the `source` prop of the `Image` component. Place the image file in your project directory and use the following syntax: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<Image source={require('./path/to/your/image.png')} /> |
||||||
|
``` |
||||||
|
|
||||||
|
To display a remote image from a URL, you need to set the `source` prop with a `uri` object: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<Image source={{ uri: 'https://path/to/your/remote/image.png' }} /> |
||||||
|
``` |
||||||
|
|
||||||
|
Keep in mind that you need to define the dimensions (width and height) when using remote images: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<Image source={{ uri: 'https://path/to/remote/image.png' }} style={{ width: 200, height: 200 }} /> |
||||||
|
``` |
||||||
|
|
||||||
|
You can set image scaling and positioning with the `resizeMode` prop. It accepts the following values: `cover`, `contain`, `stretch`, `repeat`, and `center`. Default value is `cover`. |
||||||
|
|
||||||
|
```javascript |
||||||
|
<Image source={require('./path/to/your/image.png')} resizeMode="contain" /> |
||||||
|
``` |
||||||
|
|
||||||
|
There are additional props which you can use to further modify the image behavior. |
||||||
|
|
||||||
|
- `blurRadius`: Adds a blur effect to the image. |
||||||
|
- `defaultSource`: Displays a placeholder image while the target image is loading (only for Android). |
||||||
|
- `loadingIndicatorSource`: Similar to `defaultSource`, but works on both Android and iOS. |
||||||
|
- `onLoad`: A callback function that gets called when the image finishes loading. |
||||||
|
|
||||||
|
Here's an example combining some of these props: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<Image style={{ width: 300, height: 200 }} |
||||||
|
source={{ uri: 'https://path/to/remote/image.png' }} |
||||||
|
resizeMode="contain" |
||||||
|
onLoad={() => console.log('Image loaded')}> |
||||||
|
``` |
||||||
|
|
||||||
|
For more information and details, you can refer to the React Native docs: [Image - React Native](https://reactnative.dev/docs/image) |
@ -1 +1,38 @@ |
|||||||
# Image background |
# ImageBackground |
||||||
|
|
||||||
|
`ImageBackground` is a React Native core component that allows you to display an image as a background while still being able to place content inside the component. This helps in creating beautiful layouts with images and text or other content on top. |
||||||
|
|
||||||
|
To use `ImageBackground`, you need to import it from the `react-native` package and then include it in your JSX. |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { View, Text, ImageBackground, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => ( |
||||||
|
<ImageBackground |
||||||
|
source={{ uri: 'https://some-image-url.com/background.jpg' }} |
||||||
|
style={styles.background} |
||||||
|
resizeMode="cover" |
||||||
|
> |
||||||
|
<Text style={styles.text}>Hello, World!</Text> |
||||||
|
</ImageBackground> |
||||||
|
); |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
background: { |
||||||
|
flex: 1, |
||||||
|
justifyContent: 'center', |
||||||
|
}, |
||||||
|
text: { |
||||||
|
color: 'white', |
||||||
|
fontSize: 42, |
||||||
|
lineHeight: 84, |
||||||
|
fontWeight: 'bold', |
||||||
|
textAlign: 'center', |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
In the above example, `source` prop is used to add the image URL, `style` prop for adding some custom styling, and `resizeMode` to define how the image should stretch to fill the available space. The `Text` component inside the `ImageBackground` is then rendered on top of the image. |
@ -1 +1,34 @@ |
|||||||
# Switch |
# Switch |
||||||
|
|
||||||
|
A `Switch` is a core component in React Native used to implement a "toggle" or "on-off" input. It provides a UI for the user to switch between two different states, typically true or false. The primary use case is to enable or disable a feature or setting within an application. |
||||||
|
|
||||||
|
`Switch` component has a boolean `value` prop (true for on, false for off) and an `onValueChange` event handler, which is triggered whenever the user toggles the switch. |
||||||
|
|
||||||
|
Here's an example of how to use `Switch` in a React Native application: |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React, {useState} from 'react'; |
||||||
|
import {View, Switch, Text} from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
const [isEnabled, setIsEnabled] = useState(false); |
||||||
|
|
||||||
|
const toggleSwitch = () => setIsEnabled(previousState => !previousState); |
||||||
|
|
||||||
|
return ( |
||||||
|
<View> |
||||||
|
<Text>Enable Feature:</Text> |
||||||
|
<Switch |
||||||
|
trackColor={{ false: "#767577", true: "#81b0ff" }} |
||||||
|
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"} |
||||||
|
onValueChange={toggleSwitch} |
||||||
|
value={isEnabled} |
||||||
|
/> |
||||||
|
</View> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, `Switch` component's `value` prop is set to the state hook `isEnabled`. The `onValueChange` event handler triggers `toggleSwitch` function, which updates the state of `isEnabled`. The colors for the track and thumb of the switch can be customized using `trackColor` and `thumbColor` props. |
@ -1 +1,43 @@ |
|||||||
# Status bar |
# StatusBar |
||||||
|
|
||||||
|
The `StatusBar` component is used to control the appearance of the status bar on the top of the screen. It may strike as a bit unusual since, unlike other React Native components, it doesn't render any visible content. Instead, it sets some native properties that can help customize the look of status bars on Android, iOS, or other platforms. |
||||||
|
|
||||||
|
To use the `StatusBar` component, you need to import it from 'react-native' and use it in your `React` component. Here's an example: |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { View, StatusBar } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
return ( |
||||||
|
<View> |
||||||
|
<StatusBar barStyle="dark-content" backgroundColor="#F0F0F0" /> |
||||||
|
{/* Your other components */} |
||||||
|
</View> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
Here are some common properties you might want to use: |
||||||
|
|
||||||
|
- `barStyle`: Sets the color of the status bar text (light-content, dark-content, or default) |
||||||
|
- `backgroundColor`: Sets the background color of the status bar (Android only) |
||||||
|
- `hidden`: Hides or shows the status bar (true or false) |
||||||
|
- `animated`: Defines whether or not to animate status bar style changes (true or false) |
||||||
|
- `translucent`: Sets the status bar to be translucent (Android only) |
||||||
|
|
||||||
|
You can set these properties like in the following example: |
||||||
|
|
||||||
|
```jsx |
||||||
|
<StatusBar |
||||||
|
barStyle="light-content" |
||||||
|
backgroundColor="#6A0E37" |
||||||
|
hidden={false} |
||||||
|
animated={true} |
||||||
|
translucent={true} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
Remember, some properties work only on specific platforms (Android/iOS), so it's essential to check the compatibility when using different properties. |
@ -1 +1,23 @@ |
|||||||
# Activity indicator |
# Activity Indicator |
||||||
|
|
||||||
|
The `ActivityIndicator` is a core component in React Native that provides a simple visual indication of some ongoing activity or loading state within your application. It shows a spinning animation, which gives the user feedback that something is happening in the background. This component is particularly useful when fetching data from an external source, like a server, or while performing time-consuming operations. |
||||||
|
|
||||||
|
To use the `ActivityIndicator` component, simply import it from 'react-native', and add it to your component tree. You can customize the appearance and behavior of the `ActivityIndicator` by providing various optional props, such as `animating`, `color`, and `size`. |
||||||
|
|
||||||
|
Below is an example of how to use the `ActivityIndicator` component within a functional React component: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { ActivityIndicator, View, Text } from 'react-native'; |
||||||
|
|
||||||
|
const LoadingScreen = () => ( |
||||||
|
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> |
||||||
|
<Text>Loading, please wait...</Text> |
||||||
|
<ActivityIndicator size="large" color="#0000ff" /> |
||||||
|
</View> |
||||||
|
); |
||||||
|
|
||||||
|
export default LoadingScreen; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, the `ActivityIndicator` is placed within a `View` component alongside a `Text` component. The `ActivityIndicator` has its `size` set to 'large' and `color` set to blue. By default, the component will be animating. If you want to control the animation, you can use the `animating` prop and set it to `true` or `false`. |
@ -1 +1,58 @@ |
|||||||
# Modal |
# Modal |
||||||
|
|
||||||
|
A `Modal` is a component that displays content on top of the current view, creating an overlay that can be used for various purposes, such as displaying additional information, confirmation messages, or a selection menu. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React, {useState} from 'react'; |
||||||
|
import {Modal, Text, TouchableHighlight, View, Alert} from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
const [modalVisible, setModalVisible] = useState(false); |
||||||
|
|
||||||
|
return ( |
||||||
|
<View> |
||||||
|
<Modal |
||||||
|
animationType="slide" |
||||||
|
transparent={true} |
||||||
|
visible={modalVisible} |
||||||
|
onRequestClose={() => { |
||||||
|
Alert.alert('Modal has been closed.'); |
||||||
|
setModalVisible(!modalVisible); |
||||||
|
}}> |
||||||
|
<View> |
||||||
|
<View> |
||||||
|
<Text>Hello, I am a Modal!</Text> |
||||||
|
|
||||||
|
<TouchableHighlight |
||||||
|
onPress={() => { |
||||||
|
setModalVisible(!modalVisible); |
||||||
|
}}> |
||||||
|
<Text>Hide Modal</Text> |
||||||
|
</TouchableHighlight> |
||||||
|
</View> |
||||||
|
</View> |
||||||
|
</Modal> |
||||||
|
|
||||||
|
<TouchableHighlight |
||||||
|
onPress={() => { |
||||||
|
setModalVisible(true); |
||||||
|
}}> |
||||||
|
<Text>Show Modal</Text> |
||||||
|
</TouchableHighlight> |
||||||
|
</View> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, `Modal` is imported from `react-native` and used to create a modal overlay. The modal visibility is managed using the `useState` hook and is toggled using the `TouchableHighlight` components. |
||||||
|
|
||||||
|
Some of the modal properties include: |
||||||
|
|
||||||
|
- `animationType`: Controls how the modal appears and disappears. Possible values are `none`, `slide`, and `fade`. Default is `none`. |
||||||
|
- `transparent`: Determines whether the background is transparent or not. Default is `false`. |
||||||
|
- `visible`: Controls the visibility of the modal. Default is `true`. |
||||||
|
- `onRequestClose`: Called when the user tries to close the modal. Required on Android to properly handle the hardware back button. |
||||||
|
|
||||||
|
For more information and prop details, you can check out the [official documentation](https://reactnative.dev/docs/modal). |
@ -1 +1,59 @@ |
|||||||
# Pressable |
# Pressable |
||||||
|
|
||||||
|
Pressable is a core component in React Native that makes any view respond properly to touch or press events. It provides a wide range of event handlers for managing user interactions, such as onPress, onPressIn, onPressOut, and onLongPress. With Pressable, you can create custom buttons, cards, or any touchable elements within your app. |
||||||
|
|
||||||
|
To use Pressable in your React Native application, you need to import it from 'react-native': |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { Pressable } from 'react-native'; |
||||||
|
``` |
||||||
|
|
||||||
|
Wrap any view or component you want to make pressable with the Pressable component: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<Pressable onPress={() => console.log('Pressed!')}> |
||||||
|
<Text>Press me</Text> |
||||||
|
</Pressable> |
||||||
|
``` |
||||||
|
|
||||||
|
Pressable allows you to customize its appearance and behavior according to the user interaction state. You can use the `style` prop and pass a function that sets the style based on the state. |
||||||
|
|
||||||
|
Here's an example of a custom button that changes its background color when pressed: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { Pressable, Text, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
export default function CustomButton() { |
||||||
|
return ( |
||||||
|
<Pressable |
||||||
|
onPress={() => console.log('Pressed!')} |
||||||
|
style={({ pressed }) => [ |
||||||
|
styles.button, |
||||||
|
pressed ? styles.pressedButton : styles.normalButton, |
||||||
|
]} |
||||||
|
> |
||||||
|
<Text style={styles.buttonText}>Press me</Text> |
||||||
|
</Pressable> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
button: { |
||||||
|
padding: 10, |
||||||
|
borderRadius: 5, |
||||||
|
}, |
||||||
|
normalButton: { |
||||||
|
backgroundColor: 'blue', |
||||||
|
}, |
||||||
|
pressedButton: { |
||||||
|
backgroundColor: 'darkblue', |
||||||
|
}, |
||||||
|
buttonText: { |
||||||
|
color: 'white', |
||||||
|
textAlign: 'center', |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, when the Pressable is pressed, it will change its background color from "blue" to "darkblue". |
@ -1 +1,30 @@ |
|||||||
# Safe area view |
# SafeAreaView |
||||||
|
|
||||||
|
`SafeAreaView` is a React Native core component that helps to adjust your app's UI elements and layout to accommodate the notches, curved edges, or home indicator on iOS devices. It is particularly useful for the iPhone X and newer iPhone models, as it ensures that content is rendered within the visible portion of the screen. |
||||||
|
|
||||||
|
Here is an example of using `SafeAreaView` in the code: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { SafeAreaView, StyleSheet, Text } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
return ( |
||||||
|
<SafeAreaView style={styles.container}> |
||||||
|
<Text>Hello World!</Text> |
||||||
|
</SafeAreaView> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, the `SafeAreaView` component wraps around the content (in this case, a `Text` component), ensuring that the text is displayed within the safe area of the screen. By using `SafeAreaView`, you no longer have to worry about placing content outside the visible area or having it obstructed by the notch on iOS devices. |
||||||
|
|
||||||
|
Keep in mind that `SafeAreaView` only works on iOS devices, and has no effect on Android devices. To handle such cases, you can use platform-specific styles or libraries like `react-native-safe-area-context` which provide more control and customization options for additional platforms. |
@ -1 +1,45 @@ |
|||||||
# Keyboard avoiding view |
# KeyboardAvoidingView |
||||||
|
|
||||||
|
`KeyboardAvoidingView` is a built-in React Native component that automatically adjusts its children components' position when the keyboard opens, preventing them from being obscured by the on-screen keyboard. It's a useful component, particularly for forms and input fields where the user needs to see the text they're typing. |
||||||
|
|
||||||
|
## Usage |
||||||
|
|
||||||
|
To use the `KeyboardAvoidingView`, simply wrap the desired components that need to avoid the keyboard with the `KeyboardAvoidingView` component. The prop `behavior` is used to specify the type of animating behavior the component will use. This behavior differs depending on the platform and can be one of 'height', 'position', 'padding', or a custom defined behavior. |
||||||
|
|
||||||
|
Here's a basic example: |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { View, TextInput, StyleSheet, KeyboardAvoidingView } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
return ( |
||||||
|
<KeyboardAvoidingView |
||||||
|
style={styles.container} |
||||||
|
behavior="padding" // Additional padding when the keyboard is open. |
||||||
|
> |
||||||
|
<TextInput |
||||||
|
placeholder="Type something here" |
||||||
|
style={styles.textInput} |
||||||
|
/> |
||||||
|
</KeyboardAvoidingView> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
justifyContent: 'center', |
||||||
|
}, |
||||||
|
textInput: { |
||||||
|
borderWidth: 1, |
||||||
|
borderColor: 'black', |
||||||
|
padding: 10, |
||||||
|
margin: 20, |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
Remember to test the behavior on different devices and platforms to ensure the desired result is achieved. |
@ -1 +1,31 @@ |
|||||||
# View |
# View |
||||||
|
|
||||||
|
The `View` component in React Native is a fundamental container component that supports various layout styles. It is the equivalent of a `div` element in HTML and can be used to create and style containers for various elements. It is a versatile component that can handle various user interactions, including touch events, as well as serving as a decorative and functional piece in your mobile application. |
||||||
|
|
||||||
|
Here's an example of how to use the `View` component: |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { StyleSheet, View, Text } from 'react-native'; |
||||||
|
|
||||||
|
function App() { |
||||||
|
return ( |
||||||
|
<View style={styles.container}> |
||||||
|
<Text>Hello, World!</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
backgroundColor: '#fff', |
||||||
|
alignItems: 'center', |
||||||
|
justifyContent: 'center', |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, the `View` component is used to create a container with a background color of white and centering its child components both vertically and horizontally. Inside the container, a `Text` component displays the message "Hello, World!". |
@ -1 +1,29 @@ |
|||||||
# Scroll view |
# Scroll View |
||||||
|
|
||||||
|
In React Native, the `ScrollView` is a generic scrolling container used to provide a scrollable view to its child components. It is useful when you need to display scrollable content larger than the screen, such as lists, images, or text. A `ScrollView` must have a bounded height in order to properly work. |
||||||
|
|
||||||
|
Here's a simple example of how to use the `ScrollView` component in your React Native app: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { ScrollView, Text } from 'react-native'; |
||||||
|
|
||||||
|
const MyScrollView = () => { |
||||||
|
return ( |
||||||
|
<ScrollView> |
||||||
|
<Text>Item 1</Text> |
||||||
|
<Text>Item 2</Text> |
||||||
|
<Text>Item 3</Text> |
||||||
|
<Text>Item 4</Text> |
||||||
|
<Text>Item 5</Text> |
||||||
|
<Text>Item 6</Text> |
||||||
|
</ScrollView> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
export default MyScrollView; |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, the `ScrollView` component is imported from the `react-native` package, and it's used as a container for several `Text` components that represent items in a list. Users can scroll through the items if they don't fit on the screen. |
||||||
|
|
||||||
|
Keep in mind that `ScrollView` is not optimized for long lists of items, and you should use the `FlatList` or `SectionList` components for better performance in those cases. However, it's still useful for smaller content where you need a scrollable area, such as forms or when the content size is unknown. |
@ -1 +1,40 @@ |
|||||||
# Flat list |
# FlatList |
||||||
|
|
||||||
|
`FlatList` is a `React Native` core component that displays a scrolling list of changing, but similarly structured, data. It is an efficient list component that makes use of a limited scrolling `renderWindow`, reducing the memory footprint and creating smooth scrolling. Additionally, `FlatList` supports-Headers, Footers, Pull-to-refresh, and Horizontal scrolling, among other things. |
||||||
|
|
||||||
|
Here is a basic example demonstrating how to use the `FlatList` component: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { FlatList, View, Text } from 'react-native'; |
||||||
|
|
||||||
|
const data = [ |
||||||
|
{ id: '1', content: 'Item 1' }, |
||||||
|
{ id: '2', content: 'Item 2' }, |
||||||
|
{ id: '3', content: 'Item 3' }, |
||||||
|
// ... |
||||||
|
]; |
||||||
|
|
||||||
|
const renderItem = ({ item }) => ( |
||||||
|
<View> |
||||||
|
<Text>{item.content}</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
|
||||||
|
const MyFlatList = () => ( |
||||||
|
<FlatList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id} |
||||||
|
/> |
||||||
|
); |
||||||
|
|
||||||
|
export default MyFlatList; |
||||||
|
``` |
||||||
|
|
||||||
|
In the example above: |
||||||
|
|
||||||
|
- We import the `FlatList` along with `View` and `Text` components. |
||||||
|
- We have an array of data containing objects with a unique ID and content. |
||||||
|
- `renderItem` is a function that takes an item and returns the components to render for that item. |
||||||
|
- In the `MyFlatList` component, we use the `FlatList` and pass the data, the `renderItem` function, and a `keyExtractor` to extract a key from the item. |
@ -1 +1,103 @@ |
|||||||
# List views |
# List Views in React Native |
||||||
|
|
||||||
|
List views are an essential component in mobile applications when you need to display a list of items in an organized and efficient way. In React Native, there are two primary components to display a list - `FlatList` and `SectionList`. Let's dive into each one with some examples. |
||||||
|
|
||||||
|
## FlatList |
||||||
|
|
||||||
|
A `FlatList` is a simple list view component that renders a list of items in a user-friendly scrolling format. FlatList is great for large lists of data that only render a small number of items on the screen at a time. It supports both horizontal and vertical scrolling, allows you to customize the appearance of items, and provides built-in performance optimizations. |
||||||
|
|
||||||
|
Here's a basic example using FlatList: |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { View, FlatList, Text, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const data = [ |
||||||
|
{ id: '1', title: 'Item 1' }, |
||||||
|
{ id: '2', title: 'Item 2' }, |
||||||
|
{ id: '3', title: 'Item 3' }, |
||||||
|
]; |
||||||
|
|
||||||
|
const renderItem = ({ item }) => ( |
||||||
|
<View style={styles.item}> |
||||||
|
<Text>{item.title}</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
|
||||||
|
const App = () => ( |
||||||
|
<FlatList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id} |
||||||
|
/> |
||||||
|
); |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
item: { |
||||||
|
backgroundColor: '#f9c2ff', |
||||||
|
padding: 20, |
||||||
|
marginVertical: 8, |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
## SectionList |
||||||
|
|
||||||
|
A `SectionList` is a more complex list view component that presents items in multiple sections with optional section headers. It is suitable for use cases where you need to categorize data into separate sections and display a header for each section. |
||||||
|
|
||||||
|
Here's a basic example using SectionList: |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { View, SectionList, Text, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const data = [ |
||||||
|
{ |
||||||
|
title: 'Section 1', |
||||||
|
data: ['Item 1.1', 'Item 1.2', 'Item 1.3'], |
||||||
|
}, |
||||||
|
{ |
||||||
|
title: 'Section 2', |
||||||
|
data: ['Item 2.1', 'Item 2.2', 'Item 2.3'], |
||||||
|
}, |
||||||
|
]; |
||||||
|
|
||||||
|
const renderItem = ({ item }) => ( |
||||||
|
<View style={styles.item}> |
||||||
|
<Text>{item}</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
|
||||||
|
const renderSectionHeader = ({ section: { title } }) => ( |
||||||
|
<View style={styles.header}> |
||||||
|
<Text>{title}</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
|
||||||
|
const App = () => ( |
||||||
|
<SectionList |
||||||
|
sections={data} |
||||||
|
keyExtractor={(item, index) => item + index} |
||||||
|
renderItem={renderItem} |
||||||
|
renderSectionHeader={renderSectionHeader} |
||||||
|
/> |
||||||
|
); |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
item: { |
||||||
|
backgroundColor: '#f9c2ff', |
||||||
|
padding: 20, |
||||||
|
marginVertical: 8, |
||||||
|
}, |
||||||
|
header: { |
||||||
|
backgroundColor: 'skyblue', |
||||||
|
padding: 20, |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
In summary, `FlatList` and `SectionList` are the primary list view components in React Native. Use `FlatList` for simple lists and when performance is a priority, and use `SectionList` when you need to organize data into multiple sections. |
@ -1 +1,64 @@ |
|||||||
# Section list |
# SectionList |
||||||
|
|
||||||
|
`SectionList` is a component used to render sections and headers in a scroll view. It helps to manage and optimize a large list of items divided into categories. It is one of the List View components provided by React Native along with FlatList. |
||||||
|
|
||||||
|
The key difference between SectionList and FlatList is that SectionList separates data items into sections, with headers. |
||||||
|
|
||||||
|
Here's an example of how to use a SectionList in your app: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React, {Component} from 'react'; |
||||||
|
import {SectionList, StyleSheet, Text, View, SafeAreaView} from 'react-native'; |
||||||
|
|
||||||
|
export default class App extends Component { |
||||||
|
render() { |
||||||
|
return ( |
||||||
|
<SafeAreaView style={styles.container}> |
||||||
|
<SectionList |
||||||
|
sections={[ |
||||||
|
{ |
||||||
|
title: 'Section 1', |
||||||
|
data: ['Item 1.1', 'Item 1.2', 'Item 1.3'], |
||||||
|
}, |
||||||
|
{ |
||||||
|
title: 'Section 2', |
||||||
|
data: ['Item 2.1', 'Item 2.2', 'Item 2.3'], |
||||||
|
}, |
||||||
|
]} |
||||||
|
renderItem={({item}) => <Text style={styles.item}>{item}</Text>} |
||||||
|
renderSectionHeader={({section}) => ( |
||||||
|
<Text style={styles.sectionHeader}>{section.title}</Text> |
||||||
|
)} |
||||||
|
keyExtractor={(item, index) => String(index)} |
||||||
|
/> |
||||||
|
</SafeAreaView> |
||||||
|
); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
paddingRight: 10, |
||||||
|
paddingLeft: 10, |
||||||
|
}, |
||||||
|
sectionHeader: { |
||||||
|
fontSize: 20, |
||||||
|
fontWeight: 'bold', |
||||||
|
backgroundColor: 'lightgrey', |
||||||
|
padding: 5, |
||||||
|
}, |
||||||
|
item: { |
||||||
|
fontSize: 16, |
||||||
|
padding: 10, |
||||||
|
borderBottomWidth: 1, |
||||||
|
borderBottomColor: 'black', |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, we have two sections: 'Section 1' and 'Section 2'. Each section has its own data items. |
||||||
|
|
||||||
|
`renderItem` is a function that takes an object containing an item property and returns a Text component with the item value. |
||||||
|
|
||||||
|
`renderSectionHeader` is a function that takes an object containing a section property and returns a text component with the section's title. |
@ -1 +1,45 @@ |
|||||||
# Refresh control |
# Refresh Control |
||||||
|
|
||||||
|
`RefreshControl` is a component in React Native that is used to provide pull-to-refresh functionality for scrollable components like `ScrollView`, `ListView`, and `FlatList`. |
||||||
|
|
||||||
|
## How to use RefreshControl: |
||||||
|
|
||||||
|
- Import `RefreshControl` from 'react-native': |
||||||
|
``` |
||||||
|
import { RefreshControl } from 'react-native'; |
||||||
|
``` |
||||||
|
- Add `RefreshControl` to a scrollable component (`ScrollView`, `ListView`, or `FlatList`). Here is an example with `FlatList`: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React, { useState } from 'react'; |
||||||
|
import { FlatList, RefreshControl, Text } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
const [refreshing, setRefreshing] = useState(false); |
||||||
|
|
||||||
|
const fetchData = () => { |
||||||
|
// Fetch the data and update your state accordingly |
||||||
|
}; |
||||||
|
|
||||||
|
const onRefresh = () => { |
||||||
|
setRefreshing(true); |
||||||
|
fetchData().then(() => { |
||||||
|
setRefreshing(false); |
||||||
|
}); |
||||||
|
}; |
||||||
|
|
||||||
|
return ( |
||||||
|
<FlatList |
||||||
|
data={['Item 1', 'Item 2', 'Item 3']} |
||||||
|
renderItem={({ item }) => <Text>{item}</Text>} |
||||||
|
refreshControl={ |
||||||
|
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} /> |
||||||
|
} |
||||||
|
/> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
In the example above, we have a `FlatList` that renders a list of items. When the user pulls down the list, the `onRefresh` function is triggered and fetches new data. The `refreshing` state is used to control the visibility of the refresh indicator. When `refreshing` is set to `true`, the refresh indicator is shown. It is hidden when `refreshing` is set to `false`. |
@ -1 +1,82 @@ |
|||||||
# Listings |
# Listings |
||||||
|
|
||||||
|
When working with listings in React Native, the commonly used components include: |
||||||
|
|
||||||
|
- **FlatList** - It is a high-performance, scrollable list component that renders a large number of items efficiently. |
||||||
|
|
||||||
|
Example: |
||||||
|
```jsx |
||||||
|
import { FlatList, Text } from 'react-native'; |
||||||
|
|
||||||
|
const data = [ |
||||||
|
{ id: 1, text: 'Item 1' }, |
||||||
|
{ id: 2, text: 'Item 2' }, |
||||||
|
{ id: 3, text: 'Item 3' }, |
||||||
|
]; |
||||||
|
|
||||||
|
const renderItem = ({ item }) => <Text>{item.text}</Text>; |
||||||
|
|
||||||
|
const MyFlatList = () => ( |
||||||
|
<FlatList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id.toString()} |
||||||
|
/> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
- **SectionList** - Similar to FlatList, but it is used when you want to display data in separate sections with section headers. |
||||||
|
|
||||||
|
Example: |
||||||
|
```jsx |
||||||
|
import { SectionList, Text } from 'react-native'; |
||||||
|
|
||||||
|
const sections = [ |
||||||
|
{ title: 'Section 1', data: ['Item 1', 'Item 2', 'Item 3'] }, |
||||||
|
{ title: 'Section 2', data: ['Item 4', 'Item 5', 'Item 6'] }, |
||||||
|
]; |
||||||
|
|
||||||
|
const Item = ({ text }) => <Text>{text}</Text>; |
||||||
|
const SectionHeader = ({ title }) => <Text>{title}</Text>; |
||||||
|
|
||||||
|
const MySectionList = () => ( |
||||||
|
<SectionList |
||||||
|
sections={sections} |
||||||
|
renderItem={({ item }) => <Item text={item} />} |
||||||
|
renderSectionHeader={({ section: { title } }) => ( |
||||||
|
<SectionHeader title={title} /> |
||||||
|
)} |
||||||
|
keyExtractor={(item, index) => item + index} |
||||||
|
/> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
- **VirtualizedList** - A lower-level component for rendering large lists and for more fine-grained control over list rendering performance. |
||||||
|
|
||||||
|
Example: |
||||||
|
```jsx |
||||||
|
import { VirtualizedList, Text } from 'react-native'; |
||||||
|
|
||||||
|
const data = [ |
||||||
|
{ id: 1, text: 'Item 1' }, |
||||||
|
{ id: 2, text: 'Item 2' }, |
||||||
|
{ id: 3, text: 'Item 3' }, |
||||||
|
]; |
||||||
|
|
||||||
|
const getItemCount = data => data.length; |
||||||
|
const getItem = (data, index) => data[index]; |
||||||
|
|
||||||
|
const renderItem = ({ item }) => <Text>{item.text}</Text>; |
||||||
|
|
||||||
|
const MyVirtualizedList = () => ( |
||||||
|
<VirtualizedList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id.toString()} |
||||||
|
getItemCount={getItemCount} |
||||||
|
getItem={getItem} |
||||||
|
/> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
These components are essential when dealing with dynamic data and displaying large lists in React Native applications. |
@ -1 +1,65 @@ |
|||||||
# Core components |
# Core Components |
||||||
|
|
||||||
|
Core components are the essential building blocks provided by React Native to create a user interface for mobile applications. They are platform-agnostic, meaning they work across both iOS and Android devices. Some of the common core components include: |
||||||
|
|
||||||
|
- `View` is a fundamental component for constructing the user interface. It is equivalent to a `div` in HTML and can be used as a container for other components. |
||||||
|
|
||||||
|
```javascript |
||||||
|
<View style={styles.container}> |
||||||
|
<Text>Hello World!</Text> |
||||||
|
</View> |
||||||
|
``` |
||||||
|
|
||||||
|
- `Text` is used to display text content in your app. It is similar to the `p` or `span` elements in HTML. |
||||||
|
|
||||||
|
```javascript |
||||||
|
<Text style={styles.title}>Welcome to my App</Text> |
||||||
|
``` |
||||||
|
|
||||||
|
- `Image` is used to display images in your application. It can load images from local sources or remote URLs. |
||||||
|
|
||||||
|
```javascript |
||||||
|
<Image source={require('./assets/logo.png')} /> |
||||||
|
|
||||||
|
<Image source={{ uri: 'https://example.com/image.png' }} /> |
||||||
|
``` |
||||||
|
|
||||||
|
- `TextInput` is a basic input field that allows users to type text into your app. It is similar to the `input` element in HTML. |
||||||
|
|
||||||
|
```javascript |
||||||
|
<TextInput |
||||||
|
value={this.state.text} |
||||||
|
onChangeText={text => this.setState({ text })} |
||||||
|
style={styles.input} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
- `TouchableOpacity` is a wrapper for making elements like `View` and `Text` respond properly to touch events. It provides feedback by reducing the opacity of the wrapped component when pressed. |
||||||
|
|
||||||
|
```javascript |
||||||
|
<TouchableOpacity onPress={this.onButtonPress}> |
||||||
|
<Text style={styles.buttonText}>Press me!</Text> |
||||||
|
</TouchableOpacity> |
||||||
|
``` |
||||||
|
|
||||||
|
- `ScrollView` is a scrollable container that allows users to scroll through its content. It is useful when you have content that exceeds the available screen size. |
||||||
|
|
||||||
|
```javascript |
||||||
|
<ScrollView style={styles.scrollContainer}> |
||||||
|
<Text>Content 1</Text> |
||||||
|
<Text>Content 2</Text> |
||||||
|
{/* ... */} |
||||||
|
</ScrollView> |
||||||
|
``` |
||||||
|
|
||||||
|
- `FlatList` is used to render a list of items using a performant approach. It only renders items that are currently visible on the screen and removes others to save memory. |
||||||
|
|
||||||
|
```javascript |
||||||
|
<FlatList |
||||||
|
data={this.state.data} |
||||||
|
renderItem={({ item }) => <Text>{item.name}</Text>} |
||||||
|
keyExtractor={item => item.id} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
These core components are foundational to creating functional and attractive interfaces for your React Native applications. |
@ -1 +1,42 @@ |
|||||||
# Platform module |
# Platform Module |
||||||
|
|
||||||
|
The Platform module, as the name suggests, is a part of React Native that detects the platform on which the app is running. This enables you to have specific code for either Android or iOS, allowing you to account for platform-specific differences in design or behavior. |
||||||
|
|
||||||
|
To utilize the Platform module, you need to import it and then access the `OS` property. This property returns a string, which denotes the platform — either `'ios'` or `'android'`. |
||||||
|
|
||||||
|
Here's an example: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { Platform } from 'react-native'; |
||||||
|
|
||||||
|
if (Platform.OS === 'ios') { |
||||||
|
console.log('Running on iOS'); |
||||||
|
} else if (Platform.OS === 'android') { |
||||||
|
console.log('Running on Android'); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
For a more elegant way to define platform-specific properties, React Native provides the `Platform.select` method. This method takes an object with keys `'ios'` and `'android'`, representing the respective platforms, and returns the value associated with the current platform. |
||||||
|
|
||||||
|
Here's an example of `Platform.select` in use: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { Platform, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
...Platform.select({ |
||||||
|
ios: { |
||||||
|
backgroundColor: 'red', |
||||||
|
}, |
||||||
|
android: { |
||||||
|
backgroundColor: 'blue', |
||||||
|
}, |
||||||
|
}), |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, the container's background color will be red on iOS and blue on Android. |
||||||
|
|
||||||
|
With the Platform module, you can easily create platform-specific code, enabling you to have the best user experience for each platform. Just remember to import the module and use the provided properties and methods. |
@ -1 +1,68 @@ |
|||||||
# File extensions |
# File Extensions |
||||||
|
|
||||||
|
In React Native, you can write platform-specific code by using specific file extensions. By appending `.android.` or `.ios.` to your file's name, React Native will load the file corresponding to the platform you are running your app on. |
||||||
|
|
||||||
|
There are two main scenarios where you can use this approach: |
||||||
|
|
||||||
|
## Platform-Specific Component Files |
||||||
|
|
||||||
|
You can create separate files for each platform's specific components, keeping the implementation and styling different for Android and iOS. |
||||||
|
|
||||||
|
For example, if you have a `Header` component, you can create two separate files `Header.ios.js` and `Header.android.js`. React Native will automatically pick the right file depending on the platform it's running on. |
||||||
|
|
||||||
|
```javascript |
||||||
|
// Header.ios.js |
||||||
|
import React from 'react'; |
||||||
|
import { View, Text } from 'react-native'; |
||||||
|
|
||||||
|
const Header = () => { |
||||||
|
return ( |
||||||
|
<View style={{ backgroundColor: 'blue' }}> |
||||||
|
<Text>iOS Header</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
export default Header; |
||||||
|
``` |
||||||
|
|
||||||
|
```javascript |
||||||
|
// Header.android.js |
||||||
|
import React from 'react'; |
||||||
|
import { View, Text } from 'react-native'; |
||||||
|
|
||||||
|
const Header = () => { |
||||||
|
return ( |
||||||
|
<View style={{ backgroundColor: 'green' }}> |
||||||
|
<Text>Android Header</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
export default Header; |
||||||
|
``` |
||||||
|
|
||||||
|
## Platform-Specific Code within a File |
||||||
|
|
||||||
|
You can also use the `Platform` module from React Native to determine which platform-specific code to run within a single file. |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { Platform, StyleSheet, Text } from 'react-native'; |
||||||
|
|
||||||
|
const ComponentWithPlatformSpecificCode = () => { |
||||||
|
return <Text style={styles.content}>Hello World!</Text>; |
||||||
|
}; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
content: { |
||||||
|
color: Platform.select({ |
||||||
|
ios: 'blue', |
||||||
|
android: 'green', |
||||||
|
}), |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default ComponentWithPlatformSpecificCode; |
||||||
|
``` |
||||||
|
|
||||||
|
Using file extensions and the `Platform` module, you can create tailor-made components and features for different platforms while maintaining a clean and organized codebase. |
@ -1 +1,96 @@ |
|||||||
# React native web |
# React Native Web |
||||||
|
|
||||||
|
React Native Web is an extension of React Native which allows you to run your React Native apps not only on iOS and Android devices, but also on the web. It uses the same components and APIs you're familiar with in React Native, but renders them into the DOM of a webpage instead of native UI elements. |
||||||
|
|
||||||
|
The main goal of React Native Web is to provide a consistent developer experience across platforms, reducing the effort needed to build and maintain multi-platform apps. |
||||||
|
|
||||||
|
## Platform-specific Code |
||||||
|
|
||||||
|
While React Native Web is designed to provide a consistent experience across platforms, there may still be cases where you want to use platform-specific code for an improved native experience. |
||||||
|
|
||||||
|
For example, let's say you have a React Native app with the following styles: |
||||||
|
|
||||||
|
```javascript |
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
justifyContent: 'center', |
||||||
|
alignItems: 'center', |
||||||
|
}, |
||||||
|
text: { |
||||||
|
fontSize: 16, |
||||||
|
color: 'blue', |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
Now, let's say you want to apply some platform-specific styling. You can create separate stylesheets for each platform, like `styles.native.js` and `styles.web.js`. The contents of `styles.native.js` would look like this: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
export default StyleSheet.create({ |
||||||
|
container: { |
||||||
|
// Your platform-specific styles |
||||||
|
}, |
||||||
|
text: { |
||||||
|
// Your platform-specific styles |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
And the contents of `styles.web.js` would look like this: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
export default StyleSheet.create({ |
||||||
|
container: { |
||||||
|
// Your platform-specific styles |
||||||
|
}, |
||||||
|
text: { |
||||||
|
// Your platform-specific styles |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
Then, in your main component file, you can import the appropriate styles for each platform automatically: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import styles from './styles'; |
||||||
|
|
||||||
|
// Now, your styles are platform-specific! |
||||||
|
``` |
||||||
|
|
||||||
|
This way, you can cater your styles to the specific platform your app is running on, without having to clutter your main component code with conditional styling. |
||||||
|
|
||||||
|
React Native Web also provides a utility called `Platform` that you can use to determine the current platform and apply platform-specific code directly: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { Platform, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
...Platform.select({ |
||||||
|
web: { |
||||||
|
// Web-specific styles |
||||||
|
}, |
||||||
|
native: { |
||||||
|
// Native-specific styles |
||||||
|
}, |
||||||
|
}), |
||||||
|
}, |
||||||
|
text: { |
||||||
|
...Platform.select({ |
||||||
|
web: { |
||||||
|
// Web-specific styles |
||||||
|
}, |
||||||
|
native: { |
||||||
|
// Native-specific styles |
||||||
|
}, |
||||||
|
}), |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
With these techniques, you'll be able to create tailored experiences across different platforms while maintaining a consistent development experience. |
@ -1 +1,39 @@ |
|||||||
# Platform specific code |
# Platform Specific Code |
||||||
|
|
||||||
|
In React Native, you might need to maintain certain parts of your application differently for iOS and Android. This is where "Platform Specific Code" comes into play. There are two ways you can achieve this: |
||||||
|
|
||||||
|
## Platform module |
||||||
|
|
||||||
|
React Native provides a `Platform` module that can be used to detect which platform your code is running on (iOS or Android). This can be helpful when you have minor platform differences in your code execution, component styles, or API calls. |
||||||
|
|
||||||
|
**Example:** |
||||||
|
|
||||||
|
```javascript |
||||||
|
import { Platform, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
...Platform.select({ |
||||||
|
ios: { |
||||||
|
backgroundColor: 'red', |
||||||
|
}, |
||||||
|
android: { |
||||||
|
backgroundColor: 'blue', |
||||||
|
}, |
||||||
|
}), |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
## File extensions |
||||||
|
|
||||||
|
Another way to handle platform-specific logic is by using file extensions like `.ios.js` and `.android.js`. By naming your files with these extensions, React Native will automatically pick up the appropriate file based on the platform the app is running on. |
||||||
|
|
||||||
|
**Example:** |
||||||
|
|
||||||
|
Let's say you have two files in your project, `Header.ios.js` and `Header.android.js`. When you import the `Header` component in your code, React Native will automatically import the correct file for the platform. |
||||||
|
|
||||||
|
```javascript |
||||||
|
// App.js |
||||||
|
import Header from './Header'; |
||||||
|
``` |
@ -1 +1,88 @@ |
|||||||
# Stylesheets |
# Stylesheets in React Native |
||||||
|
|
||||||
|
In React Native, stylesheets are objects that define the appearance of components. They provide a way to separate styling from the component's logic. Stylesheets are created using `StyleSheet.create` method, which ensures a standardized and efficient way to manage styles for your components. |
||||||
|
|
||||||
|
## Creating a stylesheet |
||||||
|
|
||||||
|
You can create a stylesheet by importing `StyleSheet` from 'react-native', and then defining your styles using `StyleSheet.create` method. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
justifyContent: 'center', |
||||||
|
alignItems: 'center', |
||||||
|
backgroundColor: '#F5FCFF', |
||||||
|
}, |
||||||
|
text: { |
||||||
|
fontSize: 20, |
||||||
|
textAlign: 'center', |
||||||
|
margin: 10, |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
## Applying styles to components |
||||||
|
|
||||||
|
To apply styles, simply reference the style object from your stylesheet using `styles.styleName`. For example: |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { View, Text, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
return ( |
||||||
|
<View style={styles.container}> |
||||||
|
<Text style={styles.text}>Hello, React Native!</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
justifyContent: 'center', |
||||||
|
alignItems: 'center', |
||||||
|
backgroundColor: '#F5FCFF', |
||||||
|
}, |
||||||
|
text: { |
||||||
|
fontSize: 20, |
||||||
|
textAlign: 'center', |
||||||
|
margin: 10, |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
## Combining styles |
||||||
|
|
||||||
|
You can combine multiple styles by passing an array of styles to the `style` prop of a component. The last style in the array takes precedence if there are conflicting styles. |
||||||
|
|
||||||
|
```jsx |
||||||
|
<View style={[styles.container, styles.backgroundRed]}> |
||||||
|
<Text style={styles.text}>Hello, React Native!</Text> |
||||||
|
</View> |
||||||
|
|
||||||
|
// Adding backgroundRed to the existing styles |
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
justifyContent: 'center', |
||||||
|
alignItems: 'center', |
||||||
|
backgroundColor: '#F5FCFF', |
||||||
|
}, |
||||||
|
text: { |
||||||
|
fontSize: 20, |
||||||
|
textAlign: 'center', |
||||||
|
margin: 10, |
||||||
|
}, |
||||||
|
backgroundRed: { |
||||||
|
backgroundColor: 'red', |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
That's a brief summary of stylesheets in React Native. You can now create, apply, and combine styles for your React Native components. |
@ -1 +1,57 @@ |
|||||||
# Layouts |
# Layouts in React Native |
||||||
|
|
||||||
|
In React Native, layouts are primarily managed using the Flexbox styling system. Flexbox is a powerful and flexible layout system that allows you to create responsive and complex UIs using a set of simple rules. |
||||||
|
|
||||||
|
## Flexbox |
||||||
|
|
||||||
|
Flexbox consists of three key elements: the `container`, `main axis`, and `cross axis`. |
||||||
|
- The `container` is the parent flex container that holds and distributes all the child elements. |
||||||
|
- The `main axis` is the primary direction of the layout (horizontal or vertical). |
||||||
|
- The `cross axis` is the perpendicular direction, opposite of the main axis. |
||||||
|
|
||||||
|
Here are some of the most commonly used Flexbox styles: |
||||||
|
|
||||||
|
- **`flexDirection`**: This style specifies the primary axis using four possible values: `row`, `row-reverse`, `column`, or `column-reverse`. |
||||||
|
```jsx |
||||||
|
<View style={{flexDirection: 'row'}}> |
||||||
|
<Text>First child</Text> |
||||||
|
<Text>Second child</Text> |
||||||
|
</View> |
||||||
|
``` |
||||||
|
|
||||||
|
- **`alignItems`**: This style is used to align the child items along the cross-axis. It uses the values `flex-start`, `flex-end`, `center`, `stretch`, or `baseline`. |
||||||
|
```jsx |
||||||
|
<View style={{flexDirection: 'row', alignItems: 'center'}}> |
||||||
|
<Text>First child</Text> |
||||||
|
<Text>Second child</Text> |
||||||
|
</View> |
||||||
|
``` |
||||||
|
|
||||||
|
- **`justifyContent`**: This style is used to align the child items along the main axis. It accepts the values `flex-start`, `flex-end`, `center`, `space-between`, or `space-around`. |
||||||
|
```jsx |
||||||
|
<View style={{flexDirection: 'row', justifyContent: 'space-between'}}> |
||||||
|
<Text>First child</Text> |
||||||
|
<Text>Second child</Text> |
||||||
|
</View> |
||||||
|
``` |
||||||
|
|
||||||
|
- **`flexWrap`**: Set to either `wrap` or `nowrap` to specify if child items should wrap around to the next line when there's not enough space on the current line. |
||||||
|
```jsx |
||||||
|
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}> |
||||||
|
<Text>First child</Text> |
||||||
|
<Text>Second child</Text> |
||||||
|
<Text>Third child</Text> |
||||||
|
</View> |
||||||
|
``` |
||||||
|
|
||||||
|
- **`flex`**: This style determines how the child items grow or shrink when there's remaining space in the container. It's a shorthand for `flex-grow`, `flex-shrink`, and `flex-basis`. |
||||||
|
```jsx |
||||||
|
<View style={{flexDirection: 'row'}}> |
||||||
|
<Text style={{flex: 1}}>First child</Text> |
||||||
|
<Text style={{flex: 2}}>Second child</Text> |
||||||
|
</View> |
||||||
|
``` |
||||||
|
|
||||||
|
You can use these styles in various combinations to create flexible layouts in React Native. Flexbox makes it easy to create responsive UIs that adapt to changes in screen size or orientation. Note that some of these styles might not work as expected in React Native compared to in CSS for the web, but the overall concepts remain the same. |
||||||
|
|
||||||
|
To learn more about these styling properties, you can refer to the [official React Native documentation](https://reactnative.dev/docs/flexbox). |
@ -1 +1,89 @@ |
|||||||
# Accessibility |
# Accessibility |
||||||
|
|
||||||
|
Accessibility (a11y) in React Native allows you to create applications that are usable to everyone, including people with disabilities. It provides a set of attributes and APIs to customize UI components by considering diverse user needs. |
||||||
|
|
||||||
|
## Accessibility Props |
||||||
|
|
||||||
|
React Native provides several accessibility properties that can be applied to components for enhancing their a11y features: |
||||||
|
|
||||||
|
`accessible` : (Boolean) - Indicates if the element can be focused by screen readers. |
||||||
|
```jsx |
||||||
|
<TouchableOpacity accessible={true} /> |
||||||
|
``` |
||||||
|
|
||||||
|
`accessibilityLabel` : (String) - Used by the screen reader to describe the element to the user. |
||||||
|
```jsx |
||||||
|
<TouchableOpacity accessibilityLabel="Tap me!"> |
||||||
|
``` |
||||||
|
|
||||||
|
`accessibilityHint` : (String) - Gives a hint to the user of the components behavior. |
||||||
|
```jsx |
||||||
|
<TouchableOpacity accessibilityHint="Tapping this button will show a welcome text"> |
||||||
|
``` |
||||||
|
|
||||||
|
`accessibilityRole` : (String) - Describes the role of the element for the screen reader. |
||||||
|
```jsx |
||||||
|
<TextInput accessibilityRole="search" /> |
||||||
|
``` |
||||||
|
|
||||||
|
`accessibilityValue` : (Object with properties: min, max, now) - Defines the accessibility values for elements such as progress bars or sliders, among others. |
||||||
|
|
||||||
|
```jsx |
||||||
|
<Slider |
||||||
|
accessibilityValue={{ |
||||||
|
min: 0, |
||||||
|
max: 100, |
||||||
|
now: 50, |
||||||
|
}} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
`accessibilityState` : (Object) - Represents the current state of the component. |
||||||
|
```jsx |
||||||
|
<TouchableOpacity |
||||||
|
accessibilityState={{ |
||||||
|
disabled: false, |
||||||
|
selected: true, |
||||||
|
}} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
`accessibilityActions` and `onAccessibilityAction` are used to create custom actions. |
||||||
|
```jsx |
||||||
|
import { AccessibilityInfo, Text, View } from 'react-native'; |
||||||
|
|
||||||
|
function CustomButton() { |
||||||
|
const [count, setCount] = React.useState(0); |
||||||
|
|
||||||
|
const onIncrement = () => { |
||||||
|
setCount(count + 1); |
||||||
|
}; |
||||||
|
|
||||||
|
React.useEffect(() => { |
||||||
|
const announce = () => { |
||||||
|
AccessibilityInfo.announceForAccessibility(`Count raised to ${count}`); |
||||||
|
}; |
||||||
|
announce(); |
||||||
|
}, [count]); |
||||||
|
|
||||||
|
return ( |
||||||
|
<View |
||||||
|
accessible={true} |
||||||
|
accessibilityActions={[ |
||||||
|
{ name: "increment", label: "increase count" }, |
||||||
|
]} |
||||||
|
onAccessibilityAction={(event) => { |
||||||
|
switch (event.nativeEvent.actionName) { |
||||||
|
case "increment": |
||||||
|
onIncrement(); |
||||||
|
break; |
||||||
|
} |
||||||
|
}} |
||||||
|
> |
||||||
|
<Text>Increment Counter: {count}</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
Of course, different platforms may have some exclusive accessibility properties, which can be found in the [official React Native documentation](https://reactnative.dev/docs/accessibility). |
@ -1 +1,87 @@ |
|||||||
# Styling |
# Styling |
||||||
|
|
||||||
|
Styling in React Native is accomplished through JavaScript and uses a subset of CSS properties. Unlike CSS in web development, React Native has its own set of components and styling rules. The main components used for styling are `StyleSheet`, `View`, and `Text`. |
||||||
|
|
||||||
|
## StyleSheet |
||||||
|
|
||||||
|
`StyleSheet` is a module provided by React Native to manage and optimize styles. It is similar to a CSS stylesheet and helps in creating and working with multiple styles efficiently. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { StyleSheet, View, Text } from 'react-native'; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
backgroundColor: '#fff', |
||||||
|
alignItems: 'center', |
||||||
|
justifyContent: 'center', |
||||||
|
}, |
||||||
|
text: { |
||||||
|
fontSize: 20, |
||||||
|
fontWeight: 'bold', |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
## View and Text components |
||||||
|
|
||||||
|
`View` and `Text` components are the basic building blocks for creating a user interface in React Native. They are used to add structure and style to the layout. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { StyleSheet, View, Text } from 'react-native'; |
||||||
|
|
||||||
|
export default function App() { |
||||||
|
return ( |
||||||
|
<View style={styles.container}> |
||||||
|
<Text style={styles.text}>Hello, React Native!</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
backgroundColor: '#fff', |
||||||
|
alignItems: 'center', |
||||||
|
justifyContent: 'center', |
||||||
|
}, |
||||||
|
text: { |
||||||
|
fontSize: 20, |
||||||
|
fontWeight: 'bold', |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
## Inline styles |
||||||
|
|
||||||
|
In some cases, you might prefer to apply styles directly to a component using inline styling. However, it is not recommended for larger applications due to performance issues. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { View, Text } from 'react-native'; |
||||||
|
|
||||||
|
export default function App() { |
||||||
|
return ( |
||||||
|
<View |
||||||
|
style={{ |
||||||
|
flex: 1, |
||||||
|
backgroundColor: '#fff', |
||||||
|
alignItems: 'center', |
||||||
|
justifyContent: 'center', |
||||||
|
}} |
||||||
|
> |
||||||
|
<Text |
||||||
|
style={{ |
||||||
|
fontSize: 20, |
||||||
|
fontWeight: 'bold', |
||||||
|
}} |
||||||
|
> |
||||||
|
Hello, React Native! |
||||||
|
</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
In summary, styling in React Native is done through JavaScript using a subset of CSS properties. The main components used for styling are `StyleSheet`, `View`, and `Text`. You can also use inline styles when necessary, although it's not recommended for performance reasons. |
@ -1 +1,101 @@ |
|||||||
# Connectivity |
# Connectivity Status |
||||||
|
|
||||||
|
Connectivity refers to the mechanisms that allow data transfer between your React Native app and external resources through various means of communication. It is essential to ensure efficient communication with APIs, servers, and external systems, to update your app's data, fetching content or enabling real-time interactions. |
||||||
|
|
||||||
|
## Networking Types |
||||||
|
|
||||||
|
-**Fetch API**: The Fetch API is a native JavaScript way to make HTTP requests that can be used in React Native. It provides a simple interface for fetching resources and returns a Promise that resolves to the response of the request. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```js |
||||||
|
fetch('https://api.example.com/data') |
||||||
|
.then((response) => response.json()) |
||||||
|
.then((data) => console.log(data)) |
||||||
|
.catch((error) => console.error(error)); |
||||||
|
``` |
||||||
|
|
||||||
|
- **XMLHttpRequest**: React Native has built-in support for XMLHttpRequest, which is a popular choice for communication with APIs. It can deal with various data types, like XML, JSON, or even binary data. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```js |
||||||
|
var xhr = new XMLHttpRequest(); |
||||||
|
xhr.onreadystatechange = function () { |
||||||
|
if (xhr.readyState === 4 && xhr.status === 200) { |
||||||
|
console.log(xhr.responseText); |
||||||
|
} |
||||||
|
}; |
||||||
|
xhr.open('GET', 'https://api.example.com/data', true); |
||||||
|
xhr.send(); |
||||||
|
``` |
||||||
|
|
||||||
|
- **WebSockets**: WebSockets allow you to establish real-time communication between your React Native app and a server. It provides a two-way communication mechanism over a single, long-held TCP connection, enabling real-time data transfer. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```js |
||||||
|
const webSocket = new WebSocket('wss://example.com/ws'); |
||||||
|
|
||||||
|
webSocket.onopen = () => { |
||||||
|
webSocket.send('Hello from React Native app!'); |
||||||
|
}; |
||||||
|
|
||||||
|
webSocket.onmessage = (event) => { |
||||||
|
console.log('Message from the server:', event.data); |
||||||
|
}; |
||||||
|
|
||||||
|
webSocket.onerror = (error) => { |
||||||
|
console.error('WebSocket error:', error); |
||||||
|
}; |
||||||
|
|
||||||
|
webSocket.onclose = (event) => { |
||||||
|
console.log('WebSocket connection closed:', event.code, event.reason); |
||||||
|
}; |
||||||
|
``` |
||||||
|
|
||||||
|
## Libraries for Networking |
||||||
|
|
||||||
|
In addition to the built-in networking types, you can use external libraries to simplify networking tasks, such as: |
||||||
|
|
||||||
|
- **Axios**: Axios is a promise-based HTTP client for the browser and Node.js environment. It supports various features like intercepting requests and responses, timeouts, and handling retries. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```js |
||||||
|
import axios from 'axios'; |
||||||
|
|
||||||
|
axios |
||||||
|
.get('https://api.example.com/data') |
||||||
|
.then((response) => console.log(response.data)) |
||||||
|
.catch((error) => console.error(error)); |
||||||
|
``` |
||||||
|
|
||||||
|
- **Apollo Client**: Apollo Client is a comprehensive GraphQL client that helps you manage your data in a better and more efficient way, making it easier to build powerful and scalable applications. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```js |
||||||
|
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; |
||||||
|
|
||||||
|
const client = new ApolloClient({ |
||||||
|
uri: 'https://api.example.com/graphql', |
||||||
|
cache: new InMemoryCache(), |
||||||
|
}); |
||||||
|
|
||||||
|
client |
||||||
|
.query({ |
||||||
|
query: gql` |
||||||
|
query GetData { |
||||||
|
data { |
||||||
|
id |
||||||
|
name |
||||||
|
} |
||||||
|
} |
||||||
|
`, |
||||||
|
}) |
||||||
|
.then((result) => console.log(result)) |
||||||
|
.catch((error) => console.error(error)); |
||||||
|
``` |
||||||
|
|
||||||
|
By understanding these options, you can choose the most appropriate connectivity method for your React Native app, and efficiently communicate with APIs, servers, and external systems. |
@ -1 +1,39 @@ |
|||||||
# Fetch |
# Fetch |
||||||
|
|
||||||
|
*Fetch* is a JavaScript function available in React Native that is used to make network requests, similar to XMLHttpRequest in web applications. It allows you to handle requests and retrieve data from APIs or other sources. The Fetch API is built on Promises, making it simple to handle success and error cases. |
||||||
|
|
||||||
|
## Usage |
||||||
|
|
||||||
|
Here's a basic example demonstrating how to use fetch to make a GET request: |
||||||
|
|
||||||
|
```javascript |
||||||
|
fetch('https://jsonplaceholder.typicode.com/todos/1') |
||||||
|
.then(response => response.json()) |
||||||
|
.then(data => console.log(data)) |
||||||
|
.catch(error => console.error(error)); |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, we are using `fetch()` to make a GET request to a sample API. The function `fetch()` returns a Promise that resolves to the Response object representing the response to the request. Using `then()`, we manage the response and extract the JSON data from it. If an error occurs, we catch it with `catch()`. |
||||||
|
|
||||||
|
## POST Request |
||||||
|
|
||||||
|
To make a POST request using fetch, you need to provide an additional object with the `method`, `headers`, and `body` properties: |
||||||
|
|
||||||
|
```javascript |
||||||
|
fetch('https://jsonplaceholder.typicode.com/todos', { |
||||||
|
method: 'POST', |
||||||
|
headers: { |
||||||
|
'Accept': 'application/json', |
||||||
|
'Content-Type': 'application/json' |
||||||
|
}, |
||||||
|
body: JSON.stringify({ |
||||||
|
title: 'New Task', |
||||||
|
completed: false |
||||||
|
}) |
||||||
|
}) |
||||||
|
.then(response => response.json()) |
||||||
|
.then(data => console.log(data)) |
||||||
|
.catch(error => console.error(error)); |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, we are making a POST request to add a new task to the sample API. The `method` property is set to 'POST', and `headers` define the content type as 'application/json'. The `body` property contains the new task in JSON format, which needs to be converted to a string using `JSON.stringify()`. Just like the GET request, we handle the response and catch any errors that occur. |
@ -1 +1,67 @@ |
|||||||
# Websockets |
# Websockets |
||||||
|
|
||||||
|
WebSockets are a protocol that allows full-duplex communication between a client and a server over a single, long-lived connection. They are useful when real-time communication is needed, such as in chat applications, online gaming, or financial trading platforms. |
||||||
|
|
||||||
|
## Setting up a WebSocket connection |
||||||
|
|
||||||
|
In React Native, you can use the `WebSocket` API to establish a WebSocket connection with the server. Here's an example of how to open a WebSocket connection: |
||||||
|
|
||||||
|
```javascript |
||||||
|
const webSocket = new WebSocket('ws://my-websocket-server.com'); |
||||||
|
``` |
||||||
|
|
||||||
|
## Receiving and sending messages |
||||||
|
|
||||||
|
You can handle the different events associated with a WebSocket connection by attaching event listeners to the `WebSocket` instance. |
||||||
|
|
||||||
|
### Handling connection |
||||||
|
|
||||||
|
To handle connection establishment, you can use the `onopen` event listener: |
||||||
|
|
||||||
|
```javascript |
||||||
|
webSocket.onopen = (event) => { |
||||||
|
console.log('WebSocket connection opened:', event); |
||||||
|
}; |
||||||
|
``` |
||||||
|
|
||||||
|
### Handling incoming messages |
||||||
|
|
||||||
|
To receive messages from the server, you can use the `onmessage` event listener: |
||||||
|
|
||||||
|
```javascript |
||||||
|
webSocket.onmessage = (event) => { |
||||||
|
console.log('Received from server:', event.data); |
||||||
|
}; |
||||||
|
``` |
||||||
|
|
||||||
|
### Sending messages to the server |
||||||
|
|
||||||
|
To send messages to the server, you can use the `send` method: |
||||||
|
|
||||||
|
```javascript |
||||||
|
webSocket.send('Hello server'); |
||||||
|
``` |
||||||
|
|
||||||
|
### Handling connection error and closure |
||||||
|
|
||||||
|
You can catch connection errors and closure events using the `onerror` and `onclose` event listeners: |
||||||
|
|
||||||
|
```javascript |
||||||
|
webSocket.onerror = (event) => { |
||||||
|
console.log('WebSocket error:', event); |
||||||
|
}; |
||||||
|
|
||||||
|
webSocket.onclose = (event) => { |
||||||
|
console.log('WebSocket connection closed:', event); |
||||||
|
}; |
||||||
|
``` |
||||||
|
|
||||||
|
## Closing the WebSocket connection |
||||||
|
|
||||||
|
To close the WebSocket connection, you can use the `close` method: |
||||||
|
|
||||||
|
```javascript |
||||||
|
webSocket.close(); |
||||||
|
``` |
||||||
|
|
||||||
|
That's a brief summary of using WebSockets in React Native! Don't forget to handle various edge cases such as connection loss, reconnection, and graceful shutdowns in a real-world application. |
@ -1 +1,20 @@ |
|||||||
# Networking |
# Networking |
||||||
|
|
||||||
|
React Native provides the ability to make network requests and manage data fetched from remote sources. Networking can be accomplished through the following techniques: |
||||||
|
|
||||||
|
## Fetch |
||||||
|
|
||||||
|
The `fetch` function is a top-level API to make HTTP requests. It is a promise-based API for handling network requests. It allows you to fetch resources (typically JSON data) from a provided URL. |
||||||
|
|
||||||
|
### Fetch Example |
||||||
|
|
||||||
|
```jsx |
||||||
|
fetch('https://jsonplaceholder.typicode.com/todos/1') |
||||||
|
.then((response) => response.json()) |
||||||
|
.then((json) => console.log(json)) |
||||||
|
.catch((error) => console.error(error)); |
||||||
|
``` |
||||||
|
|
||||||
|
## Axios |
||||||
|
|
||||||
|
Axios is a popular and widely-used library for making HTTP requests in javascript applications. It's promise-based and provides a simple-to-use API. |
@ -1 +1,8 @@ |
|||||||
# Push notifications |
# Push Notifications in React Native |
||||||
|
|
||||||
|
Push notifications are a way to engage and retain users by delivering alerts, messages, or other information directly to their devices, even when the app is not running. They are an essential feature in modern mobile applications as they help keep users informed about important updates and allow developers to encourage user interaction with the app. |
||||||
|
|
||||||
|
In React Native, you can implement push notifications using third-party libraries or services. Some popular options are: |
||||||
|
|
||||||
|
- Firebase Cloud Messaging (FCM) for both Android and iOS |
||||||
|
- Apple Push Notification Service (APNs) for iOS |
@ -1 +1,77 @@ |
|||||||
# Touchables |
# Touchables |
||||||
|
|
||||||
|
In React Native, `Touchable` components are used to handle user interactions like taps, long presses, and double-taps on the appropriate elements. The main Touchable components include: |
||||||
|
|
||||||
|
- `TouchableOpacity`: The opacity of the wrapped view is decreased when it's active. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { TouchableOpacity } from 'react-native'; |
||||||
|
|
||||||
|
<TouchableOpacity |
||||||
|
onPress={() => { |
||||||
|
alert('Tapped!'); |
||||||
|
}} |
||||||
|
> |
||||||
|
<Text>Tap me</Text> |
||||||
|
</TouchableOpacity> |
||||||
|
``` |
||||||
|
|
||||||
|
- `TouchableHighlight`: The view is highlighted with a specified color when active. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { TouchableHighlight } from 'react-native'; |
||||||
|
|
||||||
|
<TouchableHighlight |
||||||
|
onPress={() => { |
||||||
|
alert('Tapped!'); |
||||||
|
}} |
||||||
|
underlayColor="gray" |
||||||
|
> |
||||||
|
<Text>Tap me</Text> |
||||||
|
</TouchableHighlight> |
||||||
|
``` |
||||||
|
|
||||||
|
- `TouchableWithoutFeedback`: No visual feedback is provided when the view is tapped. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { TouchableWithoutFeedback } from 'react-native'; |
||||||
|
|
||||||
|
<TouchableWithoutFeedback |
||||||
|
onPress={() => { |
||||||
|
alert('Tapped!'); |
||||||
|
}} |
||||||
|
> |
||||||
|
<Text>Tap me</Text> |
||||||
|
</TouchableWithoutFeedback> |
||||||
|
``` |
||||||
|
|
||||||
|
- `TouchableNativeFeedback`: Provides additional Android-specific visual feedback. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { TouchableNativeFeedback } from 'react-native'; |
||||||
|
|
||||||
|
<TouchableNativeFeedback |
||||||
|
onPress={() => { |
||||||
|
alert('Tapped!'); |
||||||
|
}} |
||||||
|
> |
||||||
|
<Text>Tap me</Text> |
||||||
|
</TouchableNativeFeedback> |
||||||
|
``` |
||||||
|
|
||||||
|
- `TouchableHighlight`: The view will slightly change scale when pressed. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { TouchableScale } from 'react-native-touchable-scale'; |
||||||
|
|
||||||
|
<TouchableScale |
||||||
|
onPress={() => { |
||||||
|
alert('Tapped!'); |
||||||
|
}} |
||||||
|
activeScale={0.9} |
||||||
|
> |
||||||
|
<Text>Tap me</Text> |
||||||
|
</TouchableScale> |
||||||
|
``` |
||||||
|
|
||||||
|
Each of these components is from the `react-native` package, except `TouchableScale` which is from `react-native-touchable-scale`. They can be used interchangeably depending on the type of interaction you want to provide. The main `props` used with these components are `onPress`, `onLongPress`, and some component-specific ones like `underlayColor` for `TouchableHighlight`. |
@ -1 +1,84 @@ |
|||||||
# Gesture |
# Gesture Responder System |
||||||
|
|
||||||
|
Gesture handling is an essential and powerful feature in React Native that helps create interactive and responsive user interfaces. React Native provides several built-in components and libraries to recognize and respond to different types of user gestures. Some of the common gestures include tapping, swiping, dragging, and pinching. |
||||||
|
|
||||||
|
## Touchable Components |
||||||
|
|
||||||
|
React Native offers several "Touchable" components to handle simple gestures like tapping, long-pressing, and double-tapping. Some of these components include: |
||||||
|
|
||||||
|
- **TouchableOpacity**: This component allows you to specify a function that gets executed when the touchable area is pressed. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { TouchableOpacity, Text } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => ( |
||||||
|
<TouchableOpacity onPress={() => console.log('Pressed!')}> |
||||||
|
<Text>Press me!</Text> |
||||||
|
</TouchableOpacity> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
- **TouchableHighlight**: This component highlights the touchable area by changing the background color when it's pressed. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { TouchableHighlight, Text } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => ( |
||||||
|
<TouchableHighlight onPress={() => console.log('Pressed!')} underlayColor="lightblue"> |
||||||
|
<Text>Press me!</Text> |
||||||
|
</TouchableHighlight> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
- **TouchableWithoutFeedback**: This component provides a simple wrapper for touchable components without feedback. This is useful for customizing feedback of touchable components. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React from 'react'; |
||||||
|
import { TouchableWithoutFeedback, View, Text } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => ( |
||||||
|
<TouchableWithoutFeedback onPress={() => console.log('Pressed!')}> |
||||||
|
<View> |
||||||
|
<Text>Press me!</Text> |
||||||
|
</View> |
||||||
|
</TouchableWithoutFeedback> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
## PanResponder |
||||||
|
|
||||||
|
For more advanced gesture handling, React Native's `PanResponder` can be used. It is a flexible and powerful gesture responder system that helps in recognizing and capturing complex gestures involving multiple touches, drags, and pans. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React, { useRef } from 'react'; |
||||||
|
import { PanResponder, View, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
const App = () => { |
||||||
|
const panResponder = useRef( |
||||||
|
PanResponder.create({ |
||||||
|
onStartShouldSetPanResponder: (evt, gestureState) => true, |
||||||
|
onPanResponderMove: (evt, gestureState) => { |
||||||
|
console.log('Gesture moved', gestureState); |
||||||
|
}, |
||||||
|
onPanResponderRelease: (evt, gestureState) => { |
||||||
|
console.log('Gesture ended', gestureState); |
||||||
|
}, |
||||||
|
}) |
||||||
|
).current; |
||||||
|
|
||||||
|
return <View style={styles.container} {...panResponder.panHandlers} />; |
||||||
|
}; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
backgroundColor: 'lightblue', |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
Using these components and libraries, you can implement a wide range of gesture interactions in your React Native applications to make your user interfaces responsive and intuitive. |
@ -1 +1,92 @@ |
|||||||
# Scrolling swiping |
# Scrolling and Swiping |
||||||
|
|
||||||
|
In React Native, scrolling and swiping interactions can be defined and customized with a set of built-in components. These components are efficient and provide fluid navigation through the elements inside them. |
||||||
|
|
||||||
|
## Scrolling |
||||||
|
|
||||||
|
React Native provides `ScrollView` and `FlatList` components to handle scrolling interactions. Both components have their own use cases. Let's discuss them in detail: |
||||||
|
|
||||||
|
- **ScrollView**: Used for simple and short lists with a known number of elements. It renders all the child elements in memory at once, which can negatively impact performance for longer lists. |
||||||
|
|
||||||
|
Example: |
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { ScrollView, Text } from 'react-native'; |
||||||
|
|
||||||
|
const ScrollViewExample = () => ( |
||||||
|
<ScrollView> |
||||||
|
{['Element 1', 'Element 2', 'Element 3'].map((item, index) => ( |
||||||
|
<Text key={index}>{item}</Text> |
||||||
|
))} |
||||||
|
</ScrollView> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
- **FlatList**: Used for long and complex lists where the number of elements is unknown or potentially infinite. It optimizes performance by rendering only the currently visible elements in the viewport. |
||||||
|
|
||||||
|
Example: |
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { FlatList, Text } from 'react-native'; |
||||||
|
|
||||||
|
const DATA = [ |
||||||
|
{ id: '1', text: 'Element 1' }, |
||||||
|
{ id: '2', text: 'Element 2' }, |
||||||
|
{ id: '3', text: 'Element 3' }, |
||||||
|
]; |
||||||
|
|
||||||
|
const renderItem = ({ item }) => ( |
||||||
|
<Text>{item.text}</Text> |
||||||
|
); |
||||||
|
|
||||||
|
const FlatListExample = () => ( |
||||||
|
<FlatList |
||||||
|
data={DATA} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={(item) => item.id} |
||||||
|
/> |
||||||
|
); |
||||||
|
``` |
||||||
|
|
||||||
|
## Swiping |
||||||
|
|
||||||
|
To implement swiping in React Native, the community-driven package `react-native-gesture-handler` is commonly used. One of its components is `Swipeable`, which allows you to create swipeable elements with custom swipe actions. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React from 'react'; |
||||||
|
import { Text, View } from 'react-native'; |
||||||
|
import { RectButton } from 'react-native-gesture-handler'; |
||||||
|
import Swipeable from 'react-native-gesture-handler/Swipeable'; |
||||||
|
|
||||||
|
const RightActions = (progress, dragX, onPress) => { |
||||||
|
return ( |
||||||
|
<RectButton onPress={onPress}> |
||||||
|
<View> |
||||||
|
<Text>Delete</Text> |
||||||
|
</View> |
||||||
|
</RectButton> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
const SwipeableExample = () => { |
||||||
|
const handleDelete = () => { |
||||||
|
alert('Delete action'); |
||||||
|
}; |
||||||
|
|
||||||
|
return ( |
||||||
|
<Swipeable |
||||||
|
renderRightActions={(progress, dragX) => |
||||||
|
RightActions(progress, dragX, handleDelete) |
||||||
|
} |
||||||
|
> |
||||||
|
<View> |
||||||
|
<Text>Swipeable Element</Text> |
||||||
|
</View> |
||||||
|
</Swipeable> |
||||||
|
); |
||||||
|
}; |
||||||
|
``` |
||||||
|
|
||||||
|
In summary, React Native provides various components for smooth scrolling and swiping interactions. Components like `ScrollView`, `FlatList`, and `react-native-gesture-handler` are essential tools in creating a seamless user experience. |
@ -1 +1,8 @@ |
|||||||
# Screen navigation |
# Screen Navigation |
||||||
|
|
||||||
|
In React Native, navigating from one screen to another is a crucial aspect of app development. The most commonly used navigation libraries are React Navigation and React Native Navigation. |
||||||
|
|
||||||
|
Learn more from the following resources: |
||||||
|
|
||||||
|
- [React Native Navigation](https://github.com/wix/react-native-navigation) |
||||||
|
- [React Navigation](https://reactnavigation.org/) |
@ -1 +1,74 @@ |
|||||||
# Animations |
# Animations |
||||||
|
|
||||||
|
React Native supports two types of animations: `Animated` and `LayoutAnimation`. The `Animated` API provides a basic set of methods for creating and managing animations, while the `LayoutAnimation` API provides a way to animate changes from one layout to another. |
||||||
|
|
||||||
|
## Animated |
||||||
|
|
||||||
|
`Animated` is a declarative API that focuses on handling animation-related calculations. It allows you to create and combine animations with fine-grained control over the specific properties that are being animated. You can use this API to create a variety of effects, such as fading, scaling, and translating components on the screen. |
||||||
|
|
||||||
|
Here's a simple example of how to use `Animated` to move a view across the screen: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React, { Component } from "react"; |
||||||
|
import { Animated, View } from "react-native"; |
||||||
|
|
||||||
|
class MoveView extends Component { |
||||||
|
constructor(props) { |
||||||
|
super(props); |
||||||
|
this.position = new Animated.ValueXY({ x: 0, y: 0 }); |
||||||
|
} |
||||||
|
|
||||||
|
componentDidMount() { |
||||||
|
Animated.timing(this.position, { |
||||||
|
toValue: { x: 100, y: 100 }, |
||||||
|
duration: 1000, |
||||||
|
}).start(); |
||||||
|
} |
||||||
|
|
||||||
|
render() { |
||||||
|
return ( |
||||||
|
<Animated.View style={this.position.getLayout()}> |
||||||
|
{/* Your content here */} |
||||||
|
</Animated.View> |
||||||
|
); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
It creates a new `Animated` value that represents the position of the view and moves it to another location over a duration of 1000 milliseconds. |
||||||
|
|
||||||
|
## LayoutAnimation |
||||||
|
|
||||||
|
`LayoutAnimation` is a higher-level abstraction for animating changes to the layout. Instead of animating individual properties, you define how the changes should occur and React Native takes care of updating the layout accordingly. This is particularly useful for animating multiple components or modifying the layout in response to user interaction, such as adding/removing/reordering items in a list. |
||||||
|
|
||||||
|
Here's an example of how to use `LayoutAnimation` to animate a view when it is added to or removed from a list of items: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import React, { Component } from "react"; |
||||||
|
import { LayoutAnimation, TouchableOpacity, View } from "react-native"; |
||||||
|
|
||||||
|
class ListItem extends Component { |
||||||
|
componentDidMount() { |
||||||
|
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); |
||||||
|
} |
||||||
|
|
||||||
|
componentWillUnmount() { |
||||||
|
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); |
||||||
|
} |
||||||
|
|
||||||
|
render() { |
||||||
|
return ( |
||||||
|
<View style={styles.itemContainer}> |
||||||
|
<TouchableOpacity onPress={this.props.onRemove}> |
||||||
|
{/* Button content here */} |
||||||
|
</TouchableOpacity> |
||||||
|
{/* Item content here */} |
||||||
|
</View> |
||||||
|
); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
In this example, whenever a `ListItem` component is added or removed, the layout will be animated using the preset `easeInEaseOut` configuration. |
||||||
|
|
||||||
|
These two animation methods in React Native help you create smooth, natural-looking animations for a variety of interactions and use cases in your applications. |
@ -1 +1,140 @@ |
|||||||
# Interactions |
# Interactions |
||||||
|
|
||||||
|
Interaction in React Native means dealing with how the user can interact with your application. This typically involves handling touch events, gestures, and animations to provide a more engaging and dynamic user experience. There are several built-in components and libraries available in React Native to help you build interactive elements in your app. |
||||||
|
|
||||||
|
## Touchables |
||||||
|
|
||||||
|
Touchable components are used to recognize various touch events in your application. React Native provides a few touchable components that you can use: |
||||||
|
|
||||||
|
- **TouchableHighlight**: Responds to the press event with a visual effect, such as highlighting the touched area. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { TouchableHighlight, Text } from 'react-native'; |
||||||
|
|
||||||
|
function MyButton() { |
||||||
|
return ( |
||||||
|
<TouchableHighlight onPress={() => console.log('Button pressed')}> |
||||||
|
<Text>Press me!</Text> |
||||||
|
</TouchableHighlight> |
||||||
|
); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
- **TouchableOpacity**: Responds to the press events by making the touched area semi-transparent. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { TouchableOpacity, Text } from 'react-native'; |
||||||
|
|
||||||
|
function MyButton() { |
||||||
|
return ( |
||||||
|
<TouchableOpacity onPress={() => console.log('Button pressed')}> |
||||||
|
<Text>Press me!</Text> |
||||||
|
</TouchableOpacity> |
||||||
|
); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
- **TouchableWithoutFeedback**: Responds to the press events without any visual feedback. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { TouchableWithoutFeedback, Text } from 'react-native'; |
||||||
|
|
||||||
|
function MyButton() { |
||||||
|
return ( |
||||||
|
<TouchableWithoutFeedback onPress={() => console.log('Button pressed')}> |
||||||
|
<Text>Press me!</Text> |
||||||
|
</TouchableWithoutFeedback> |
||||||
|
); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## Gesture Responder System |
||||||
|
|
||||||
|
The Gesture Responder System is a low-level API for capturing touch events and managing touch responsiveness in a React Native application. It allows components to take ownership of touch events and determine how they should be handled. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { View, Text, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
function MyComponent() { |
||||||
|
return ( |
||||||
|
<View |
||||||
|
style={styles.container} |
||||||
|
onStartShouldSetResponder={() => true} |
||||||
|
onResponderGrant={(event) => console.log('Touch started')} |
||||||
|
onResponderMove={(event) => console.log('Touch moving')} |
||||||
|
onResponderRelease={(event) => console.log('Touch released')} |
||||||
|
> |
||||||
|
<Text>Touch me!</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
borderWidth: 1, |
||||||
|
borderColor: 'black', |
||||||
|
padding: 10, |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
## PanResponder |
||||||
|
|
||||||
|
PanResponder is a gesture responder helper that deals with touch events using the Gesture Responder System. It simplifies creating components that respond to various touch events. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { PanResponder, View, Text, StyleSheet } from 'react-native'; |
||||||
|
|
||||||
|
function MyComponent() { |
||||||
|
const panResponder = PanResponder.create({ |
||||||
|
onStartShouldSetPanResponder: () => true, |
||||||
|
onPanResponderGrant: (event) => console.log('Touch started'), |
||||||
|
onPanResponderMove: (event) => console.log('Touch moving'), |
||||||
|
onPanResponderRelease: (event) => console.log('Touch released'), |
||||||
|
}); |
||||||
|
|
||||||
|
return ( |
||||||
|
<View style={styles.container} {...panResponder.panHandlers}> |
||||||
|
<Text>Touch me!</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
borderWidth: 1, |
||||||
|
borderColor: 'black', |
||||||
|
padding: 10, |
||||||
|
}, |
||||||
|
}); |
||||||
|
``` |
||||||
|
|
||||||
|
## Animated |
||||||
|
|
||||||
|
The `Animated` library provides a way to create smooth animations in a React Native application. It can handle various types of animations, such as opacity, scaling, and rotation. |
||||||
|
|
||||||
|
```jsx |
||||||
|
import { Animated, TouchableOpacity } from 'react-native'; |
||||||
|
|
||||||
|
function MyAnimatedComponent() { |
||||||
|
const opacity = new Animated.Value(1); |
||||||
|
|
||||||
|
function animateOpacity() { |
||||||
|
Animated.timing(opacity, { |
||||||
|
toValue: 0, |
||||||
|
duration: 1000, |
||||||
|
useNativeDriver: true, |
||||||
|
}).start(); |
||||||
|
} |
||||||
|
|
||||||
|
return ( |
||||||
|
<TouchableOpacity onPress={animateOpacity}> |
||||||
|
<Animated.View style={{ opacity }}> |
||||||
|
{/* Your content */} |
||||||
|
</Animated.View> |
||||||
|
</TouchableOpacity> |
||||||
|
); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
These components and libraries will help you build more interactive and engaging user experiences in your React Native applications. |
@ -1 +1,56 @@ |
|||||||
# Deep linking |
# Deep Linking |
||||||
|
|
||||||
|
Deep linking is a technique used in mobile applications that allows you to open a specific screen, content, or functionality within the application using a URL or a custom URL scheme. This is useful for providing seamless user experiences by navigating the user directly to the desired part of the app. Deep linking can be triggered by clicking on a link in an email, scanning a QR code, or through a push notification. |
||||||
|
|
||||||
|
There are two types of deep links: |
||||||
|
|
||||||
|
1. **Universal Links** (iOS) / **App Links** (Android): These are HTTPS URLs that allow the user to navigate to a specific screen when the app is installed and fallback to a specified website when the app is not installed. |
||||||
|
2. **Custom URL Schemes**: Unique URLs, like `myapp://my-screen`, that can open the app directly to a specific screen when clicked. |
||||||
|
|
||||||
|
## Handling Deep Links in React Native |
||||||
|
|
||||||
|
In React Native, you can handle deep links using the `Linking` module which provides the necessary methods to work with deep links. |
||||||
|
|
||||||
|
First, you have to import `Linking` from `"react-native"`: |
||||||
|
|
||||||
|
```js |
||||||
|
import { Linking } from 'react-native'; |
||||||
|
``` |
||||||
|
|
||||||
|
To handle deep links, you need to add a listener that will be triggered when the app receives a deep link. You can add the listener in the `componentDidMount` lifecycle method and remove it in the `componentWillUnmount` method. |
||||||
|
|
||||||
|
For example: |
||||||
|
|
||||||
|
```js |
||||||
|
import React from 'react'; |
||||||
|
import { Linking, Text, View } from 'react-native'; |
||||||
|
|
||||||
|
class App extends React.Component { |
||||||
|
componentDidMount() { |
||||||
|
Linking.addEventListener('url', this.handleOpenURL); |
||||||
|
} |
||||||
|
|
||||||
|
componentWillUnmount() { |
||||||
|
Linking.removeEventListener('url', this.handleOpenURL); |
||||||
|
} |
||||||
|
|
||||||
|
handleOpenURL(event) { |
||||||
|
// Handle your deep link logic |
||||||
|
console.log('Received deep link: ', event.url); |
||||||
|
} |
||||||
|
|
||||||
|
render() { |
||||||
|
return ( |
||||||
|
<View> |
||||||
|
<Text>Hello from React Native!</Text> |
||||||
|
</View> |
||||||
|
); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
export default App; |
||||||
|
``` |
||||||
|
|
||||||
|
To work with universal links or app links, you need to configure your app on both iOS and Android. You can follow the official guide [here](https://reactnative.dev/docs/linking). |
||||||
|
|
||||||
|
You can also use popular libraries like `react-navigation` or `react-native-navigation` that provide built-in support for handling deep links in your app. |
@ -1 +1,11 @@ |
|||||||
# Authentication |
# Authentication |
||||||
|
|
||||||
|
Authentication is a crucial aspect of securing your React Native application. It enables you to verify the identity of users and give access to protected resources and features. Here are the common methods used for authentication in React Native: |
||||||
|
|
||||||
|
- JWT Authentication |
||||||
|
- OAuth |
||||||
|
- Simple Token Authentication |
||||||
|
|
||||||
|
Have a look at the following react native page for further details about security. |
||||||
|
|
||||||
|
- [Authentication and Deep Linking](https://reactnative.dev/docs/security#authentication-and-deep-linking) |
@ -1 +1,9 @@ |
|||||||
# Networking |
# Networking |
||||||
|
|
||||||
|
React Native offers various ways to handle networking tasks like making API calls, sending/receiving data from remote servers, and handling different network protocols. |
||||||
|
|
||||||
|
- Fetch |
||||||
|
- HTTP Call Libraries |
||||||
|
- Web Sockets |
||||||
|
|
||||||
|
These are the major ways to handle networking tasks in React Native. Choose the method that best suits your specific use case and allows you to take full advantage of the features offered. |
@ -1 +1 @@ |
|||||||
# Storage |
# Storage |
||||||
|
@ -1 +1,84 @@ |
|||||||
# Security |
# Security |
||||||
|
|
||||||
|
# React Native Security |
||||||
|
|
||||||
|
React Native is a framework for building cross-platform mobile applications using JavaScript and ReactJS. As with any application development, security is a crucial aspect to protect your application data and user information. Here is a brief overview of some React Native security best practices. |
||||||
|
|
||||||
|
## 1. Secure Storage |
||||||
|
Store sensitive data, such as authentication tokens, encryption keys, or user credentials, securely using a storage solution that comes with built-in encryption mechanisms. |
||||||
|
|
||||||
|
### Example: |
||||||
|
For React Native, [react-native-keychain](https://github.com/oblador/react-native-keychain) and [react-native-encrypted-storage](https://github.com/emeraldsanto/react-native-encrypted-storage) are popular libraries handling secure storage. |
||||||
|
|
||||||
|
```javascript |
||||||
|
import * as Keychain from 'react-native-keychain'; |
||||||
|
|
||||||
|
// Save data to the keychain |
||||||
|
await Keychain.setGenericPassword(username, password); |
||||||
|
|
||||||
|
// Retrieve data from the keychain |
||||||
|
const credentials = await Keychain.getGenericPassword(); |
||||||
|
``` |
||||||
|
|
||||||
|
## 2. Secure Communication |
||||||
|
Use HTTPS for network communication with APIs and remote services. This ensures that the data exchanged between server and client is encrypted and secure. |
||||||
|
|
||||||
|
### Example: |
||||||
|
Use the [fetch](https://reactnative.dev/docs/network) method with URLs starting with 'https://'. |
||||||
|
|
||||||
|
```javascript |
||||||
|
const response = await fetch('https://example.com/api/data'); |
||||||
|
const data = await response.json(); |
||||||
|
``` |
||||||
|
|
||||||
|
## 3. Minimize Permissions |
||||||
|
Request only the necessary permissions from the user that your application needs to function, and do this at runtime when the feature actually needs the permission. |
||||||
|
|
||||||
|
### Example: |
||||||
|
Using [react-native-permissions](https://github.com/zoontek/react-native-permissions), you can request permissions when they are needed: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import {check, PERMISSIONS, request, RESULTS} from 'react-native-permissions'; |
||||||
|
|
||||||
|
async function requestLocationPermission() { |
||||||
|
const result = await check(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE); |
||||||
|
|
||||||
|
if (result === RESULTS.DENIED) { |
||||||
|
return await request(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE); |
||||||
|
} |
||||||
|
|
||||||
|
return result; |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## 4. Validate User Input |
||||||
|
Ensure you validate and sanitize all user input before processing it. This helps to prevent potential threats like SQL injection or cross-site scripting (XSS). |
||||||
|
|
||||||
|
### Example: |
||||||
|
Use a validation library like [Yup](https://github.com/jquense/yup) to validate user input. |
||||||
|
|
||||||
|
```javascript |
||||||
|
import * as Yup from 'yup'; |
||||||
|
|
||||||
|
const loginSchema = Yup.object({ |
||||||
|
email: Yup.string().email('Invalid email address').required('Required'), |
||||||
|
password: Yup.string() |
||||||
|
.min(8, 'Password must be at least 8 characters') |
||||||
|
.required('Required'), |
||||||
|
}); |
||||||
|
|
||||||
|
loginSchema.validate({email: 'user@example.com', password: 'password'}); |
||||||
|
``` |
||||||
|
|
||||||
|
## 5. Keep Dependencies Up to Date |
||||||
|
Regularly update your dependencies to ensure they don't contain known security vulnerabilities. Use tools like [npm audit](https://docs.npmjs.com/cli/v7/commands/npm-audit) and [dependabot](https://github.com/dependabot/dependabot-core) to automatically audit and update your dependencies. |
||||||
|
|
||||||
|
### Example: |
||||||
|
Using npm, you can update your dependencies and check for potential vulnerabilities: |
||||||
|
|
||||||
|
```bash |
||||||
|
npm update |
||||||
|
npm audit |
||||||
|
``` |
||||||
|
|
||||||
|
Following these best practices will help you create more secure React Native applications, protecting your application's data and your users' information. |
@ -1 +1,5 @@ |
|||||||
# Async storage |
# react-native-async-storage |
||||||
|
|
||||||
|
An asynchronous, unencrypted, persistent, key-value storage system for React Native. |
||||||
|
|
||||||
|
- [Visit the Documentation](https://github.com/react-native-async-storage/async-storage) |
@ -1 +1,66 @@ |
|||||||
# Expo secure store |
# expo-secure-store |
||||||
|
|
||||||
|
Expo Secure Store is a built-in package provided by the Expo SDK to store encrypted data securely on users' devices. It is a key-value storage system, but it is not designed to store larger amounts of data such as app databases or complex data structures. It is most appropriate for storing secret keys, access tokens, and small user preferences. |
||||||
|
|
||||||
|
First, you need to install the package by running: |
||||||
|
|
||||||
|
```bash |
||||||
|
expo install expo-secure-store |
||||||
|
``` |
||||||
|
|
||||||
|
Then, import the module into your app: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import * as SecureStore from 'expo-secure-store'; |
||||||
|
``` |
||||||
|
|
||||||
|
## Saving Data |
||||||
|
|
||||||
|
To save data to the secure store, use the `setItemAsync` method. It takes two arguments: a key and a value. Both should be strings. |
||||||
|
|
||||||
|
```javascript |
||||||
|
async function saveData() { |
||||||
|
try { |
||||||
|
await SecureStore.setItemAsync('your_key', 'your_value'); |
||||||
|
console.log('Data saved successfully!'); |
||||||
|
} catch (error) { |
||||||
|
console.error('Error saving data:', error); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## Retrieving Data |
||||||
|
|
||||||
|
To retrieve data from the secure store, use the `getItemAsync` method, which takes the key as a parameter and returns a Promise that resolves to the value. |
||||||
|
|
||||||
|
```javascript |
||||||
|
async function getData() { |
||||||
|
try { |
||||||
|
const value = await SecureStore.getItemAsync('your_key'); |
||||||
|
if (value !== null) { |
||||||
|
console.log('Data retrieved:', value); |
||||||
|
} else { |
||||||
|
console.log('No data found with that key.'); |
||||||
|
} |
||||||
|
} catch (error) { |
||||||
|
console.error('Error retrieving data:', error); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## Deleting Data |
||||||
|
|
||||||
|
To delete data from the secure store, use the `deleteItemAsync` method. It takes the key as a parameter. |
||||||
|
|
||||||
|
```javascript |
||||||
|
async function deleteData() { |
||||||
|
try { |
||||||
|
await SecureStore.deleteItemAsync('your_key'); |
||||||
|
console.log('Data deleted successfully!'); |
||||||
|
} catch (error) { |
||||||
|
console.error('Error deleting data:', error); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
Please note that Expo Secure Store uses different security mechanisms based on the platform (iOS or Android). Additionally, while the store is encrypted, remember that it is not foolproof, and a determined attacker may be able to extract data. However, it provides a good balance between security and usability for most use cases. |
@ -1 +1,85 @@ |
|||||||
# Expo file system |
# Expo File System |
||||||
|
|
||||||
|
Expo File System is a universal module that provides access to the file system on the device. Using this module, you can perform various file operations like reading, writing, copying, moving, and deleting files and folders. It also supports reading file metadata and querying file URI. |
||||||
|
|
||||||
|
To use the Expo File System library, you need to install the `expo-file-system` package: |
||||||
|
|
||||||
|
```bash |
||||||
|
expo install expo-file-system |
||||||
|
``` |
||||||
|
|
||||||
|
First, import the `expo-file-system` module: |
||||||
|
|
||||||
|
```javascript |
||||||
|
import * as FileSystem from 'expo-file-system'; |
||||||
|
``` |
||||||
|
|
||||||
|
Here are some examples of how to use the Expo File System: |
||||||
|
|
||||||
|
## Reading a file |
||||||
|
|
||||||
|
```javascript |
||||||
|
async function readFileAsync() { |
||||||
|
const fileUri = FileSystem.documentDirectory + 'myFile.txt'; |
||||||
|
|
||||||
|
try { |
||||||
|
const content = await FileSystem.readAsStringAsync(fileUri); |
||||||
|
console.log('File content:', content); |
||||||
|
} catch (error) { |
||||||
|
console.error('Error while reading file:', error); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## Writing a file |
||||||
|
|
||||||
|
```javascript |
||||||
|
async function writeFileAsync() { |
||||||
|
const fileUri = FileSystem.documentDirectory + 'myFile.txt'; |
||||||
|
const content = 'Hello, World!'; |
||||||
|
|
||||||
|
try { |
||||||
|
await FileSystem.writeAsStringAsync(fileUri, content); |
||||||
|
console.log('File written successfully'); |
||||||
|
} catch (error) { |
||||||
|
console.error('Error while writing file:', error); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## Copying & Moving a file |
||||||
|
|
||||||
|
```javascript |
||||||
|
async function copyAndMoveFileAsync() { |
||||||
|
const srcUri = FileSystem.documentDirectory + 'myFile.txt'; |
||||||
|
const destUri = FileSystem.documentDirectory + 'copiedFile.txt'; |
||||||
|
|
||||||
|
try { |
||||||
|
await FileSystem.copyAsync({ from: srcUri, to: destUri }); |
||||||
|
console.log('File copied successfully'); |
||||||
|
|
||||||
|
const newDestUri = FileSystem.documentDirectory + 'movedFile.txt'; |
||||||
|
await FileSystem.moveAsync({ from: destUri, to: newDestUri }); |
||||||
|
console.log('File moved successfully'); |
||||||
|
} catch (error) { |
||||||
|
console.error('Error while copying/moving file:', error); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## Deleting a file |
||||||
|
|
||||||
|
```javascript |
||||||
|
async function deleteFileAsync() { |
||||||
|
const fileUri = FileSystem.documentDirectory + 'myFile.txt'; |
||||||
|
|
||||||
|
try { |
||||||
|
await FileSystem.deleteAsync(fileUri); |
||||||
|
console.log('File deleted successfully'); |
||||||
|
} catch (error) { |
||||||
|
console.error('Error while deleting file:', error); |
||||||
|
} |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
I hope this brief summary of Expo File System helps you understand its functionality and usage. Remember to visit the [official documentation](https://docs.expo.dev/versions/latest/sdk/filesystem/) for more details and other available features. |
@ -1 +1,8 @@ |
|||||||
# Other storage options |
# Other Storage Options |
||||||
|
|
||||||
|
Besides AsyncStorage, there are other options available for handling data storage in React Native applications. This guide will briefly cover some popular options: Realm, Firebase Realtime Database, and SQLite. |
||||||
|
|
||||||
|
- [Realm](https://github.com/realm/realm-js) |
||||||
|
- [Firebase Realtime Database](https://firebase.google.com/docs/database) |
||||||
|
|
||||||
|
These are just a few examples of additional storage options for React Native. Depending on your requirements, you may choose the one that best fits your project. |
@ -1 +1,5 @@ |
|||||||
# Expo sqlite |
# expo-sqlite |
||||||
|
|
||||||
|
Expo SQLite is a powerful tool for handling local SQLite databases in your React Native application. By using this API, you can create, read, update, and delete data as needed, without writing native code. Expo SQLite is available as part of the [expo-sqlite](https://docs.expo.dev/versions/latest/sdk/sqlite/) package, which provides an easy-to-use interface for SQLite functionalities. |
||||||
|
|
||||||
|
With Expo SQLite, you can efficiently manage SQLite databases within your React Native applications. It enables you to perform various database operations without the need for writing native code. |
@ -1 +1,10 @@ |
|||||||
# Storage |
# Storage |
||||||
|
|
||||||
|
React Native provides a few ways to persist data locally in the app. Here's a brief summary of the storage options available: |
||||||
|
|
||||||
|
- Async Storage |
||||||
|
- Expo Secure Store |
||||||
|
- Expo File System |
||||||
|
- Expo SQLite |
||||||
|
|
||||||
|
Choose the storage option that best fits your app's requirements and use cases. Keep in mind that AsyncStorage and SecureStorage are more suited for small-scale data storage, while Realm and SQLite support more complex storage and querying needs. |
@ -1 +1,10 @@ |
|||||||
# Jest |
# Jest |
||||||
|
|
||||||
|
Jest is a delightful JavaScript Testing Framework with a focus on simplicity. |
||||||
|
It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more! |
||||||
|
|
||||||
|
Visit the following resources to learn more: |
||||||
|
|
||||||
|
- [Official Website](https://jestjs.io/) |
||||||
|
- [Official Documentation](https://jestjs.io/docs/getting-started) |
||||||
|
- [Jest Crash Course - Unit Testing in JavaScript](https://www.youtube.com/watch?v=7r4xVDI2vho) |
||||||
|
@ -1 +1,5 @@ |
|||||||
# React test renderer |
# React Test Renderer |
||||||
|
|
||||||
|
React Test Renderer is a library provided by the React team that allows you to render React components as JavaScript objects without depending on the DOM or a native mobile environment. It can be used to test components in Node.js environments where the actual rendering is not required. |
||||||
|
|
||||||
|
- [React Test Renderer](https://jestjs.io/docs/tutorial-react) |
@ -1 +1,12 @@ |
|||||||
# React native testing library |
# React Native Testing Library |
||||||
|
|
||||||
|
React Native Testing Library (RNTL) is a collection of tools and utilities to test React Native components. It is built on top of the Testing Library ecosystem, designed to work seamlessly with Jest and other testing frameworks. Its primary goal is to enable efficient and effective testing by providing simple and intuitive APIs that promote best practices, like testing UI components in isolation and promoting accessibility checks. |
||||||
|
|
||||||
|
- It encourages testing from a user's perspective, focusing on interaction and accessibility rather than component implementation details. |
||||||
|
- Built-in support for React Native's asynchronous APIs like `act` and `flushMicrotasksQueue`. |
||||||
|
- Provides utility methods to query, fire events, and wait for elements in the components tree. |
||||||
|
|
||||||
|
Follow the links below for more details: |
||||||
|
|
||||||
|
- [React Native Testing Library](https://callstack.github.io/react-native-testing-library/) |
||||||
|
- [React Native Testing Library (Docs)](https://testing-library.com/docs/react-native-testing-library/intro/) |
@ -1 +1,7 @@ |
|||||||
# Detox |
# Detox |
||||||
|
|
||||||
|
Detox is an end-to-end testing framework for React Native applications. It enables you to run tests on an actual device or in a simulator/emulator environment. The goal of Detox is to maintain a high level of confidence in your application's behavior while allowing for quick test runs and easy debugging. |
||||||
|
|
||||||
|
Learn more about Detox from the following links: |
||||||
|
|
||||||
|
- [Detox Official Docs](https://wix.github.io/Detox/) |
@ -1 +1,9 @@ |
|||||||
# Appium |
# Appium |
||||||
|
|
||||||
|
Appium is an open-source test automation framework for mobile devices, targeting native, hybrid, or mobile-web apps for iOS, Android, and Windows platforms. Appium works with multiple programming languages, including JavaScript, Ruby, Python, Java, and C#. |
||||||
|
|
||||||
|
Appium uses the WebDriver protocol, which allows you to write tests that can interact with your app through a series of commands. The WebDriver protocol interprets these commands into actions that are then performed on the app. |
||||||
|
|
||||||
|
Learn more about Appium from the following resources: |
||||||
|
|
||||||
|
- [Appium Documentation](http://appium.io/) |
@ -1 +1,3 @@ |
|||||||
# Testing |
# Testing |
||||||
|
|
||||||
|
When it comes to testing, you can use a combination of Jest, React Test Renderer, React Native Testing Library, Detox and Appium for all sorts of API needs. |
@ -1 +1,57 @@ |
|||||||
# Frame rates |
# Understand Frame Rates |
||||||
|
|
||||||
|
Frame rates represent the number of frames (or images) displayed per second in an animation or video. The performance of a React Native application can be highly impacted by the frame rate, so it is important to optimize your application for the best possible user experience. Higher frame rates provide smoother animations, but may require more system resources. To achieve the desired frame rate, the application should ensure that each frame is computed and rendered within the time budget. |
||||||
|
|
||||||
|
In general, frame rates can be categorized into two types: |
||||||
|
|
||||||
|
- **Static Frame Rate**: This is when your application's frame rate remains constant during its runtime. |
||||||
|
|
||||||
|
- **Adaptive Frame Rate**: This is when your application adjusts the frame rate according to device performance and available resources. |
||||||
|
|
||||||
|
### Animated library |
||||||
|
|
||||||
|
One of the ways to achieve high frame rates and smooth animations in React Native is by using the `Animated` library. This library provides a set of methods and components that help you manage animations efficiently. By using the `Animated` library, you can define animations declaratively, avoid unnecessary render cycles, and utilize the native driver to offload animation from the JavaScript thread. |
||||||
|
|
||||||
|
Here's an example of using the `Animated` library to create a simple fade-in animation: |
||||||
|
|
||||||
|
```jsx |
||||||
|
import React, { useEffect, useRef } from 'react'; |
||||||
|
import { Animated, StyleSheet, View } from 'react-native'; |
||||||
|
|
||||||
|
const FadeIn = (props) => { |
||||||
|
const opacity = useRef(new Animated.Value(0)).current; |
||||||
|
|
||||||
|
useEffect(() => { |
||||||
|
Animated.timing(opacity, { |
||||||
|
toValue: 1, |
||||||
|
duration: 500, |
||||||
|
useNativeDriver: true, // This line offloads animation to the native driver |
||||||
|
}).start(); |
||||||
|
}, []); |
||||||
|
|
||||||
|
return ( |
||||||
|
<Animated.View |
||||||
|
style={[ |
||||||
|
styles.container, |
||||||
|
{ |
||||||
|
opacity: opacity, // This line applies the animated opacity value |
||||||
|
}, |
||||||
|
]} |
||||||
|
> |
||||||
|
{props.children} |
||||||
|
</Animated.View> |
||||||
|
); |
||||||
|
}; |
||||||
|
|
||||||
|
const styles = StyleSheet.create({ |
||||||
|
container: { |
||||||
|
flex: 1, |
||||||
|
justifyContent: 'center', |
||||||
|
alignItems: 'center', |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
export default FadeIn; |
||||||
|
``` |
||||||
|
|
||||||
|
By following best practices and leveraging tools like the `Animated` library, you can optimize your React Native application's performance and achieve smooth, high-quality animations with optimal frame rates. |
@ -1 +1,74 @@ |
|||||||
# Common problem sources |
# Common Problem Sources |
||||||
|
|
||||||
|
## 1. Console Logs |
||||||
|
|
||||||
|
Excessive console logs can lead to decreased performance in React Native, especially in debug mode. In order to avoid this, keep the usage of console logging to a minimum, and clean up unnecessary logs before releasing the app. |
||||||
|
|
||||||
|
## 2. Images |
||||||
|
|
||||||
|
Heavy and unoptimized images can lead to performance issues in React Native. To avoid this, use the following techniques: |
||||||
|
|
||||||
|
- Optimize image size and resolution before bundling them in the application. |
||||||
|
- Use `resizeMode` prop on the `Image` component to cache images for better rendering. |
||||||
|
|
||||||
|
```jsx |
||||||
|
<Image source={require('./my-image.png')} resizeMode="cover" /> |
||||||
|
``` |
||||||
|
|
||||||
|
## 3. Inline Functions and Styles |
||||||
|
|
||||||
|
Using inline functions and styles within components can lead to unnecessary re-rendering and performance issues. Instead, define functions and styles outside of the component render method. |
||||||
|
|
||||||
|
```jsx |
||||||
|
// Bad |
||||||
|
render() { |
||||||
|
return ( |
||||||
|
<TouchableOpacity onPress={() => this.onPress()}> |
||||||
|
<Text style={{fontSize: 16, color: 'blue'}}>Click me</Text> |
||||||
|
</TouchableOpacity> |
||||||
|
); |
||||||
|
} |
||||||
|
|
||||||
|
// Good |
||||||
|
const styles = StyleSheet.create({ |
||||||
|
buttonText: { |
||||||
|
fontSize: 16, |
||||||
|
color: 'blue', |
||||||
|
}, |
||||||
|
}); |
||||||
|
|
||||||
|
onPressHandler = () => { |
||||||
|
// Handle press |
||||||
|
}; |
||||||
|
|
||||||
|
render() { |
||||||
|
return ( |
||||||
|
<TouchableOpacity onPress={this.onPressHandler}> |
||||||
|
<Text style={styles.buttonText}>Click me</Text> |
||||||
|
</TouchableOpacity> |
||||||
|
); |
||||||
|
} |
||||||
|
``` |
||||||
|
|
||||||
|
## 4. PureComponent and React.memo |
||||||
|
|
||||||
|
Components that extend `React.PureComponent` or are wrapped in `React.memo()` can lead to performance issues in case they're updating frequently and causing unnecessary re-renders. Make sure to only use them when appropriate to avoid performance bottlenecks. |
||||||
|
|
||||||
|
## 5. ListView and FlatList |
||||||
|
|
||||||
|
When working with large lists in React Native, using `ListView` instead of `FlatList` can cause performance issues. Replace `ListView` with the more performant `FlatList` or `SectionList` components. |
||||||
|
|
||||||
|
```jsx |
||||||
|
// Use FlatList instead of ListView |
||||||
|
<FlatList |
||||||
|
data={this.state.data} |
||||||
|
renderItem={({item}) => <MyListItemComponent item={item} />} |
||||||
|
keyExtractor={(item) => item.id} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
## 6. JavaScript Thread Blockage |
||||||
|
|
||||||
|
Blocking the JavaScript thread with expensive synchronous computations can lead to poor performance. Make sure to handle heavy computations asynchronously or offload them to native modules. |
||||||
|
|
||||||
|
Read more in the [Official React Native documentation](https://reactnative.dev/docs/performance#common-sources-of-performance-problems). |
@ -1 +1,5 @@ |
|||||||
# Speeding up builds |
# Speeding up Builds |
||||||
|
|
||||||
|
Building your React Native app could be expensive and take several minutes of developers time. This can be problematic as your project grows and generally in bigger organizations with multiple React Native developers. |
||||||
|
|
||||||
|
- [Speeding up your Build phase](https://reactnative.dev/docs/build-speed) |
@ -1 +1,84 @@ |
|||||||
# Optimizing flatlist config |
# Optimizing FlatList Config |
||||||
|
|
||||||
|
In React Native, the FlatList component is used to efficiently display large lists of items. It's crucial to optimize the FlatList configuration for better performance. Here are some important tips to help you optimize FlatList configurations: |
||||||
|
|
||||||
|
## 1. Set `windowSize` |
||||||
|
|
||||||
|
`windowSize` is a prop that determines the number of pages rendered above and below the current window. By default, this value is 21. You can decrease it based on your needs to reduce the number of off-screen rendered components. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<FlatList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id} |
||||||
|
windowSize={10} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
## 2. Set `removeClippedSubviews` |
||||||
|
|
||||||
|
Enable the `removeClippedSubviews` prop to unmount components that are off the screen. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<FlatList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id} |
||||||
|
removeClippedSubviews={true} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
## 3. Set `maxToRenderPerBatch` |
||||||
|
|
||||||
|
`maxToRenderPerBatch` prop helps to control the number of items to be rendered per batch. By default, this is set to 10. Optimize this value according to your list's requirements. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<FlatList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id} |
||||||
|
maxToRenderPerBatch={5} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
## 4. Set `initialNumToRender` |
||||||
|
|
||||||
|
`initialNumToRender` is used to set the number of items to be rendered initially. Setting this value to a reasonable number can help in avoiding blank screens on load. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<FlatList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id} |
||||||
|
initialNumToRender={10} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
## 5. Set `getItemLayout` |
||||||
|
|
||||||
|
Using the `getItemLayout` prop allows you to specify the exact dimensions of each item. This prevents the need for measuring them dynamically, resulting in improved performance. |
||||||
|
|
||||||
|
Example: |
||||||
|
|
||||||
|
```javascript |
||||||
|
<FlatList |
||||||
|
data={data} |
||||||
|
renderItem={renderItem} |
||||||
|
keyExtractor={item => item.id} |
||||||
|
getItemLayout={(data, index) => ( |
||||||
|
{length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index} |
||||||
|
)} |
||||||
|
/> |
||||||
|
``` |
||||||
|
|
||||||
|
Implementing these optimizations in your FlatList config will help improve the performance of large lists in your React Native application. |
||||||
|
|
||||||
|
- [Optimizing Flatlist Configuration](https://reactnative.dev/docs/optimizing-flatlist-configuration) |
@ -1 +1,5 @@ |
|||||||
# Ram bundles |
# RAM Bundles + Inline Requires |
||||||
|
|
||||||
|
If you have a large app you may want to consider the Random Access Modules (RAM) bundle format, and using inline requires. This is useful for apps that have a large number of screens which may not ever be opened during a typical usage of the app. Generally it is useful to apps that have large amounts of code that are not needed for a while after startup. For instance the app includes complicated profile screens or lesser used features, but most sessions only involve visiting the main screen of the app for updates. We can optimize the loading of the bundle by using the RAM format and requiring those features and screens inline (when they are actually used). |
||||||
|
|
||||||
|
- [RAM Bundles and Inline Requires](https://reactnative.dev/docs/ram-bundles-inline-requires) |
@ -1 +1,9 @@ |
|||||||
# Profiling |
# Profiling |
||||||
|
|
||||||
|
Use the built-in profiler to get detailed information about work done in the JavaScript thread and main thread side-by-side. Access it by selecting Perf Monitor from the Debug menu. |
||||||
|
|
||||||
|
For iOS, Instruments is an invaluable tool, and on Android you should learn to use `systrace`. |
||||||
|
|
||||||
|
Visit the following for more details: |
||||||
|
|
||||||
|
- [Profiling React Native](https://reactnative.dev/docs/profiling) |
@ -1 +1,5 @@ |
|||||||
# Performance |
# Performance |
||||||
|
|
||||||
|
Performance is a crucial aspect of any application, and React Native is no exception. Optimizing performance in your React Native apps will not only lead to a better user experience but also lessen the load on device resources. |
||||||
|
|
||||||
|
Go through the topics listed under this node as well as [React Native Documentation](https://reactnative.dev/docs/performance) for more details. |
@ -1 +1,5 @@ |
|||||||
# For ios |
# For iOS |
||||||
|
|
||||||
|
Visit the Native Modules documentation in react native documentation to learn more about this topic. |
||||||
|
|
||||||
|
- [iOS Native Modules](https://reactnative.dev/docs/native-modules-ios) |
@ -1 +1,5 @@ |
|||||||
# For android |
# For Android |
||||||
|
|
||||||
|
Visit the Native Modules documentation in react native documentation to learn more about this topic. |
||||||
|
|
||||||
|
- [Android Native Modules](https://reactnative.dev/docs/native-modules-android) |
@ -1 +1,7 @@ |
|||||||
# Using native modules |
# Using Native Modules |
||||||
|
|
||||||
|
Sometimes a React Native app needs to access a native platform API that is not available by default in JavaScript, for example the native APIs to access Apple or Google Pay. Maybe you want to reuse some existing Objective-C, Swift, Java or C++ libraries without having to reimplement it in JavaScript, or write some high performance, multi-threaded code for things like image processing. |
||||||
|
|
||||||
|
The NativeModule system exposes instances of Java/Objective-C/C++ (native) classes to JavaScript (JS) as JS objects, thereby allowing you to execute arbitrary native code from within JS. While we don't expect this feature to be part of the usual development process, it is essential that it exists. If React Native doesn't export a native API that your JS app needs you should be able to export it yourself! |
||||||
|
|
||||||
|
- [Native Modules Introduction](https://reactnative.dev/docs/native-modules-intro) |
@ -1 +1,5 @@ |
|||||||
# App store |
# Publishing Apps in App Store |
||||||
|
|
||||||
|
The App Store is Apple's official platform for distributing iOS apps to users with iPhones, iPads, and iPod Touch devices. To publish an app on the App Store, you need to follow specific guidelines and use the necessary tools provided by Apple. |
||||||
|
|
||||||
|
- [Publishing to Apple App Store](https://reactnative.dev/docs/publishing-to-app-store) |
@ -1 +1,5 @@ |
|||||||
# Google store |
# Publishing React Native Apps on Google Store |
||||||
|
|
||||||
|
Publishing your React Native app on Google Store consists of several steps. |
||||||
|
|
||||||
|
- [Publishing to Google Play Store](https://reactnative.dev/docs/signed-apk-android) |
@ -1 +1,3 @@ |
|||||||
# Publishing apps |
# Publishing Apps |
||||||
|
|
||||||
|
Publishing React Native apps is the process of deploying your application on various app stores so that users can download and use your app. The two most popular app stores for publishing are the Apple App Store (iOS) and the Google Play Store (Android). |
Loading…
Reference in new issue