this repo has no description

Sanitise headings and single-child text nodes

-2
out/llms-full-react-native-gesture-handler.txt
···
The flow looks as follows:
-
Loading...
-
### Events
There are three types of events in RNGH2: `StateChangeEvent`, `GestureEvent` and `PointerEvent`. The `StateChangeEvent` is send every time a gesture moves to a different state, while `GestureEvent` is send every time a gesture is updated. The first two carry a gesture-specific data and a `state` property, indicating the current state of the gesture. `StateChangeEvent` also carries a `oldState` property indicating the previous state of the gesture. `PointerEvent` carries information about raw touch events, like touching the screen or moving the finger. These events are handled internally before they are passed along to the correct callbacks:
···
The flow looks as follows:
### Events
There are three types of events in RNGH2: `StateChangeEvent`, `GestureEvent` and `PointerEvent`. The `StateChangeEvent` is send every time a gesture moves to a different state, while `GestureEvent` is send every time a gesture is updated. The first two carry a gesture-specific data and a `state` property, indicating the current state of the gesture. `StateChangeEvent` also carries a `oldState` property indicating the previous state of the gesture. `PointerEvent` carries information about raw touch events, like touching the screen or moving the finger. These events are handled internally before they are passed along to the correct callbacks:
-130
out/llms-full-react-native-reanimated.txt
···
### Example
-
Loading...
-
### Remarks
- Animated styles take precedence over React Native's static styles. All values specified in animated styles override values from static styles.
···
### Example
-
Loading...
-
### Remarks
- The returned handler may be passed to multiple components. In such situation, the handler will invoke for the given events each time any of the components dispatches them.
···
### Example
-
Loading...
-
This example can be more easily implemented using `useScrollViewOffset`.
### Remarks
···
The hook returns a context that will be reused by event handlers and value that indicates whether worklets should be rebuilt. If different implementation is needed for web, `useWeb` boolean is returned to check for web environment
### Example
-
-
Loading...
This example can be more easily implemented using `useScrollViewOffset`.
···
### Example
-
Loading...
-
### Platform compatibility
| Android | iOS | Web |
···
### Example
-
Loading...
-
### Remarks
- The returned handler may be passed to multiple components. In such situation, the handler will invoke for the given events each time any of the components dispatches them.
···
`scrollTo` returns `undefined`.
### Example
-
-
Loading...
### Remarks
···
#### Example
-
Loading...
-
### Platform compatibility
| Android | iOS | Web |
···
### Example
-
Loading...
-
### Platform compatibility
| Android | iOS | Web |
···
`useScrollViewOffset` returns a shared value which holds the current offset of the `ScrollView`.
### Example
-
-
Loading...
### Remarks
···
And that's it! Pretty straightforward, isn't it? Let's see it in its full glory in an interactive example:
-
Loading...
-
You can make use of composing gestures to more complex behaviors. But what if we'd like to create something a bit more interesting?
### Handling pan gestures
···
You can play around with the example below and see how the circle changes and reacts to the gesture:
-
Loading...
-
### Using `withDecay`
Remember when some time ago we said that we'll come back to `withDecay`? Now this is the time!
···
Play around and see how the square decelerates when let go with some speed!
-
Loading...
-
Make sure to check the full `withDecay` API reference to get to know the rest of the configuration options.
### Summary
···
## withRepeat
`withRepeat` is an animation modifier that lets you repeat an animation given number of times or run it indefinitely.
-
-
Loading...
### Reference
···
A parameter that determines how the animation responds to the device's reduced motion accessibility setting.
-
Loading...
-
#### Returns
`withRepeat` returns an animation object which holds the current state of the animation. It can be either assigned directly to a shared value or can be used as a value for a style object returned from useAnimatedStyle.
### Example
-
-
Loading...
### Remarks
···
### Example
-
Loading...
-
### Remarks
- `measure` is implemented only on the UI thread. When using `measure` inside event handlers, it has to be wrapped with the `runOnUI` function.
···
### Example
-
Loading...
-
### Remarks
- Ensure you do not mutate the same shared value in the `result` function that you've used in the `prepare` function, as this will lead to an infinite loop.
···
`withSequence` is an animation modifier that lets you run animations in a sequence.
-
Loading...
-
### Reference
```
···
`withSequence` returns an animation object which holds the current state of the animation. It can be either assigned directly to a shared value or can be used as a value for a style object returned from useAnimatedStyle.
### Example
-
-
Loading...
### Platform compatibility
···
`useFrameCallback` lets you run a function on every frame update.
-
Loading...
-
### Reference
```
···
- `callbackId` a number indicating a unique identifier of the frame callback
### Example
-
-
Loading...
### Remarks
···
### Example
-
Loading...
-
### Platform compatibility
| Android | iOS | Web |
···
| state | `SharedValue<KeyboardState>` | A shared value containing current state of the keyboard. Possible states: `{ CLOSED, OPEN, CLOSING, OPENING }` |
### Example
-
-
Loading...
### Remarks
···
`withClamp` is an animation modifier that lets you limit the scope of movement of your animation to make it stay within some predefined range. Use it with withSpring animation.
-
Loading...
-
### Reference
```
···
For a full, in depth documentation follow the Sensors guide on Android Developers and the Device motion in the Apple Developer documentation.
The playground below mimics the behaviour and returned values of selected sensors:
-
-
Loading...
### Reference
···
### Example
-
Loading...
-
### Remarks
- You should always reach for `useAnimatedStyle` and `useAnimatedProps` first when animating styles or properties.
···
### Example
-
Loading...
-
### Remarks
- Changing the reduced motion system setting doesn't cause your components to rerender.
···
### Example
-
Loading...
-
### Remarks
info
···
You can see it in action in the example below:
-
Loading...
-
### Animating props
Most of the values that developers animate (`width`, `color`, `transform` etc.) are modified by passing them as an object to the `style` property of an element. But that's not always the case.
···
Check out the full example below:
-
Loading...
-
### Summary
In this section, we went through the differences between animating styles and props and how to use `useAnimatedStyle` and `useAnimatedProps`. To sum up:
···
- `ReduceMotion.Never` - This option ensures that the animation remains enabled at all times.
### Example
-
-
Loading...
### Platform compatibility
···
Reanimated comes with a bunch of predefined animations you can customize. For more advanced use-cases, you can use Keyframes or create your own custom entering/exiting animations.
-
Loading...
-
info
Spring-based animations are yet to be introduced to the web. Due to that, playground doesn't cover `springify()` options but they can be applied to your animations on iOS and Android platforms.
···
### Example
-
Loading...
-
### Remarks
- Don't read or modify the value of a shared value during a component's render. Access to `value` property or calling `get`/`set` methods is a side-effect. Triggering side-effects during render violates the Rules of React. All reads from and writes to a shared value should happen in relevant callbacks which aren't executed during render, i.e. in `useAnimatedStyle` or `useEffect` hooks.
···
## Layout transitions
Layout transitions allows you to replace layout changes with smooth transitions. Each layout change may include changes of size and position and both of them can be animated.
-
-
Loading...
### Predefined Transitions
···
### Example
-
Loading...
-
### Remarks
- You can share animated props between components to avoid code duplication.
···
## withTiming
`withTiming` lets you create an animation based on duration and easing.
-
-
Loading...
### Reference
···
The timing animation configuration.
-
Loading...
-
Available properties:
| Name | Type | Default | Description |
···
The `easing` parameter lets you fine-tune the animation over the specified time duration. For example, you can make the animation begin with fast acceleration and then slow down towards the end, or start slowly, then pick up speed before slowing down again towards the end.
It will all start to make sense when you compare a `linear` easing side by side with the default `Easing.inOut(Easing.quad)` easing.
-
-
Loading...
Reanimated provides a selection of ready-to-use easing functions in the `Easing` module. You can find a visualization of some common easing functions at <http://easings.net/>.
···
`withTiming` returns an animation object which holds the current state of the animation. It can be either assigned directly to a shared value or can be used as a value for a style object returned from useAnimatedStyle.
### Example
-
-
Loading...
### Remarks
···
`useScrollViewOffset` returns a shared value which holds the current offset of the `ScrollView`.
### Example
-
-
Loading...
### Remarks
···
It all will start to make sense when you compare side by side a `linear` easing with the default easing.
-
Loading...
-
Reanimated comes with a handful of predefined easing functions. You can play around with them in the interactive playground below or check the full `withTiming` API reference.
`withTiming` interactive playground
···
The mass of a spring influences how hard is it to make an object move and to bring it to a stop. Mass adds a feeling of _inertia_ to the object you're trying to move. You can see in the playground that the spring with greater mass moves more "sluggish" compared to the default configuration.
-
Loading...
-
Stiffness affects how bouncy the spring is. As an example, think about the difference between a steel spring (with very high stiffness) and a spring made out of soft plastic (with low stiffness).
Damping describes how quickly the spring animation finishes. Higher damping means the spring will come to rest faster. In the real world, you could think about the same spring bouncing in the air and underwater. For example, a spring in a vacuum would have zero friction and thus zero damping.
···
## withSpring
`withSpring` lets you create spring-based animations.
-
-
Loading...
### Reference
···
##### `config`Optional
The spring animation configuration.
-
-
Loading...
Available for physics-based spring:
···
### Example
-
Loading...
-
### Remarks
- The callback passed to the 3rd argument is automatically workletized and ran on the UI thread.
···
You can see it in action in the example below:
-
Loading...
-
### Animating props
Most of the values that developers animate (`width`, `color`, `transform` etc.) are modified by passing them as an object to the `style` property of an element. But that's not always the case.
···
Check out the full example below:
-
Loading...
-
### Summary
In this section, we went through the differences between animating styles and props and how to use `useAnimatedStyle` and `useAnimatedProps`. To sum up:
···
`useDerivedValue` returns a new readonly shared value based on a value returned from the `updater` function.
### Example
-
-
Loading...
### Remarks
···
### Example
-
Loading...
-
### Remarks
- Functions passed to `runOnJS` must be defined in the JavaScript thread scope, i.e. in the component body or the global scope. This code won't work because `myFunction` is defined in the `withTiming` callback, which is only executed in the UI thread:
···
Don't forget to call the function returned from `runOnUI`.
### Example
-
-
Loading...
### Remarks
···
And voilà, we've made our first animation using Reanimated! You can see how it works in its full glory in a preview below:
-
Loading...
-
### Summary
In this section, we gained a firm grasp on the Reanimated fundamentals. We learned about `Animated` components, shared values and how to use them to create a simple animation. To sum up:
···
## withDecay
`withDecay` lets you create animations that mimic objects in motion with friction. The animation will start with the provided velocity and slow down over time according to the given deceleration rate until it stops.
-
-
Loading...
### Reference
···
The decay animation configuration.
-
Loading...
-
Available properties:
| Name | Type | Default | Description |
···
`withDecay` returns an animation object which holds the current state of the animation. It can be either assigned directly to a shared value or can be used as a value for a style object returned from useAnimatedStyle.
### Example
-
-
Loading...
### Remarks
···
`createAnimatedComponent` returns a component that Reanimated is capable of animating.
### Example
-
-
Loading...
### Platform compatibility
···
`cancelAnimation` returns `undefined`.
### Example
-
-
Loading...
### Remarks
···
}
```
-
Loading...
-
### Repeating an animation
To implement our desired shake animation we can use `withRepeat` modifier. This modifier lets you repeat a provided animation.
···
```
When we run this code we can see that the box jiggles left to right between the set offset and a starting position. After the animation finishes the box doesn't come back to its initial place. It's not really how we imagined a shake animation but we'll get there in a second!
-
-
Loading...
### Running animations in a sequence
···
};
```
-
Loading...
-
### Starting the animation with delay
As a cherry on top, we'll add a little bit of suspense by adding a slight delay before the animation begins. For this exact purpose, Reanimated comes with a `withDelay` modifier.
···
);
};
```
-
-
Loading...
### Summary
···
`interpolate` lets you map a value from one range to another using linear interpolation.
-
Loading...
-
### Reference
```
···
`interpolate` returns a mapped value within the output range.
### Example
-
-
Loading...
### Platform compatibility
···
### Example
-
Loading...
-
### Platform compatibility
| Android | iOS | Web |
···
`interpolateColor` returns the color after interpolation from within the output range in `rgba(r, g, b, a)` format.
### Example
-
-
Loading...
### Remarks
···
### Example
### Remarks
- Animated styles take precedence over React Native's static styles. All values specified in animated styles override values from static styles.
···
### Example
### Remarks
- The returned handler may be passed to multiple components. In such situation, the handler will invoke for the given events each time any of the components dispatches them.
···
### Example
This example can be more easily implemented using `useScrollViewOffset`.
### Remarks
···
The hook returns a context that will be reused by event handlers and value that indicates whether worklets should be rebuilt. If different implementation is needed for web, `useWeb` boolean is returned to check for web environment
### Example
This example can be more easily implemented using `useScrollViewOffset`.
···
### Example
### Platform compatibility
| Android | iOS | Web |
···
### Example
### Remarks
- The returned handler may be passed to multiple components. In such situation, the handler will invoke for the given events each time any of the components dispatches them.
···
`scrollTo` returns `undefined`.
### Example
### Remarks
···
#### Example
### Platform compatibility
| Android | iOS | Web |
···
### Example
### Platform compatibility
| Android | iOS | Web |
···
`useScrollViewOffset` returns a shared value which holds the current offset of the `ScrollView`.
### Example
### Remarks
···
And that's it! Pretty straightforward, isn't it? Let's see it in its full glory in an interactive example:
You can make use of composing gestures to more complex behaviors. But what if we'd like to create something a bit more interesting?
### Handling pan gestures
···
You can play around with the example below and see how the circle changes and reacts to the gesture:
### Using `withDecay`
Remember when some time ago we said that we'll come back to `withDecay`? Now this is the time!
···
Play around and see how the square decelerates when let go with some speed!
Make sure to check the full `withDecay` API reference to get to know the rest of the configuration options.
### Summary
···
## withRepeat
`withRepeat` is an animation modifier that lets you repeat an animation given number of times or run it indefinitely.
### Reference
···
A parameter that determines how the animation responds to the device's reduced motion accessibility setting.
#### Returns
`withRepeat` returns an animation object which holds the current state of the animation. It can be either assigned directly to a shared value or can be used as a value for a style object returned from useAnimatedStyle.
### Example
### Remarks
···
### Example
### Remarks
- `measure` is implemented only on the UI thread. When using `measure` inside event handlers, it has to be wrapped with the `runOnUI` function.
···
### Example
### Remarks
- Ensure you do not mutate the same shared value in the `result` function that you've used in the `prepare` function, as this will lead to an infinite loop.
···
`withSequence` is an animation modifier that lets you run animations in a sequence.
### Reference
```
···
`withSequence` returns an animation object which holds the current state of the animation. It can be either assigned directly to a shared value or can be used as a value for a style object returned from useAnimatedStyle.
### Example
### Platform compatibility
···
`useFrameCallback` lets you run a function on every frame update.
### Reference
```
···
- `callbackId` a number indicating a unique identifier of the frame callback
### Example
### Remarks
···
### Example
### Platform compatibility
| Android | iOS | Web |
···
| state | `SharedValue<KeyboardState>` | A shared value containing current state of the keyboard. Possible states: `{ CLOSED, OPEN, CLOSING, OPENING }` |
### Example
### Remarks
···
`withClamp` is an animation modifier that lets you limit the scope of movement of your animation to make it stay within some predefined range. Use it with withSpring animation.
### Reference
```
···
For a full, in depth documentation follow the Sensors guide on Android Developers and the Device motion in the Apple Developer documentation.
The playground below mimics the behaviour and returned values of selected sensors:
### Reference
···
### Example
### Remarks
- You should always reach for `useAnimatedStyle` and `useAnimatedProps` first when animating styles or properties.
···
### Example
### Remarks
- Changing the reduced motion system setting doesn't cause your components to rerender.
···
### Example
### Remarks
info
···
You can see it in action in the example below:
### Animating props
Most of the values that developers animate (`width`, `color`, `transform` etc.) are modified by passing them as an object to the `style` property of an element. But that's not always the case.
···
Check out the full example below:
### Summary
In this section, we went through the differences between animating styles and props and how to use `useAnimatedStyle` and `useAnimatedProps`. To sum up:
···
- `ReduceMotion.Never` - This option ensures that the animation remains enabled at all times.
### Example
### Platform compatibility
···
Reanimated comes with a bunch of predefined animations you can customize. For more advanced use-cases, you can use Keyframes or create your own custom entering/exiting animations.
info
Spring-based animations are yet to be introduced to the web. Due to that, playground doesn't cover `springify()` options but they can be applied to your animations on iOS and Android platforms.
···
### Example
### Remarks
- Don't read or modify the value of a shared value during a component's render. Access to `value` property or calling `get`/`set` methods is a side-effect. Triggering side-effects during render violates the Rules of React. All reads from and writes to a shared value should happen in relevant callbacks which aren't executed during render, i.e. in `useAnimatedStyle` or `useEffect` hooks.
···
## Layout transitions
Layout transitions allows you to replace layout changes with smooth transitions. Each layout change may include changes of size and position and both of them can be animated.
### Predefined Transitions
···
### Example
### Remarks
- You can share animated props between components to avoid code duplication.
···
## withTiming
`withTiming` lets you create an animation based on duration and easing.
### Reference
···
The timing animation configuration.
Available properties:
| Name | Type | Default | Description |
···
The `easing` parameter lets you fine-tune the animation over the specified time duration. For example, you can make the animation begin with fast acceleration and then slow down towards the end, or start slowly, then pick up speed before slowing down again towards the end.
It will all start to make sense when you compare a `linear` easing side by side with the default `Easing.inOut(Easing.quad)` easing.
Reanimated provides a selection of ready-to-use easing functions in the `Easing` module. You can find a visualization of some common easing functions at <http://easings.net/>.
···
`withTiming` returns an animation object which holds the current state of the animation. It can be either assigned directly to a shared value or can be used as a value for a style object returned from useAnimatedStyle.
### Example
### Remarks
···
`useScrollViewOffset` returns a shared value which holds the current offset of the `ScrollView`.
### Example
### Remarks
···
It all will start to make sense when you compare side by side a `linear` easing with the default easing.
Reanimated comes with a handful of predefined easing functions. You can play around with them in the interactive playground below or check the full `withTiming` API reference.
`withTiming` interactive playground
···
The mass of a spring influences how hard is it to make an object move and to bring it to a stop. Mass adds a feeling of _inertia_ to the object you're trying to move. You can see in the playground that the spring with greater mass moves more "sluggish" compared to the default configuration.
Stiffness affects how bouncy the spring is. As an example, think about the difference between a steel spring (with very high stiffness) and a spring made out of soft plastic (with low stiffness).
Damping describes how quickly the spring animation finishes. Higher damping means the spring will come to rest faster. In the real world, you could think about the same spring bouncing in the air and underwater. For example, a spring in a vacuum would have zero friction and thus zero damping.
···
## withSpring
`withSpring` lets you create spring-based animations.
### Reference
···
##### `config`Optional
The spring animation configuration.
Available for physics-based spring:
···
### Example
### Remarks
- The callback passed to the 3rd argument is automatically workletized and ran on the UI thread.
···
You can see it in action in the example below:
### Animating props
Most of the values that developers animate (`width`, `color`, `transform` etc.) are modified by passing them as an object to the `style` property of an element. But that's not always the case.
···
Check out the full example below:
### Summary
In this section, we went through the differences between animating styles and props and how to use `useAnimatedStyle` and `useAnimatedProps`. To sum up:
···
`useDerivedValue` returns a new readonly shared value based on a value returned from the `updater` function.
### Example
### Remarks
···
### Example
### Remarks
- Functions passed to `runOnJS` must be defined in the JavaScript thread scope, i.e. in the component body or the global scope. This code won't work because `myFunction` is defined in the `withTiming` callback, which is only executed in the UI thread:
···
Don't forget to call the function returned from `runOnUI`.
### Example
### Remarks
···
And voilà, we've made our first animation using Reanimated! You can see how it works in its full glory in a preview below:
### Summary
In this section, we gained a firm grasp on the Reanimated fundamentals. We learned about `Animated` components, shared values and how to use them to create a simple animation. To sum up:
···
## withDecay
`withDecay` lets you create animations that mimic objects in motion with friction. The animation will start with the provided velocity and slow down over time according to the given deceleration rate until it stops.
### Reference
···
The decay animation configuration.
Available properties:
| Name | Type | Default | Description |
···
`withDecay` returns an animation object which holds the current state of the animation. It can be either assigned directly to a shared value or can be used as a value for a style object returned from useAnimatedStyle.
### Example
### Remarks
···
`createAnimatedComponent` returns a component that Reanimated is capable of animating.
### Example
### Platform compatibility
···
`cancelAnimation` returns `undefined`.
### Example
### Remarks
···
}
```
### Repeating an animation
To implement our desired shake animation we can use `withRepeat` modifier. This modifier lets you repeat a provided animation.
···
```
When we run this code we can see that the box jiggles left to right between the set offset and a starting position. After the animation finishes the box doesn't come back to its initial place. It's not really how we imagined a shake animation but we'll get there in a second!
### Running animations in a sequence
···
};
```
### Starting the animation with delay
As a cherry on top, we'll add a little bit of suspense by adding a slight delay before the animation begins. For this exact purpose, Reanimated comes with a `withDelay` modifier.
···
);
};
```
### Summary
···
`interpolate` lets you map a value from one range to another using linear interpolation.
### Reference
```
···
`interpolate` returns a mapped value within the output range.
### Example
### Platform compatibility
···
### Example
### Platform compatibility
| Android | iOS | Web |
···
`interpolateColor` returns the color after interpolation from within the output range in `rgba(r, g, b, a)` format.
### Example
### Remarks
-740
out/llms-full-react-native.txt
···
#### `alert()`
-
tsx
-
```
static alert (
title: string,
···
---
#### `prompt()`iOS
-
-
tsx
```
static prompt: (
···
#### `addEventListener()`
-
tsx
-
```
static addEventListener(
type: 'url',
···
---
#### `canOpenURL()`
-
-
tsx
```
static canOpenURL(url: string): Promise<boolean>;
···
#### `getInitialURL()`
-
tsx
-
```
static getInitialURL(): Promise<string | null>;
```
···
#### `openSettings()`
-
tsx
-
```
static openSettings(): Promise<void>;
```
···
---
#### `openURL()`
-
-
tsx
```
static openURL(url: string): Promise<any>;
···
#### `sendIntent()`Android
-
tsx
-
```
static sendIntent(
action: string,
···
#### `showActionSheetWithOptions()`
-
tsx
-
```
static showActionSheetWithOptions: (
options: ActionSheetIOSOptions,
···
Minimal example:
-
tsx
-
```
ActionSheetIOS.showActionSheetWithOptions(
{
···
#### `dismissActionSheet()`
-
tsx
-
```
static dismissActionSheet();
```
···
---
#### `showShareActionSheetWithOptions()`
-
-
tsx
```
static showShareActionSheetWithOptions: (
···
2. For iOS only, navigate in the `App/ios` folder and run `bundle exec pod install` to install your dependencies.
3. Update the `App.tsx` code to import the code in your library. For example:
-
tsx
-
```
import NativeSampleModule from '../Library/src/index';
```
···
A task is an async function that you register on `AppRegistry`, similar to registering React applications:
-
tsx
-
```
import {AppRegistry} from 'react-native';
AppRegistry.registerHeadlessTask('SomeTaskName', () =>
···
```
Then, in `SomeTaskName.js`:
-
-
tsx
```
module.exports = async taskData => {
···
Example:
-
tsx
-
```
import {HeadlessJsTaskError} from 'HeadlessJsTask';
···
}
}
```
-
-
tsx
```
import React from 'react';
···
moduleName:@"ImageBrowserApp"
initialProperties:props];
```
-
-
tsx
```
import React from 'react';
···
### Usage Pattern
-
tsx
-
```
const ExampleComponent = () => {
const panResponder = React.useRef(
···
### Methods
#### `create()`
-
-
tsx
```
static create(config: PanResponderCallbacks): PanResponderInstance;
···
The native module can then be accessed in JS like this:
-
tsx
-
```
const {CalendarModule} = ReactNative.NativeModules;
```
···
Find a place in your application where you would like to add a call to the native module’s `createCalendarEvent()` method. Below is an example of a component, `NewModuleButton` you can add in your app. You can invoke the native module inside `NewModuleButton`'s `onPress()` function.
-
tsx
-
```
import React from 'react';
import {NativeModules, Button} from 'react-native';
···
In order to access your native module from JavaScript you need to first import `NativeModules` from React Native:
-
tsx
-
```
import {NativeModules} from 'react-native';
```
You can then access the `CalendarModule` native module off of `NativeModules`.
-
tsx
-
```
const {CalendarModule} = NativeModules;
```
Now that you have the CalendarModule native module available, you can invoke your native method `createCalendarEvent()`. Below it is added to the `onPress()` method in `NewModuleButton`:
-
-
tsx
```
const onPress = () => {
···
To save consumers of your native module from needing to do that each time they want to access your native module, you can create a JavaScript wrapper for the module. Create a new JavaScript file named `CalendarModule.js` with the following content:
-
tsx
-
```
/**
* This exposes the native CalendarModule module as a JS module. This has a
···
This JavaScript file also becomes a good location for you to add any JavaScript side functionality. For example, if you use a type system like TypeScript you can add type annotations for your native module here. While React Native does not yet support Native to JS type safety, all your JS code will be type safe. Doing so will also make it easier for you to switch to type-safe native modules down the line. Below is an example of adding type safety to the CalendarModule:
-
tsx
-
```
/**
* This exposes the native CalendarModule module as a JS module. This has a
···
```
In your other JavaScript files you can access the native module and invoke its method like this:
-
-
tsx
```
import CalendarModule from './CalendarModule';
···
The constant can then be accessed by invoking `getConstants` on the native module in JS:
-
tsx
-
```
const {DEFAULT_EVENT_NAME} = CalendarModule.getConstants();
console.log(DEFAULT_EVENT_NAME);
···
This method could then be accessed in JavaScript using:
-
tsx
-
```
const onPress = () => {
CalendarModule.createCalendarEvent(
···
```
In JavaScript, you can then check the first argument to see if an error was passed through:
-
-
tsx
```
const onPress = () => {
···
```
Then in JavaScript you can add a separate callback for error and success responses:
-
-
tsx
```
const onPress = () => {
···
The JavaScript counterpart of this method returns a Promise. This means you can use the `await` keyword within an async function to call it and wait for its result:
-
tsx
-
```
const onSubmit = async () => {
try {
···
```
JavaScript modules can then register to receive events by `addListener` on the NativeEventEmitter class.
-
-
tsx
```
import {NativeEventEmitter, NativeModules} from 'react-native';
···
```
The native module can then be accessed in JS like this:
-
-
tsx
```
const {CalendarModuleFoo} = ReactNative.NativeModules;
···
The native module can then be accessed in JS like this:
-
tsx
-
```
const {CalendarModule} = ReactNative.NativeModules;
```
···
Find a place in your application where you would like to add a call to the native module’s `createCalendarEvent()` method. Below is an example of a component, `NewModuleButton` you can add in your app. You can invoke the native module inside `NewModuleButton`'s `onPress()` function.
-
tsx
-
```
import React from 'react';
import {Button} from 'react-native';
···
```
In order to access your native module from JavaScript you need to first import `NativeModules` from React Native:
-
-
tsx
```
import {NativeModules} from 'react-native';
···
You can then access the `CalendarModule` native module off of `NativeModules`.
-
tsx
-
```
const {CalendarModule} = NativeModules;
```
Now that you have the CalendarModule native module available, you can invoke your native method `createCalendarEvent()`. Below it is added to the `onPress()` method in `NewModuleButton`:
-
-
tsx
```
const onPress = () => {
···
Importing your native module by pulling it off of `NativeModules` like above is a bit clunky.
To save consumers of your native module from needing to do that each time they want to access your native module, you can create a JavaScript wrapper for the module. Create a new JavaScript file named NativeCalendarModule.js with the following content:
-
-
tsx
```
/**
···
This JavaScript file also becomes a good location for you to add any JavaScript side functionality. For example, if you use a type system like TypeScript you can add type annotations for your native module here. While React Native does not yet support Native to JS type safety, with these type annotations, all your JS code will be type safe. These annotations will also make it easier for you to switch to type-safe native modules down the line. Below is an example of adding type safety to the Calendar Module:
-
tsx
-
```
/**
* This exposes the native CalendarModule module as a JS module. This has a
···
```
In your other JavaScript files you can access the native module and invoke its method like this:
-
-
tsx
```
import NativeCalendarModule from './NativeCalendarModule';
···
```
The constant can then be accessed by invoking `getConstants()` on the native module in JS like so:
-
-
tsx
```
const {DEFAULT_EVENT_NAME} = CalendarModule.getConstants();
···
This method could then be accessed in JavaScript using the following:
-
tsx
-
```
const onSubmit = () => {
CalendarModule.createCalendarEvent(
···
```
In JavaScript, you can then check the first argument to see if an error was passed through:
-
-
tsx
```
const onPress = () => {
···
Then in JavaScript you can add a separate callback for error and success responses:
-
tsx
-
```
const onPress = () => {
CalendarModule.createCalendarEventCallback(
···
```
The JavaScript counterpart of this method returns a Promise. This means you can use the `await` keyword within an async function to call it and wait for its result:
-
-
tsx
```
const onSubmit = async () => {
···
#### Create a `App.tsx` file
Let's create an `App.tsx` file. This is a TypeScript file that can have JSX expressions. It contains the root React Native component that we will integrate into our Android application (link):
-
-
tsx
```
import React from 'react';
···
Let's create an `App.tsx` file. This is a TypeScript file that can have JSX expressions. It contains the root React Native component that we will integrate into our iOS application (link):
-
tsx
-
```
import React from 'react';
import {
···
A React Native view can have more than one child view in the view tree eg.
-
tsx
-
```
<View>
<MyNativeView />
···
In this example, the class `MyNativeView` is a wrapper for a `NativeComponent` and exposes methods, which will be called on the iOS platform. `MyNativeView` is defined in `MyNativeView.ios.js` and contains proxy methods of `NativeComponent`.
When the user interacts with the component, like clicking the button, the `backgroundColor` of `MyNativeView` changes. In this case `UIManager` would not know which `MyNativeView` should be handled and which one should change `backgroundColor`. Below you will find a solution to this problem:
-
-
tsx
```
<View>
···
TouchableOpacity uses `setNativeProps` internally to update the opacity of its child component:
-
tsx
-
```
const viewRef = useRef<View>();
const setOpacityTo = useCallback(value => {
···
```
This allows us to write the following code and know that the child will have its opacity updated in response to taps, without the child having any knowledge of that fact or requiring any changes to its implementation:
-
-
tsx
```
<TouchableOpacity onPress={handlePress}>
···
```
Let's imagine that `setNativeProps` was not available. One way that we might implement it with that constraint is to store the opacity value in the state, then update that value whenever `onPress` is fired:
-
-
tsx
```
const [buttonOpacity, setButtonOpacity] = useState(1);
···
#### `aria-labelledby`Android
Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the `nativeID` of the related element:
-
-
tsx
```
<View>
···
If this button doesn't look right for your app, you can build your own button using Pressable. For inspiration, look at the source code for the Button component.
-
tsx
-
```
<Button
onPress={onPressLearnMore}
···
#### Working with animations
Animations are started by calling `start()` on your animation. `start()` takes a completion callback that will be called when the animation is done. If the animation finished running normally, the completion callback will be invoked with `{finished: true}`. If the animation is done because `stop()` was called on it before it could finish (e.g. because it was interrupted by a gesture or another animation), then it will receive `{finished: false}`.
-
-
tsx
```
Animated.timing({}).start(({finished}) => {
···
For example, when working with horizontal scrolling gestures, you would do the following in order to map `event.nativeEvent.contentOffset.x` to `scrollX` (an `Animated.Value`):
-
tsx
-
```
onScroll={Animated.event(
// scrollX = e.nativeEvent.contentOffset.x
···
#### `decay()`
-
tsx
-
```
static decay(value, config): CompositeAnimation;
```
···
---
#### `timing()`
-
-
tsx
```
static timing(value, config): CompositeAnimation;
···
#### `spring()`
-
tsx
-
```
static spring(value, config): CompositeAnimation;
```
···
#### `add()`
-
tsx
-
```
static add(a: Animated, b: Animated): AnimatedAddition;
```
···
---
#### `subtract()`
-
-
tsx
```
static subtract(a: Animated, b: Animated): AnimatedSubtraction;
···
#### `divide()`
-
tsx
-
```
static divide(a: Animated, b: Animated): AnimatedDivision;
```
···
#### `multiply()`
-
tsx
-
```
static multiply(a: Animated, b: Animated): AnimatedMultiplication;
```
···
---
#### `modulo()`
-
-
tsx
```
static modulo(a: Animated, modulus: number): AnimatedModulo;
···
#### `diffClamp()`
-
tsx
-
```
static diffClamp(a: Animated, min: number, max: number): AnimatedDiffClamp;
```
···
#### `delay()`
-
tsx
-
```
static delay(time: number): CompositeAnimation;
```
···
#### `sequence()`
-
tsx
-
```
static sequence(animations: CompositeAnimation[]): CompositeAnimation;
```
···
---
#### `parallel()`
-
-
tsx
```
static parallel(
···
---
#### `stagger()`
-
-
tsx
```
static stagger(
···
#### `loop()`
-
tsx
-
```
static loop(
animation: CompositeAnimation[],
···
#### `event()`
-
tsx
-
```
static event(
argMapping: Mapping[],
···
Takes an array of mappings and extracts values from each arg accordingly, then calls `setValue` on the mapped outputs. e.g.
-
tsx
-
```
onScroll={Animated.event(
[{nativeEvent: {contentOffset: {x: this._scrollX}}}],
···
#### `start()`
-
tsx
-
```
static start(callback?: (result: {finished: boolean}) => void);
```
···
| callback | `(result: {finished: boolean}) => void` | No | Function that will be called after the animation finished running normally or when the animation is done because stop() was called on it before it could finish |
Start example with callback:
-
-
tsx
```
Animated.timing({}).start(({finished}) => {
···
#### `stop()`
-
tsx
-
```
static stop();
```
···
---
#### `reset()`
-
-
tsx
```
static reset();
···
#### `abortPrefetch()`Android
-
tsx
-
```
static abortPrefetch(requestId: number);
```
···
---
#### `getSize()`
-
-
tsx
```
static getSize(uri: string): Promise<{width: number, height: number}>;
···
#### `getSizeWithHeaders()`
-
tsx
-
```
static getSizeWithHeaders(
uri: string,
···
---
#### `prefetch()`
-
-
tsx
```
await Image.prefetch(url);
···
#### `queryCache()`
-
tsx
-
```
static queryCache(
urls: string[],
···
---
#### `resolveAssetSource()`
-
-
tsx
```
static resolveAssetSource(source: ImageSourcePropType): {
···
## Pressable
Pressable is a Core Component wrapper that can detect various stages of press interactions on any of its defined children.
-
-
tsx
```
<Pressable onPress={onPressFunction}>
···
### Methods
#### `flashScrollIndicators()`
-
-
tsx
```
flashScrollIndicators();
···
#### `scrollTo()`
-
tsx
-
```
scrollTo(
options?: {x?: number, y?: number, animated?: boolean} | number,
···
---
#### `scrollToEnd()`
-
-
tsx
```
scrollToEnd(options?: {animated?: boolean});
···
#### `popStackEntry()`
-
tsx
-
```
static popStackEntry(entry: StatusBarProps);
```
···
---
#### `pushStackEntry()`
-
-
tsx
```
static pushStackEntry(props: StatusBarProps): StatusBarProps;
···
#### `replaceStackEntry()`
-
tsx
-
```
static replaceStackEntry(
entry: StatusBarProps,
···
#### `setBackgroundColor()`Android
-
tsx
-
```
static setBackgroundColor(color: ColorValue, animated?: boolean);
```
···
#### `setBarStyle()`
-
tsx
-
```
static setBarStyle(style: StatusBarStyle, animated?: boolean);
```
···
---
#### `setHidden()`
-
-
tsx
```
static setHidden(hidden: boolean, animation?: StatusBarAnimation);
···
#### `setNetworkActivityIndicatorVisible()`iOS
-
tsx
-
```
static setNetworkActivityIndicatorVisible(visible: boolean);
```
···
---
#### `setTranslucent()`Android
-
-
tsx
```
static setTranslucent(translucent: boolean);
···
The `<Text>` element is unique relative to layout: everything inside is no longer using the Flexbox layout but using text layout. This means that elements inside of a `<Text>` are no longer rectangles, but wrap when they see the end of the line.
-
tsx
-
```
<Text>
<Text>First part and </Text>
···
In React Native, we are more strict about it: **you must wrap all the text nodes inside of a `<Text>` component**. You cannot have a text node directly under a `<View>`.
-
tsx
-
```
// BAD: will raise exception, can't have a text node as child of a <View>
<View>
···
```
You also lose the ability to set up a default font for an entire subtree. Meanwhile, `fontFamily` only accepts a single font name, which is different from `font-family` in CSS. The recommended way to use consistent fonts and sizes across your application is to create a component `MyAppText` that includes them and use this component across your app. You can also use this component to make more specific components like `MyAppHeaderText` for other kinds of text.
-
-
tsx
```
<View>
···
Assuming that `MyAppText` is a component that only renders out its children into a `Text` component with styling, then `MyAppHeaderText` can be defined as follows:
-
tsx
-
```
const MyAppHeaderText = ({children}) => {
return (
···
Composing `MyAppText` in this way ensures that we get the styles from a top-level component, but leaves us the ability to add/override them in specific use cases.
React Native still has the concept of style inheritance, but limited to text subtrees. In this case, the second part will be both bold and red.
-
-
tsx
```
<Text style={{fontWeight: 'bold'}}>
···
#### `.focus()`
-
tsx
-
```
focus();
```
···
Makes the native input request focus.
#### `.blur()`
-
-
tsx
```
blur();
···
#### `clear()`
-
tsx
-
```
clear();
```
···
#### `isFocused()`
-
tsx
-
```
isFocused(): boolean;
```
···
React Native provides a unified way of managing images and other media assets in your Android and iOS apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:
-
tsx
-
```
<Image source={require('./my-icon.png')} />
```
···
...and `button.js` code contains:
-
tsx
-
```
<Image source={require('./img/check.png')} />
```
···
7. Images can be distributed via npm packages.
In order for this to work, the image name in `require` has to be known statically.
-
-
tsx
```
// GOOD
···
For images included via Xcode asset catalogs or in the Android drawable folder, use the image name without the extension:
-
tsx
-
```
<Image
source={{uri: 'app_icon'}}
···
```
For images in the Android assets folder, use the `asset:/` scheme:
-
-
tsx
```
<Image
···
Many of the images you will display in your app will not be available at compile time, or you will want to load some dynamically to keep the binary size down. Unlike with static resources, _you will need to manually specify the dimensions of your image_. It's highly recommended that you use https as well in order to satisfy App Transport Security requirements on iOS.
-
tsx
-
```
// GOOD
<Image source={{uri: 'https://reactjs.org/logo-og.png'}}
···
If you would like to set such things as the HTTP-Verb, Headers or a Body along with the image request, you may do this by defining these properties on the source object:
-
tsx
-
```
<Image
source={{
···
This is recommended for very small and dynamic images only, like icons in a list from a DB.
-
tsx
-
```
// include at least width and height!
<Image
···
- `force-cache`: The existing cached data will be used to satisfy the request, regardless of its age or expiration date. If there is no existing data in the cache corresponding the request, the data is loaded from the originating source.
- `only-if-cached`: The existing cache data will be used to satisfy a request, regardless of its age or expiration date. If there is no existing data in the cache corresponding to a URL load request, no attempt is made to load the data from the originating source, and the load is considered to have failed.
-
tsx
-
```
<Image
source={{
···
Android supports loading drawable resources via the `xml` file type. This means you can use vector drawables for rendering icons or shape drawables for, well, drawing shapes! You can import and use these resource types the same as any other static resource or hybrid resource. You have to specify image dimensions manually.
For static drawables that live alongside your JS code, use the `require` or `import` syntax (both work the same):
-
-
tsx
```
<Image
···
For drawables included in the Android drawable folder (i.e. `res/drawable`), use the resource name without the extension:
-
tsx
-
```
<Image
source={{uri: 'my_icon'}}
···
For example, the result of `require('./my-icon.png')` might be:
-
tsx
-
```
{"__packager_asset":true,"uri":"my-icon.png","width":591,"height":573}
```
···
In React Native, one interesting decision is that the `src` attribute is named `source` and doesn't take a string but an object with a `uri` attribute.
-
tsx
-
```
<Image source={{uri: 'something.jpg'}} />
```
···
A common feature request from developers familiar with the web is `background-image`. To handle this use case, you can use the `<ImageBackground>` component, which has the same props as `<Image>`, and add whatever children to it you would like to layer on top of it.
You might not want to use `<ImageBackground>` in some cases, since the implementation is basic. Refer to `<ImageBackground>`'s documentation for more insight, and create your own custom component when needed.
-
-
tsx
```
return (
···
The underlay comes from wrapping the child in a new View, which can affect layout, and sometimes cause unwanted visual artifacts if not used correctly, for example if the backgroundColor of the wrapped view isn't explicitly set to an opaque color.
TouchableHighlight must have one child (not zero or more than one). If you wish to have several child components, wrap them in a View.
-
-
tsx
```
function MyComponent(props: MyComponentProps) {
···
### Displaying a basic button
Button provides a basic button component that is rendered nicely on all platforms. The minimal example to display a button looks like this:
-
-
tsx
```
<Button
···
### Usage Pattern
-
tsx
-
```
function MyComponent(props: MyComponentProps) {
return (
···
Now, you need to wrap the whole app in `NavigationContainer`. Usually you'd do this in your entry file, such as `index.js` or `App.js`:
-
tsx
-
```
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
···
#### Usage
Now you can create an app with a home screen and a profile screen:
-
-
tsx
```
import * as React from 'react';
···
You can set options such as the screen title for each screen in the `options` prop of `Stack.Screen`.
Each screen takes a `component` prop that is a React component. Those components receive a prop called `navigation` which has various methods to link to other screens. For example, you can use `navigation.navigate` to go to the `Profile` screen:
-
-
tsx
```
const HomeScreen = ({navigation}) => {
···
For example, if we want to create a 2-second long animation of an object that slightly backs up before moving to its final position:
-
tsx
-
```
Animated.timing(this.state.xPosition, {
toValue: 100,
···
For example, the following animation coasts to a stop, then it springs back while twirling in parallel:
-
tsx
-
```
Animated.sequence([
// decay, then spring to start and twirl
···
There are some cases where an animated value needs to invert another animated value for calculation. An example is inverting a scale (2x There are some cases where an animated value needs to invert another animated value for calculation. An example is inverting a scale (2x --> 0.5x):
-
tsx
-
```
const a = new Animated.Value(1);
const b = Animated.divide(1, a);
···
A basic mapping to convert a 0-1 range to a 0-100 range would be:
-
tsx
-
```
value.interpolate({
inputRange: [0, 1],
···
For example, you may want to think about your `Animated.Value` as going from 0 to 1, but animate the position from 150px to 0px and the opacity from 0 to 1. This can be done by modifying `style` from the example above like so:
-
tsx
-
```
style={{
opacity: this.state.fadeAnim, // Binds directly
···
```
`interpolate()` supports multiple range segments as well, which is handy for defining dead zones and other handy tricks. For example, to get a negation relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then back down to zero at 100 followed by a dead-zone that remains at 0 for everything beyond that, you could do:
-
-
tsx
```
value.interpolate({
···
`interpolate()` also supports mapping to strings, allowing you to animate colors as well as values with units. For example, if you wanted to animate a rotation you could do:
-
tsx
-
```
value.interpolate({
inputRange: [0, 360],
···
Animated values can also track other values by setting the `toValue` of an animation to another animated value instead of a plain number. For example, a "Chat Heads" animation like the one used by Messenger on Android could be implemented with a `spring()` pinned on another animated value, or with `timing()` and a `duration` of 0 for rigid tracking. They can also be composed with interpolations:
-
tsx
-
```
Animated.spring(follower, {toValue: leader}).start();
Animated.timing(opacity, {
···
Gestures, like panning or scrolling, and other events can map directly to animated values using `Animated.event`. This is done with a structured map syntax so that values can be extracted from complex event objects. The first level is an array to allow mapping across multiple args, and that array contains nested objects.
For example, when working with horizontal scrolling gestures, you would do the following in order to map `event.nativeEvent.contentOffset.x` to `scrollX` (an `Animated.Value`):
-
-
tsx
```
onScroll={Animated.event(
···
When using `PanResponder`, you could use the following code to extract the x and y positions from `gestureState.dx` and `gestureState.dy`. We use a `null` in the first position of the array, as we are only interested in the second argument passed to the `PanResponder` handler, which is the `gestureState`.
-
tsx
-
```
onPanResponderMove={Animated.event(
[null, // ignore the native event
···
Using the native driver for normal animations can be accomplished by setting `useNativeDriver: true` in animation config when starting it. Animations without a `useNativeDriver` property will default to false for legacy reasons, but emit a warning (and typechecking error in TypeScript).
-
tsx
-
```
Animated.timing(this.state.animatedValue, {
toValue: 1,
···
Animated values are only compatible with one driver so if you use native driver when starting an animation on a value, make sure every animation on that value also uses the native driver.
The native driver also works with `Animated.event`. This is especially useful for animations that follow the scroll position as without the native driver, the animation will always run a frame behind the gesture due to the async nature of React Native.
-
-
tsx
```
<Animated.ScrollView // <-- Use the Animated ScrollView wrapper
···
#### Bear in mind
While using transform styles such as `rotateY`, `rotateX`, and others ensure the transform style `perspective` is in place. At this time some animations may not render on Android without it. Example below.
-
-
tsx
```
<Animated.View
···
Note that in order to get this to work on **Android** you need to set the following flags via `UIManager`:
-
tsx
-
```
UIManager.setLayoutAnimationEnabledExperimental(true);
```
···
#### `drawerBackgroundColor`
Specifies the background color of the drawer. The default value is `white`. If you want to set the opacity of the drawer, use rgba. Example:
-
-
tsx
```
return (
···
### Methods
#### `closeDrawer()`
-
-
tsx
```
closeDrawer();
···
#### `openDrawer()`
-
tsx
-
```
openDrawer();
```
···
#### `SelectableBackground()`
-
tsx
-
```
static SelectableBackground(
rippleRadius: number | null,
···
---
#### `SelectableBackgroundBorderless()`
-
-
tsx
```
static SelectableBackgroundBorderless(
···
#### `Ripple()`
-
tsx
-
```
static Ripple(
color: ColorValue,
···
---
#### `canUseNativeForeground()`
-
-
tsx
```
static canUseNativeForeground(): boolean;
···
In order to fetch content from an arbitrary URL, you can pass the URL to fetch:
-
tsx
-
```
fetch('https://mywebsite.com/mydata.json');
```
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:
-
-
tsx
```
fetch('https://mywebsite.com/endpoint/', {
···
Networking is an inherently asynchronous operation. Fetch method will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
-
tsx
-
```
const getMoviesFromApi = () => {
return fetch('https://reactnative.dev/movies.json')
···
You can also use the `async` / `await` syntax in a React Native app:
-
tsx
-
```
const getMoviesFromApiAsync = async () => {
try {
···
### Using Other Networking Libraries
The XMLHttpRequest API is built into React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.
-
-
tsx
```
const request = new XMLHttpRequest();
···
### WebSocket Support
React Native also supports WebSockets, a protocol which provides full-duplex communication channels over a single TCP connection.
-
-
tsx
```
const ws = new WebSocket('ws://host.com/path');
···
On Android, `accessible={true}` property for a react-native View will be translated into native `focusable={true}`.
-
tsx
-
```
<View accessible={true}>
<Text>text one</Text>
···
To use, set the `accessibilityLabel` property to a custom string on your View, Text, or Touchable:
-
tsx
-
```
<TouchableOpacity
accessible={true}
···
A reference to another element nativeID used to build complex forms. The value of `accessibilityLabelledBy` should match the `nativeID` of the related element:
-
tsx
-
```
<View>
<Text nativeID="formLabel">Label for Input Field</Text>
···
An accessibility hint can be used to provide additional context to the user on the result of the action when it is not clear from the accessibility label alone.
Provide the `accessibilityHint` property a custom string on your View, Text, or Touchable:
-
-
tsx
```
<TouchableOpacity
···
By using the `accessibilityLanguage` property, the screen reader will understand which language to use while reading the element's **label**, **value**, and **hint**. The provided string value must follow the BCP 47 specification.
-
tsx
-
```
<View
accessible={true}
···
- **none** Accessibility services should not announce changes to this view.
- **polite** Accessibility services should announce changes to this view.
- **assertive** Accessibility services should interrupt ongoing speech to immediately announce changes to this view.
-
-
tsx
```
<TouchableWithoutFeedback onPress={addOne}>
···
A string that will be used as the title of the large content viewer when it is shown.
Requires `accessibilityShowsLargeContentViewer` to be set to `true`.
-
-
tsx
```
<View
···
Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the `nativeID` of the related element:
-
tsx
-
```
<View>
<Text nativeID="formLabel">Label for Input Field</Text>
···
#### `importantForAccessibility`Android
In the case of two overlapping UI components with the same parent, default accessibility focus can have unpredictable behavior. The `importantForAccessibility` property will resolve this by controlling if a view fires accessibility events and if it is reported to accessibility services. It can be set to `auto`, `yes`, `no` and `no-hide-descendants` (the last value will force accessibility services to ignore the component and all of its children).
-
-
tsx
```
<View style={styles.container}>
···
To handle action requests, a component must implement an `onAccessibilityAction` function. The only argument to this function is an event containing the name of the action to perform. The below example from RNTester shows how to create a component that defines and handles several custom actions.
-
tsx
-
```
<View
accessible={true}
···
### Sending Accessibility EventsAndroid
Sometimes it is useful to trigger an accessibility event on a UI component (i.e. when a custom view appears on a screen or set accessibility focus to a view). Native UIManager module exposes a method ‘sendAccessibilityEvent’ for this purpose. It takes two arguments: a view tag and a type of event. The supported event types are `typeWindowStateChanged`, `typeViewFocused`, and `typeViewClicked`.
-
-
tsx
```
import {Platform, UIManager, findNodeHandle} from 'react-native';
···
Here is how you do it: To define your `Cat` component, first use JavaScript’s `import` to import React and React Native’s `Text` Core Component:
-
tsx
-
```
import React from 'react';
import {Text} from 'react-native';
```
Your component starts as a function:
-
-
tsx
```
const Cat = () => {};
···
Here the `Cat` component will render a `<Text>` element:
-
tsx
-
```
const Cat = () => {
return <Text>Hello, I am your cat!</Text>;
···
```
You can export your function component with JavaScript’s `export default` for use throughout your app like so:
-
-
tsx
```
const Cat = () => {
···
First, you will want to import `useState` from React like so:
-
tsx
-
```
import React, {useState} from 'react';
```
Then you declare the component’s state by calling `useState` inside its function. In this example, `useState` creates an `isHungry` state variable:
-
-
tsx
```
const Cat = (props: CatProps) => {
···
It doesn’t matter what names you use. But it can be handy to think of the pattern as `[<getter>, <setter>] = useState(<initialValue>)`.
Next you add the `Button` Core Component and give it an `onPress` prop:
-
-
tsx
```
<Button
···
Now, when someone presses the button, `onPress` will fire, calling the `setIsHungry(false)`. This sets the state variable `isHungry` to `false`. When `isHungry` is false, the `Button`’s `disabled` prop is set to `true` and its `title` also changes:
-
tsx
-
```
<Button
//..
···
> You might’ve noticed that although `isHungry` is a const, it is seemingly reassignable! What is happening is when a state-setting function like `setIsHungry` is called, its component will re-render. In this case the `Cat` function will run again—and this time, `useState` will give us the next value of `isHungry`.
Finally, put your cats inside a `Cafe` component:
-
-
tsx
```
const Cafe = () => {
···
React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific.
-
tsx
-
```
import {Platform, StyleSheet} from 'react-native';
···
`Platform.OS` will be `ios` when running on iOS and `android` when running on Android.
There is also a `Platform.select` method available that, given an object where keys can be one of `'ios' | 'android' | 'native' | 'default'`, returns the most fitting value for the platform you are currently running on. That is, if you're running on a phone, `ios` and `android` keys will take preference. If those are not specified, `native` key will be used and then the `default` key.
-
-
tsx
```
import {Platform, StyleSheet} from 'react-native';
···
Since it accepts `any` value, you can also use it to return platform-specific components, like below:
-
tsx
-
```
const Component = Platform.select({
ios: () => require('ComponentIOS'),
···
<Component />;
```
-
tsx
-
```
const Component = Platform.select({
native: () => require('ComponentForNative'),
···
#### Detecting the Android versionAndroid
On Android, the `Platform` module can also be used to detect the version of the Android Platform in which the app is running:
-
-
tsx
```
import {Platform} from 'react-native';
···
On iOS, the `Version` is a result of `-[UIDevice systemVersion]`, which is a string with the current version of the operating system. An example of the system version is "10.3". For example, to detect the major version number on iOS:
-
tsx
-
```
import {Platform} from 'react-native';
···
You can then import the component as follows:
-
tsx
-
```
import BigButton from './BigButton';
```
···
```
You can still import it without the `.native` extension, as follows:
-
-
tsx
```
import Container from './Container';
···
Aside from rendering some UI, your components handle events like `onChangeText` for `TextInput` or `onPress` for `Button`. They may also contain other functions and event callbacks. Consider the following example:
-
tsx
-
```
function GroceryShoppingList() {
const [groceryItem, setGroceryItem] = useState('');
···
Component testing libraries such as React Native Testing Library facilitate writing user-centric tests by careful choice of provided APIs. The following example uses `fireEvent` methods `changeText` and `press` that simulate a user interacting with the component and a query function `getAllByText` that finds matching `Text` nodes in the rendered output.
-
tsx
-
```
test('given empty GroceryShoppingList, user can add an item to it', () => {
const {getByPlaceholderText, getByText, getAllByText} = render(
···
Snapshot testing is an advanced kind of testing enabled by Jest. It is a very powerful and low-level tool, so extra attention is advised when using it.
A "component snapshot" is a JSX-like string created by a custom React serializer built into Jest. This serializer lets Jest translate React component trees to string that's human-readable. Put another way: a component snapshot is a textual representation of your component’s render output _generated_ during a test run. It may look like this:
-
-
tsx
```
<Text
···
#### My TouchableX view isn't very responsive
Sometimes, if we do an action in the same frame that we are adjusting the opacity or highlight of a component that is responding to a touch, we won't see that effect until after the `onPress` function has returned. If `onPress` does a `setState` that results in a lot of work and a few frames dropped, this may occur. A solution to this is to wrap any action inside of your `onPress` handler in `requestAnimationFrame`:
-
-
tsx
```
handleOnPress() {
···
### Pattern
-
tsx
-
```
const subscription = BackHandler.addEventListener(
'hardwareBackPress',
···
#### `addEventListener()`
-
tsx
-
```
static addEventListener(
eventName: BackPressEventName,
···
---
#### `exitApp()`
-
-
tsx
```
static exitApp();
···
#### Use `memo()`
`React.memo()` creates a memoized component that will be re-rendered only when the props passed to the component change. We can use this function to optimize the components in the FlatList.
-
-
tsx
```
import React, {memo} from 'react';
···
For class components, move the `renderItem` function outside of the render function, so it won't recreate itself each time the render function is called.
-
tsx
-
```
const renderItem = useCallback(({item}) => (
<View key={item.key}>
···
### Advanced: Automatically inline `require` calls
If you use the React Native CLI to build your app, `require` calls (but not `import`s) will automatically be inlined for you, both in your code and inside any third-party packages (`node_modules`) you use.
-
-
tsx
```
import {useCallback, useState} from 'react';
···
Applications can schedule tasks to run after interactions with the following:
-
tsx
-
```
InteractionManager.runAfterInteractions(() => {
// ...long-running synchronous task...
···
The touch handling system considers one or more active touches to be an 'interaction' and will delay `runAfterInteractions()` callbacks until all touches have ended or been cancelled.
InteractionManager also allows applications to register animations by creating an interaction 'handle' on animation start, and clearing it upon completion:
-
-
tsx
```
const handle = InteractionManager.createInteractionHandle();
···
#### `configureNext()`
-
tsx
-
```
static configureNext(
config: LayoutAnimationConfig,
···
---
#### `create()`
-
-
tsx
```
static create(duration, type, creationProp)
···
#### `check()`
-
tsx
-
```
static check(permission: Permission): Promise<boolean>;
```
···
---
#### `request()`
-
-
tsx
```
static request(
···
---
#### `requestMultiple()`
-
-
tsx
```
static requestMultiple(
···
#### `show()`
-
tsx
-
```
static show(message: string, duration: number);
```
···
This property will only work on Android API 29 and below. For similar functionality on higher Android APIs, consider using snackbar or notification.
-
tsx
-
```
static showWithGravity(message: string, duration: number, gravity: number);
```
···
This property will only work on Android API 29 and below. For similar functionality on higher Android APIs, consider using snackbar or notification.
-
tsx
-
```
static showWithGravityAndOffset(
message: string,
···
Indicates the duration on the screen.
-
tsx
-
```
static SHORT: number;
```
···
#### `LONG`
Indicates the duration on the screen.
-
-
tsx
```
static LONG: number;
···
Indicates the position on the screen.
-
tsx
-
```
static TOP: number;
```
···
Indicates the position on the screen.
-
tsx
-
```
static BOTTOM: number;
```
···
Indicates the position on the screen.
-
tsx
-
```
static CENTER: number;
```
## Appearance
-
-
tsx
```
import {Appearance} from 'react-native';
···
### Example
You can use the `Appearance` module to determine if the user prefers a dark color scheme:
-
-
tsx
```
const colorScheme = Appearance.getColorScheme();
···
#### `getColorScheme()`
-
tsx
-
```
static getColorScheme(): 'light' | 'dark' | null;
```
···
#### `setColorScheme()`
-
tsx
-
```
static setColorScheme('light' | 'dark' | null): void;
```
···
#### `addChangeListener()`
-
tsx
-
```
static addChangeListener(
listener: (preferences: {colorScheme: 'light' | 'dark' | null}) => void,
···
`AppRegistry` is the JS entry point to running all React Native apps. App root components should register themselves with `AppRegistry.registerComponent`, then the native system can load the bundle for the app and then actually run the app when it's ready by invoking `AppRegistry.runApplication`.
-
tsx
-
```
import {Text, AppRegistry} from 'react-native';
···
#### `getAppKeys()`
-
tsx
-
```
static getAppKeys(): string[];
```
···
---
#### `getRegistry()`
-
-
tsx
```
static getRegistry(): {sections: string[]; runnables: Runnable[]};
···
---
#### `getRunnable()`
-
-
tsx
```
static getRunnable(appKey: string): : Runnable | undefined;
···
#### `getSectionKeys()`
-
tsx
-
```
static getSectionKeys(): string[];
```
···
#### `getSections()`
-
tsx
-
```
static getSections(): Record<string, Runnable>;
```
···
#### `registerCancellableHeadlessTask()`
-
tsx
-
```
static registerCancellableHeadlessTask(
taskKey: string,
···
---
#### `registerComponent()`
-
-
tsx
```
static registerComponent(
···
---
#### `registerConfig()`
-
-
tsx
```
static registerConfig(config: AppConfig[]);
···
#### `registerHeadlessTask()`
-
tsx
-
```
static registerHeadlessTask(
taskKey: string,
···
---
#### `registerRunnable()`
-
-
tsx
```
static registerRunnable(appKey: string, func: Runnable): string;
···
#### `registerSection()`
-
tsx
-
```
static registerSection(
appKey: string,
···
#### `runApplication()`
-
tsx
-
```
static runApplication(appKey: string, appParameters: any): void;
```
···
#### `setComponentProviderInstrumentationHook()`
-
tsx
-
```
static setComponentProviderInstrumentationHook(
hook: ComponentProviderInstrumentationHook,
···
#### `setWrapperComponentProvider()`
-
tsx
-
```
static setWrapperComponentProvider(
provider: WrapperComponentProvider,
···
---
#### `startHeadlessTask()`
-
-
tsx
```
static startHeadlessTask(
···
#### `unmountApplicationComponentAtRootTag()`
-
tsx
-
```
static unmountApplicationComponentAtRootTag(rootTag: number);
```
···
You should get a higher resolution image if you are on a high pixel density device. A good rule of thumb is to multiply the size of the image you display by the pixel ratio.
-
tsx
-
```
const image = getImage({
width: PixelRatio.getPixelSizeForLayoutSize(200),
···
### Methods
#### `get()`
-
-
tsx
```
static get(): number;
···
#### `getFontScale()`
-
tsx
-
```
static getFontScale(): number;
```
···
#### `getPixelSizeForLayoutSize()`
-
tsx
-
```
static getPixelSizeForLayoutSize(layoutSize: number): number;
```
···
---
#### `roundToNearestPixel()`
-
-
tsx
```
static roundToNearestPixel(layoutSize: number): number;
···
#### Require&#x64;**`renderItem`**&#x200B;
-
tsx
-
```
renderItem({
item: ItemT,
···
Example usage:
-
tsx
-
```
<FlatList
ItemSeparatorComponent={
···
#### `getItemLayout`
-
tsx
-
```
(data, index) => {length: number, offset: number, index: number}
```
`getItemLayout` is an optional optimization that allows skipping the measurement of dynamic content if you know the size (height or width) of items ahead of time. `getItemLayout` is efficient if you have fixed size items, for example:
-
-
tsx
```
getItemLayout={(data, index) => (
···
#### `keyExtractor`
-
tsx
-
```
(item: ItemT, index: number) => string;
```
···
---
#### `onRefresh`
-
-
tsx
```
() => void;
···
Error: Changing viewabilityConfig on the fly is not supported
```
-
tsx
-
```
constructor (props) {
super(props)
···
}
```
-
tsx
-
```
<FlatList
viewabilityConfig={this.viewabilityConfig}
···
#### `flashScrollIndicators()`
-
tsx
-
```
flashScrollIndicators();
```
···
---
#### `getNativeScrollRef()`
-
-
tsx
```
getNativeScrollRef(): React.ElementRef<typeof ScrollViewComponent>;
···
#### `getScrollResponder()`
-
tsx
-
```
getScrollResponder(): ScrollResponderMixin;
```
···
#### `getScrollableNode()`
-
tsx
-
```
getScrollableNode(): any;
```
···
Provides a handle to the underlying scroll node.
#### `scrollToEnd()`
-
-
tsx
```
scrollToEnd(params?: {animated?: boolean});
···
#### `scrollToIndex()`
-
tsx
-
```
scrollToIndex: (params: {
index: number;
···
#### `scrollToItem()`
-
tsx
-
```
scrollToItem(params: {
animated?: ?boolean,
···
---
#### `scrollToOffset()`
-
-
tsx
```
scrollToOffset(params: {
···
#### `addEventListener()`
-
tsx
-
```
static addEventListener(
eventName: AccessibilityChangeEventName | AccessibilityAnnouncementEventName,
···
#### `announceForAccessibility()`
-
tsx
-
```
static announceForAccessibility(announcement: string);
```
···
---
#### `announceForAccessibilityWithOptions()`
-
-
tsx
```
static announceForAccessibilityWithOptions(
···
#### `getRecommendedTimeoutMillis()`Android
-
tsx
-
```
static getRecommendedTimeoutMillis(originalTimeout: number): Promise<number>;
```
···
#### `isAccessibilityServiceEnabled()`Android
-
tsx
-
```
static isAccessibilityServiceEnabled(): Promise<boolean>;
```
···
#### `isBoldTextEnabled()`iOS
-
tsx
-
```
static isBoldTextEnabled(): Promise<boolean>:
```
···
---
#### `isGrayscaleEnabled()`iOS
-
-
tsx
```
static isGrayscaleEnabled(): Promise<boolean>;
···
#### `isInvertColorsEnabled()`iOS
-
tsx
-
```
static isInvertColorsEnabled(): Promise<boolean>;
```
···
#### `isReduceMotionEnabled()`
-
tsx
-
```
static isReduceMotionEnabled(): Promise<boolean>;
```
···
---
#### `isReduceTransparencyEnabled()`iOS
-
-
tsx
```
static isReduceTransparencyEnabled(): Promise<boolean>;
···
---
#### `isScreenReaderEnabled()`
-
-
tsx
```
static isScreenReaderEnabled(): Promise<boolean>;
···
#### `prefersCrossFadeTransitions()`iOS
-
tsx
-
```
static prefersCrossFadeTransitions(): Promise<boolean>;
```
···
---
#### `setAccessibilityFocus()`
-
-
tsx
```
static setAccessibilityFocus(reactTag: number);
···
#### `addEventListener()`
-
tsx
-
```
static addEventListener(
type: AppStateEvent,
···
#### `currentState`
-
tsx
-
```
static currentState: AppStateStatus;
```
···
### Properties
#### `constants`
-
-
tsx
```
static constants: PlatformConstants;
···
#### `isPad`iOS
-
tsx
-
```
static isPad: boolean;
```
···
#### `isTV`
-
tsx
-
```
static isTV: boolean;
```
···
#### `isVision`
-
tsx
-
```
static isVision: boolean;
```
···
---
#### `isTesting`
-
-
tsx
```
static isTesting: boolean;
···
---
#### `OS`
-
-
tsx
```
static OS: 'android' | 'ios';
···
#### `Version`
-
tsx
-
```
static Version: 'number' | 'string';
```
···
### Methods
#### `select()`
-
-
tsx
```
static select(config: Record<string, T>): T;
···
**Example usage:**
-
tsx
-
```
import {Platform, StyleSheet} from 'react-native';
···
Since the value of the corresponding platform key can be of type `any`, `select` method can also be used to return platform-specific components, like below:
-
tsx
-
```
const Component = Platform.select({
ios: () => require('ComponentIOS'),
···
<Component />;
```
-
-
tsx
```
const Component = Platform.select({
···
#### `flashScrollIndicators()`iOS
-
tsx
-
```
flashScrollIndicators();
```
···
#### `recordInteraction()`
-
tsx
-
```
recordInteraction();
```
···
#### `scrollToLocation()`
-
tsx
-
```
scrollToLocation(params: SectionListScrollParams);
```
···
#### `addMenuItem()`
-
tsx
-
```
static addMenuItem(title: string, handler: () => any);
```
···
**Example:**
-
tsx
-
```
DevSettings.addMenuItem('Show Secret Dev Screen', () => {
Alert.alert('Showing secret dev screen!');
···
---
#### `reload()`
-
-
tsx
```
static reload(reason?: string): void;
···
**Example:**
-
tsx
-
```
<Button title="Reload" onPress={() => DevSettings.reload()} />
```
···
### Reference
### Methods
-
-
tsx
```
static share(content: ShareContent, options?: ShareOptions);
···
#### `sharedAction`
-
tsx
-
```
static sharedAction: 'sharedAction';
```
···
---
#### `dismissedAction`iOS
-
-
tsx
```
static dismissedAction: 'dismissedAction';
···
#### Require&#x64;**`getItem`**&#x200B;
-
tsx
-
```
(data: any, index: number) => any;
```
···
#### Require&#x64;**`getItemCount`**&#x200B;
-
tsx
-
```
(data: any) => number;
```
···
---
#### Require&#x64;**`renderItem`**&#x200B;
-
-
tsx
```
(info: any) => ?React.Element<any>
···
#### `getItemLayout`
-
tsx
-
```
(
data: any,
···
#### `keyExtractor`
-
tsx
-
```
(item: any, index: number) => string;
```
···
#### `onRefresh`
-
tsx
-
```
() => void;
```
···
---
#### `onScrollToIndexFailed`
-
-
tsx
```
(info: {
···
#### `renderScrollComponent`
-
tsx
-
```
(props: object) => element;
```
···
#### `flashScrollIndicators()`
-
tsx
-
```
flashScrollIndicators();
```
···
#### `getScrollableNode()`
-
tsx
-
```
getScrollableNode(): any;
```
···
#### `getScrollRef()`
-
tsx
-
```
getScrollRef():
| React.ElementRef<typeof ScrollView>
···
---
#### `getScrollResponder()`
-
-
tsx
```
getScrollResponder () => ScrollResponderMixin | null;
···
#### `scrollToEnd()`
-
tsx
-
```
scrollToEnd(params?: {animated?: boolean});
```
···
#### `scrollToIndex()`
-
tsx
-
```
scrollToIndex(params: {
index: number;
···
---
#### `scrollToItem()`
-
-
tsx
```
scrollToItem(params: {
···
---
#### `scrollToOffset()`
-
-
tsx
```
scrollToOffset(params: {
···
#### `compose()`
-
tsx
-
```
static compose(style1: Object, style2: Object): Object | Object[];
```
···
#### `create()`
-
tsx
-
```
static create(styles: Object extends Record<string, ViewStyle | ImageStyle | TextStyle>): Object;
```
···
---
#### `flatten()`
-
-
tsx
```
static flatten(style: Array<Object extends Record<string, ViewStyle | ImageStyle | TextStyle>>): Object;
···
> **WARNING: EXPERIMENTAL.** Breaking changes will probably happen a lot and will not be reliably announced. The whole thing might be deleted, who knows? Use at your own risk.
-
tsx
-
```
static setStyleAttributePreprocessor(
property: string,
···
#### `setValue()`
-
tsx
-
```
setValue(value: number);
```
···
---
#### `setOffset()`
-
-
tsx
```
setOffset(offset: number);
···
#### `flattenOffset()`
-
tsx
-
```
flattenOffset();
```
···
#### `extractOffset()`
-
tsx
-
```
extractOffset();
```
···
---
#### `addListener()`
-
-
tsx
```
addListener(callback: (state: {value: number}) => void): string;
···
#### `removeListener()`
-
tsx
-
```
removeListener(id: string);
```
···
#### `removeAllListeners()`
-
tsx
-
```
removeAllListeners();
```
···
#### `stopAnimation()`
-
tsx
-
```
stopAnimation(callback?: (value: number) => void);
```
···
---
#### `resetAnimation()`
-
-
tsx
```
resetAnimation(callback?: (value: number) => void);
···
#### `interpolate()`
-
tsx
-
```
interpolate(config: InterpolationConfigType);
```
···
#### `animate()`
-
tsx
-
```
animate(animation, callback);
```
···
## Dimensions
> `useWindowDimensions` is the preferred API for React components. Unlike `Dimensions`, it updates as the window's dimensions update. This works nicely with the React paradigm.
-
-
tsx
```
import {Dimensions} from 'react-native';
···
You can get the application window's width and height using the following code:
-
tsx
-
```
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
···
#### `addEventListener()`
-
tsx
-
```
static addEventListener(
type: 'change',
···
---
#### `get()`
-
-
tsx
```
static get(dim: 'window' | 'screen'): ScaledSize;
···
#### `isEnabled()`
-
tsx
-
```
static isEnabled(): boolean;
```
···
---
#### `beginEvent()`
-
-
tsx
```
static beginEvent(eventName: string | (() => string), args?: EventArgs);
···
#### `endEvent()`
-
tsx
-
```
static endEvent(args?: EventArgs);
```
···
---
#### `beginAsyncEvent()`
-
-
tsx
```
static beginAsyncEvent(
···
#### `endAsyncEvent()`
-
tsx
-
```
static endAsyncEvent(
eventName: EventName,
···
---
#### `counterEvent()`
-
-
tsx
```
static counterEvent(eventName: string | (() => string), value: number);
···
#### `step0()`
-
tsx
-
```
static step0(n: number);
```
···
---
#### `step1()`
-
-
tsx
```
static step1(n: number);
···
#### `linear()`
-
tsx
-
```
static linear(t: number);
```
···
---
#### `ease()`
-
-
tsx
```
static ease(t: number);
···
#### `quad()`
-
tsx
-
```
static quad(t: number);
```
···
#### `cubic()`
-
tsx
-
```
static cubic(t: number);
```
···
---
#### `poly()`
-
-
tsx
```
static poly(n: number);
···
#### `sin()`
-
tsx
-
```
static sin(t: number);
```
···
#### `circle()`
-
tsx
-
```
static circle(t: number);
```
···
#### `exp()`
-
tsx
-
```
static exp(t: number);
```
···
---
#### `elastic()`
-
-
tsx
```
static elastic(bounciness: number);
···
#### `back()`
-
tsx
-
```
static back(s)
```
···
#### `bounce()`
-
tsx
-
```
static bounce(t: number);
```
···
---
#### `bezier()`
-
-
tsx
```
static bezier(x1: number, y1: number, x2: number, y2: number);
···
#### `in()`
-
tsx
-
```
static in(easing: number);
```
···
#### `out()`
-
tsx
-
```
static out(easing: number);
```
···
---
#### `inOut()`
-
-
tsx
```
static inOut(easing: number);
···
#### `cancel()`
-
tsx
-
```
static cancel();
```
···
#### `vibrate()`
-
tsx
-
```
static vibrate(
pattern?: number | number[],
···
#### `setValue()`
-
tsx
-
```
setValue(value: {x: number; y: number});
```
···
---
#### `setOffset()`
-
-
tsx
```
setOffset(offset: {x: number; y: number});
···
#### `flattenOffset()`
-
tsx
-
```
flattenOffset();
```
···
#### `extractOffset()`
-
tsx
-
```
extractOffset();
```
···
---
#### `addListener()`
-
-
tsx
```
addListener(callback: (value: {x: number; y: number}) => void);
···
#### `removeListener()`
-
tsx
-
```
removeListener(id: string);
```
···
#### `removeAllListeners()`
-
tsx
-
```
removeAllListeners();
```
···
---
#### `stopAnimation()`
-
-
tsx
```
stopAnimation(callback?: (value: {x: number; y: number}) => void);
···
#### `resetAnimation()`
-
tsx
-
```
resetAnimation(callback?: (value: {x: number; y: number}) => void);
```
···
#### `getLayout()`
-
tsx
-
```
getLayout(): {left: Animated.Value, top: Animated.Value};
```
Converts `{x, y}` into `{left, top}` for use in style, e.g.
-
-
tsx
```
style={this.state.anim.getLayout()}
···
#### `getTranslateTransform()`
-
tsx
-
```
getTranslateTransform(): [
{translateX: Animated.Value},
···
Converts `{x, y}` into a useable translation transform, e.g.
-
tsx
-
```
style={{
transform: this.state.anim.getTranslateTransform()
···
## useColorScheme
-
tsx
-
```
import {useColorScheme} from 'react-native';
```
···
## useWindowDimensions
-
tsx
-
```
import {useWindowDimensions} from 'react-native';
```
`useWindowDimensions` automatically updates all of its values when screen size or font scale changes. You can get your application window's width and height like so:
-
-
tsx
```
const {height, width} = useWindowDimensions();
···
#### `fontScale`
-
tsx
-
```
useWindowDimensions().fontScale;
```
···
---
#### `height`
-
-
tsx
```
useWindowDimensions().height;
···
#### `scale`
-
tsx
-
```
useWindowDimensions().scale;
```
···
#### `width`
-
tsx
-
```
useWindowDimensions().width;
```
···
### Methods
#### `addListener()`
-
-
tsx
```
static addListener: (
···
#### `dismiss()`
-
tsx
-
```
static dismiss();
```
···
#### `scheduleLayoutAnimation`
-
tsx
-
```
static scheduleLayoutAnimation(event: KeyboardEvent);
```
···
---
#### `isVisible()`
-
-
tsx
```
static isVisible(): boolean;
···
---
#### `metrics()`
-
-
tsx
```
static metrics(): KeyboardMetrics | undefined;
···
#### `alert()`
```
static alert (
title: string,
···
---
#### `prompt()`iOS
```
static prompt: (
···
#### `addEventListener()`
```
static addEventListener(
type: 'url',
···
---
#### `canOpenURL()`
```
static canOpenURL(url: string): Promise<boolean>;
···
#### `getInitialURL()`
```
static getInitialURL(): Promise<string | null>;
```
···
#### `openSettings()`
```
static openSettings(): Promise<void>;
```
···
---
#### `openURL()`
```
static openURL(url: string): Promise<any>;
···
#### `sendIntent()`Android
```
static sendIntent(
action: string,
···
#### `showActionSheetWithOptions()`
```
static showActionSheetWithOptions: (
options: ActionSheetIOSOptions,
···
Minimal example:
```
ActionSheetIOS.showActionSheetWithOptions(
{
···
#### `dismissActionSheet()`
```
static dismissActionSheet();
```
···
---
#### `showShareActionSheetWithOptions()`
```
static showShareActionSheetWithOptions: (
···
2. For iOS only, navigate in the `App/ios` folder and run `bundle exec pod install` to install your dependencies.
3. Update the `App.tsx` code to import the code in your library. For example:
```
import NativeSampleModule from '../Library/src/index';
```
···
A task is an async function that you register on `AppRegistry`, similar to registering React applications:
```
import {AppRegistry} from 'react-native';
AppRegistry.registerHeadlessTask('SomeTaskName', () =>
···
```
Then, in `SomeTaskName.js`:
```
module.exports = async taskData => {
···
Example:
```
import {HeadlessJsTaskError} from 'HeadlessJsTask';
···
}
}
```
```
import React from 'react';
···
moduleName:@"ImageBrowserApp"
initialProperties:props];
```
```
import React from 'react';
···
### Usage Pattern
```
const ExampleComponent = () => {
const panResponder = React.useRef(
···
### Methods
#### `create()`
```
static create(config: PanResponderCallbacks): PanResponderInstance;
···
The native module can then be accessed in JS like this:
```
const {CalendarModule} = ReactNative.NativeModules;
```
···
Find a place in your application where you would like to add a call to the native module’s `createCalendarEvent()` method. Below is an example of a component, `NewModuleButton` you can add in your app. You can invoke the native module inside `NewModuleButton`'s `onPress()` function.
```
import React from 'react';
import {NativeModules, Button} from 'react-native';
···
In order to access your native module from JavaScript you need to first import `NativeModules` from React Native:
```
import {NativeModules} from 'react-native';
```
You can then access the `CalendarModule` native module off of `NativeModules`.
```
const {CalendarModule} = NativeModules;
```
Now that you have the CalendarModule native module available, you can invoke your native method `createCalendarEvent()`. Below it is added to the `onPress()` method in `NewModuleButton`:
```
const onPress = () => {
···
To save consumers of your native module from needing to do that each time they want to access your native module, you can create a JavaScript wrapper for the module. Create a new JavaScript file named `CalendarModule.js` with the following content:
```
/**
* This exposes the native CalendarModule module as a JS module. This has a
···
This JavaScript file also becomes a good location for you to add any JavaScript side functionality. For example, if you use a type system like TypeScript you can add type annotations for your native module here. While React Native does not yet support Native to JS type safety, all your JS code will be type safe. Doing so will also make it easier for you to switch to type-safe native modules down the line. Below is an example of adding type safety to the CalendarModule:
```
/**
* This exposes the native CalendarModule module as a JS module. This has a
···
```
In your other JavaScript files you can access the native module and invoke its method like this:
```
import CalendarModule from './CalendarModule';
···
The constant can then be accessed by invoking `getConstants` on the native module in JS:
```
const {DEFAULT_EVENT_NAME} = CalendarModule.getConstants();
console.log(DEFAULT_EVENT_NAME);
···
This method could then be accessed in JavaScript using:
```
const onPress = () => {
CalendarModule.createCalendarEvent(
···
```
In JavaScript, you can then check the first argument to see if an error was passed through:
```
const onPress = () => {
···
```
Then in JavaScript you can add a separate callback for error and success responses:
```
const onPress = () => {
···
The JavaScript counterpart of this method returns a Promise. This means you can use the `await` keyword within an async function to call it and wait for its result:
```
const onSubmit = async () => {
try {
···
```
JavaScript modules can then register to receive events by `addListener` on the NativeEventEmitter class.
```
import {NativeEventEmitter, NativeModules} from 'react-native';
···
```
The native module can then be accessed in JS like this:
```
const {CalendarModuleFoo} = ReactNative.NativeModules;
···
The native module can then be accessed in JS like this:
```
const {CalendarModule} = ReactNative.NativeModules;
```
···
Find a place in your application where you would like to add a call to the native module’s `createCalendarEvent()` method. Below is an example of a component, `NewModuleButton` you can add in your app. You can invoke the native module inside `NewModuleButton`'s `onPress()` function.
```
import React from 'react';
import {Button} from 'react-native';
···
```
In order to access your native module from JavaScript you need to first import `NativeModules` from React Native:
```
import {NativeModules} from 'react-native';
···
You can then access the `CalendarModule` native module off of `NativeModules`.
```
const {CalendarModule} = NativeModules;
```
Now that you have the CalendarModule native module available, you can invoke your native method `createCalendarEvent()`. Below it is added to the `onPress()` method in `NewModuleButton`:
```
const onPress = () => {
···
Importing your native module by pulling it off of `NativeModules` like above is a bit clunky.
To save consumers of your native module from needing to do that each time they want to access your native module, you can create a JavaScript wrapper for the module. Create a new JavaScript file named NativeCalendarModule.js with the following content:
```
/**
···
This JavaScript file also becomes a good location for you to add any JavaScript side functionality. For example, if you use a type system like TypeScript you can add type annotations for your native module here. While React Native does not yet support Native to JS type safety, with these type annotations, all your JS code will be type safe. These annotations will also make it easier for you to switch to type-safe native modules down the line. Below is an example of adding type safety to the Calendar Module:
```
/**
* This exposes the native CalendarModule module as a JS module. This has a
···
```
In your other JavaScript files you can access the native module and invoke its method like this:
```
import NativeCalendarModule from './NativeCalendarModule';
···
```
The constant can then be accessed by invoking `getConstants()` on the native module in JS like so:
```
const {DEFAULT_EVENT_NAME} = CalendarModule.getConstants();
···
This method could then be accessed in JavaScript using the following:
```
const onSubmit = () => {
CalendarModule.createCalendarEvent(
···
```
In JavaScript, you can then check the first argument to see if an error was passed through:
```
const onPress = () => {
···
Then in JavaScript you can add a separate callback for error and success responses:
```
const onPress = () => {
CalendarModule.createCalendarEventCallback(
···
```
The JavaScript counterpart of this method returns a Promise. This means you can use the `await` keyword within an async function to call it and wait for its result:
```
const onSubmit = async () => {
···
#### Create a `App.tsx` file
Let's create an `App.tsx` file. This is a TypeScript file that can have JSX expressions. It contains the root React Native component that we will integrate into our Android application (link):
```
import React from 'react';
···
Let's create an `App.tsx` file. This is a TypeScript file that can have JSX expressions. It contains the root React Native component that we will integrate into our iOS application (link):
```
import React from 'react';
import {
···
A React Native view can have more than one child view in the view tree eg.
```
<View>
<MyNativeView />
···
In this example, the class `MyNativeView` is a wrapper for a `NativeComponent` and exposes methods, which will be called on the iOS platform. `MyNativeView` is defined in `MyNativeView.ios.js` and contains proxy methods of `NativeComponent`.
When the user interacts with the component, like clicking the button, the `backgroundColor` of `MyNativeView` changes. In this case `UIManager` would not know which `MyNativeView` should be handled and which one should change `backgroundColor`. Below you will find a solution to this problem:
```
<View>
···
TouchableOpacity uses `setNativeProps` internally to update the opacity of its child component:
```
const viewRef = useRef<View>();
const setOpacityTo = useCallback(value => {
···
```
This allows us to write the following code and know that the child will have its opacity updated in response to taps, without the child having any knowledge of that fact or requiring any changes to its implementation:
```
<TouchableOpacity onPress={handlePress}>
···
```
Let's imagine that `setNativeProps` was not available. One way that we might implement it with that constraint is to store the opacity value in the state, then update that value whenever `onPress` is fired:
```
const [buttonOpacity, setButtonOpacity] = useState(1);
···
#### `aria-labelledby`Android
Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the `nativeID` of the related element:
```
<View>
···
If this button doesn't look right for your app, you can build your own button using Pressable. For inspiration, look at the source code for the Button component.
```
<Button
onPress={onPressLearnMore}
···
#### Working with animations
Animations are started by calling `start()` on your animation. `start()` takes a completion callback that will be called when the animation is done. If the animation finished running normally, the completion callback will be invoked with `{finished: true}`. If the animation is done because `stop()` was called on it before it could finish (e.g. because it was interrupted by a gesture or another animation), then it will receive `{finished: false}`.
```
Animated.timing({}).start(({finished}) => {
···
For example, when working with horizontal scrolling gestures, you would do the following in order to map `event.nativeEvent.contentOffset.x` to `scrollX` (an `Animated.Value`):
```
onScroll={Animated.event(
// scrollX = e.nativeEvent.contentOffset.x
···
#### `decay()`
```
static decay(value, config): CompositeAnimation;
```
···
---
#### `timing()`
```
static timing(value, config): CompositeAnimation;
···
#### `spring()`
```
static spring(value, config): CompositeAnimation;
```
···
#### `add()`
```
static add(a: Animated, b: Animated): AnimatedAddition;
```
···
---
#### `subtract()`
```
static subtract(a: Animated, b: Animated): AnimatedSubtraction;
···
#### `divide()`
```
static divide(a: Animated, b: Animated): AnimatedDivision;
```
···
#### `multiply()`
```
static multiply(a: Animated, b: Animated): AnimatedMultiplication;
```
···
---
#### `modulo()`
```
static modulo(a: Animated, modulus: number): AnimatedModulo;
···
#### `diffClamp()`
```
static diffClamp(a: Animated, min: number, max: number): AnimatedDiffClamp;
```
···
#### `delay()`
```
static delay(time: number): CompositeAnimation;
```
···
#### `sequence()`
```
static sequence(animations: CompositeAnimation[]): CompositeAnimation;
```
···
---
#### `parallel()`
```
static parallel(
···
---
#### `stagger()`
```
static stagger(
···
#### `loop()`
```
static loop(
animation: CompositeAnimation[],
···
#### `event()`
```
static event(
argMapping: Mapping[],
···
Takes an array of mappings and extracts values from each arg accordingly, then calls `setValue` on the mapped outputs. e.g.
```
onScroll={Animated.event(
[{nativeEvent: {contentOffset: {x: this._scrollX}}}],
···
#### `start()`
```
static start(callback?: (result: {finished: boolean}) => void);
```
···
| callback | `(result: {finished: boolean}) => void` | No | Function that will be called after the animation finished running normally or when the animation is done because stop() was called on it before it could finish |
Start example with callback:
```
Animated.timing({}).start(({finished}) => {
···
#### `stop()`
```
static stop();
```
···
---
#### `reset()`
```
static reset();
···
#### `abortPrefetch()`Android
```
static abortPrefetch(requestId: number);
```
···
---
#### `getSize()`
```
static getSize(uri: string): Promise<{width: number, height: number}>;
···
#### `getSizeWithHeaders()`
```
static getSizeWithHeaders(
uri: string,
···
---
#### `prefetch()`
```
await Image.prefetch(url);
···
#### `queryCache()`
```
static queryCache(
urls: string[],
···
---
#### `resolveAssetSource()`
```
static resolveAssetSource(source: ImageSourcePropType): {
···
## Pressable
Pressable is a Core Component wrapper that can detect various stages of press interactions on any of its defined children.
```
<Pressable onPress={onPressFunction}>
···
### Methods
#### `flashScrollIndicators()`
```
flashScrollIndicators();
···
#### `scrollTo()`
```
scrollTo(
options?: {x?: number, y?: number, animated?: boolean} | number,
···
---
#### `scrollToEnd()`
```
scrollToEnd(options?: {animated?: boolean});
···
#### `popStackEntry()`
```
static popStackEntry(entry: StatusBarProps);
```
···
---
#### `pushStackEntry()`
```
static pushStackEntry(props: StatusBarProps): StatusBarProps;
···
#### `replaceStackEntry()`
```
static replaceStackEntry(
entry: StatusBarProps,
···
#### `setBackgroundColor()`Android
```
static setBackgroundColor(color: ColorValue, animated?: boolean);
```
···
#### `setBarStyle()`
```
static setBarStyle(style: StatusBarStyle, animated?: boolean);
```
···
---
#### `setHidden()`
```
static setHidden(hidden: boolean, animation?: StatusBarAnimation);
···
#### `setNetworkActivityIndicatorVisible()`iOS
```
static setNetworkActivityIndicatorVisible(visible: boolean);
```
···
---
#### `setTranslucent()`Android
```
static setTranslucent(translucent: boolean);
···
The `<Text>` element is unique relative to layout: everything inside is no longer using the Flexbox layout but using text layout. This means that elements inside of a `<Text>` are no longer rectangles, but wrap when they see the end of the line.
```
<Text>
<Text>First part and </Text>
···
In React Native, we are more strict about it: **you must wrap all the text nodes inside of a `<Text>` component**. You cannot have a text node directly under a `<View>`.
```
// BAD: will raise exception, can't have a text node as child of a <View>
<View>
···
```
You also lose the ability to set up a default font for an entire subtree. Meanwhile, `fontFamily` only accepts a single font name, which is different from `font-family` in CSS. The recommended way to use consistent fonts and sizes across your application is to create a component `MyAppText` that includes them and use this component across your app. You can also use this component to make more specific components like `MyAppHeaderText` for other kinds of text.
```
<View>
···
Assuming that `MyAppText` is a component that only renders out its children into a `Text` component with styling, then `MyAppHeaderText` can be defined as follows:
```
const MyAppHeaderText = ({children}) => {
return (
···
Composing `MyAppText` in this way ensures that we get the styles from a top-level component, but leaves us the ability to add/override them in specific use cases.
React Native still has the concept of style inheritance, but limited to text subtrees. In this case, the second part will be both bold and red.
```
<Text style={{fontWeight: 'bold'}}>
···
#### `.focus()`
```
focus();
```
···
Makes the native input request focus.
#### `.blur()`
```
blur();
···
#### `clear()`
```
clear();
```
···
#### `isFocused()`
```
isFocused(): boolean;
```
···
React Native provides a unified way of managing images and other media assets in your Android and iOS apps. To add a static image to your app, place it somewhere in your source code tree and reference it like this:
```
<Image source={require('./my-icon.png')} />
```
···
...and `button.js` code contains:
```
<Image source={require('./img/check.png')} />
```
···
7. Images can be distributed via npm packages.
In order for this to work, the image name in `require` has to be known statically.
```
// GOOD
···
For images included via Xcode asset catalogs or in the Android drawable folder, use the image name without the extension:
```
<Image
source={{uri: 'app_icon'}}
···
```
For images in the Android assets folder, use the `asset:/` scheme:
```
<Image
···
Many of the images you will display in your app will not be available at compile time, or you will want to load some dynamically to keep the binary size down. Unlike with static resources, _you will need to manually specify the dimensions of your image_. It's highly recommended that you use https as well in order to satisfy App Transport Security requirements on iOS.
```
// GOOD
<Image source={{uri: 'https://reactjs.org/logo-og.png'}}
···
If you would like to set such things as the HTTP-Verb, Headers or a Body along with the image request, you may do this by defining these properties on the source object:
```
<Image
source={{
···
This is recommended for very small and dynamic images only, like icons in a list from a DB.
```
// include at least width and height!
<Image
···
- `force-cache`: The existing cached data will be used to satisfy the request, regardless of its age or expiration date. If there is no existing data in the cache corresponding the request, the data is loaded from the originating source.
- `only-if-cached`: The existing cache data will be used to satisfy a request, regardless of its age or expiration date. If there is no existing data in the cache corresponding to a URL load request, no attempt is made to load the data from the originating source, and the load is considered to have failed.
```
<Image
source={{
···
Android supports loading drawable resources via the `xml` file type. This means you can use vector drawables for rendering icons or shape drawables for, well, drawing shapes! You can import and use these resource types the same as any other static resource or hybrid resource. You have to specify image dimensions manually.
For static drawables that live alongside your JS code, use the `require` or `import` syntax (both work the same):
```
<Image
···
For drawables included in the Android drawable folder (i.e. `res/drawable`), use the resource name without the extension:
```
<Image
source={{uri: 'my_icon'}}
···
For example, the result of `require('./my-icon.png')` might be:
```
{"__packager_asset":true,"uri":"my-icon.png","width":591,"height":573}
```
···
In React Native, one interesting decision is that the `src` attribute is named `source` and doesn't take a string but an object with a `uri` attribute.
```
<Image source={{uri: 'something.jpg'}} />
```
···
A common feature request from developers familiar with the web is `background-image`. To handle this use case, you can use the `<ImageBackground>` component, which has the same props as `<Image>`, and add whatever children to it you would like to layer on top of it.
You might not want to use `<ImageBackground>` in some cases, since the implementation is basic. Refer to `<ImageBackground>`'s documentation for more insight, and create your own custom component when needed.
```
return (
···
The underlay comes from wrapping the child in a new View, which can affect layout, and sometimes cause unwanted visual artifacts if not used correctly, for example if the backgroundColor of the wrapped view isn't explicitly set to an opaque color.
TouchableHighlight must have one child (not zero or more than one). If you wish to have several child components, wrap them in a View.
```
function MyComponent(props: MyComponentProps) {
···
### Displaying a basic button
Button provides a basic button component that is rendered nicely on all platforms. The minimal example to display a button looks like this:
```
<Button
···
### Usage Pattern
```
function MyComponent(props: MyComponentProps) {
return (
···
Now, you need to wrap the whole app in `NavigationContainer`. Usually you'd do this in your entry file, such as `index.js` or `App.js`:
```
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
···
#### Usage
Now you can create an app with a home screen and a profile screen:
```
import * as React from 'react';
···
You can set options such as the screen title for each screen in the `options` prop of `Stack.Screen`.
Each screen takes a `component` prop that is a React component. Those components receive a prop called `navigation` which has various methods to link to other screens. For example, you can use `navigation.navigate` to go to the `Profile` screen:
```
const HomeScreen = ({navigation}) => {
···
For example, if we want to create a 2-second long animation of an object that slightly backs up before moving to its final position:
```
Animated.timing(this.state.xPosition, {
toValue: 100,
···
For example, the following animation coasts to a stop, then it springs back while twirling in parallel:
```
Animated.sequence([
// decay, then spring to start and twirl
···
There are some cases where an animated value needs to invert another animated value for calculation. An example is inverting a scale (2x There are some cases where an animated value needs to invert another animated value for calculation. An example is inverting a scale (2x --> 0.5x):
```
const a = new Animated.Value(1);
const b = Animated.divide(1, a);
···
A basic mapping to convert a 0-1 range to a 0-100 range would be:
```
value.interpolate({
inputRange: [0, 1],
···
For example, you may want to think about your `Animated.Value` as going from 0 to 1, but animate the position from 150px to 0px and the opacity from 0 to 1. This can be done by modifying `style` from the example above like so:
```
style={{
opacity: this.state.fadeAnim, // Binds directly
···
```
`interpolate()` supports multiple range segments as well, which is handy for defining dead zones and other handy tricks. For example, to get a negation relationship at -300 that goes to 0 at -100, then back up to 1 at 0, and then back down to zero at 100 followed by a dead-zone that remains at 0 for everything beyond that, you could do:
```
value.interpolate({
···
`interpolate()` also supports mapping to strings, allowing you to animate colors as well as values with units. For example, if you wanted to animate a rotation you could do:
```
value.interpolate({
inputRange: [0, 360],
···
Animated values can also track other values by setting the `toValue` of an animation to another animated value instead of a plain number. For example, a "Chat Heads" animation like the one used by Messenger on Android could be implemented with a `spring()` pinned on another animated value, or with `timing()` and a `duration` of 0 for rigid tracking. They can also be composed with interpolations:
```
Animated.spring(follower, {toValue: leader}).start();
Animated.timing(opacity, {
···
Gestures, like panning or scrolling, and other events can map directly to animated values using `Animated.event`. This is done with a structured map syntax so that values can be extracted from complex event objects. The first level is an array to allow mapping across multiple args, and that array contains nested objects.
For example, when working with horizontal scrolling gestures, you would do the following in order to map `event.nativeEvent.contentOffset.x` to `scrollX` (an `Animated.Value`):
```
onScroll={Animated.event(
···
When using `PanResponder`, you could use the following code to extract the x and y positions from `gestureState.dx` and `gestureState.dy`. We use a `null` in the first position of the array, as we are only interested in the second argument passed to the `PanResponder` handler, which is the `gestureState`.
```
onPanResponderMove={Animated.event(
[null, // ignore the native event
···
Using the native driver for normal animations can be accomplished by setting `useNativeDriver: true` in animation config when starting it. Animations without a `useNativeDriver` property will default to false for legacy reasons, but emit a warning (and typechecking error in TypeScript).
```
Animated.timing(this.state.animatedValue, {
toValue: 1,
···
Animated values are only compatible with one driver so if you use native driver when starting an animation on a value, make sure every animation on that value also uses the native driver.
The native driver also works with `Animated.event`. This is especially useful for animations that follow the scroll position as without the native driver, the animation will always run a frame behind the gesture due to the async nature of React Native.
```
<Animated.ScrollView // <-- Use the Animated ScrollView wrapper
···
#### Bear in mind
While using transform styles such as `rotateY`, `rotateX`, and others ensure the transform style `perspective` is in place. At this time some animations may not render on Android without it. Example below.
```
<Animated.View
···
Note that in order to get this to work on **Android** you need to set the following flags via `UIManager`:
```
UIManager.setLayoutAnimationEnabledExperimental(true);
```
···
#### `drawerBackgroundColor`
Specifies the background color of the drawer. The default value is `white`. If you want to set the opacity of the drawer, use rgba. Example:
```
return (
···
### Methods
#### `closeDrawer()`
```
closeDrawer();
···
#### `openDrawer()`
```
openDrawer();
```
···
#### `SelectableBackground()`
```
static SelectableBackground(
rippleRadius: number | null,
···
---
#### `SelectableBackgroundBorderless()`
```
static SelectableBackgroundBorderless(
···
#### `Ripple()`
```
static Ripple(
color: ColorValue,
···
---
#### `canUseNativeForeground()`
```
static canUseNativeForeground(): boolean;
···
In order to fetch content from an arbitrary URL, you can pass the URL to fetch:
```
fetch('https://mywebsite.com/mydata.json');
```
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:
```
fetch('https://mywebsite.com/endpoint/', {
···
Networking is an inherently asynchronous operation. Fetch method will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
```
const getMoviesFromApi = () => {
return fetch('https://reactnative.dev/movies.json')
···
You can also use the `async` / `await` syntax in a React Native app:
```
const getMoviesFromApiAsync = async () => {
try {
···
### Using Other Networking Libraries
The XMLHttpRequest API is built into React Native. This means that you can use third party libraries such as frisbee or axios that depend on it, or you can use the XMLHttpRequest API directly if you prefer.
```
const request = new XMLHttpRequest();
···
### WebSocket Support
React Native also supports WebSockets, a protocol which provides full-duplex communication channels over a single TCP connection.
```
const ws = new WebSocket('ws://host.com/path');
···
On Android, `accessible={true}` property for a react-native View will be translated into native `focusable={true}`.
```
<View accessible={true}>
<Text>text one</Text>
···
To use, set the `accessibilityLabel` property to a custom string on your View, Text, or Touchable:
```
<TouchableOpacity
accessible={true}
···
A reference to another element nativeID used to build complex forms. The value of `accessibilityLabelledBy` should match the `nativeID` of the related element:
```
<View>
<Text nativeID="formLabel">Label for Input Field</Text>
···
An accessibility hint can be used to provide additional context to the user on the result of the action when it is not clear from the accessibility label alone.
Provide the `accessibilityHint` property a custom string on your View, Text, or Touchable:
```
<TouchableOpacity
···
By using the `accessibilityLanguage` property, the screen reader will understand which language to use while reading the element's **label**, **value**, and **hint**. The provided string value must follow the BCP 47 specification.
```
<View
accessible={true}
···
- **none** Accessibility services should not announce changes to this view.
- **polite** Accessibility services should announce changes to this view.
- **assertive** Accessibility services should interrupt ongoing speech to immediately announce changes to this view.
```
<TouchableWithoutFeedback onPress={addOne}>
···
A string that will be used as the title of the large content viewer when it is shown.
Requires `accessibilityShowsLargeContentViewer` to be set to `true`.
```
<View
···
Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the `nativeID` of the related element:
```
<View>
<Text nativeID="formLabel">Label for Input Field</Text>
···
#### `importantForAccessibility`Android
In the case of two overlapping UI components with the same parent, default accessibility focus can have unpredictable behavior. The `importantForAccessibility` property will resolve this by controlling if a view fires accessibility events and if it is reported to accessibility services. It can be set to `auto`, `yes`, `no` and `no-hide-descendants` (the last value will force accessibility services to ignore the component and all of its children).
```
<View style={styles.container}>
···
To handle action requests, a component must implement an `onAccessibilityAction` function. The only argument to this function is an event containing the name of the action to perform. The below example from RNTester shows how to create a component that defines and handles several custom actions.
```
<View
accessible={true}
···
### Sending Accessibility EventsAndroid
Sometimes it is useful to trigger an accessibility event on a UI component (i.e. when a custom view appears on a screen or set accessibility focus to a view). Native UIManager module exposes a method ‘sendAccessibilityEvent’ for this purpose. It takes two arguments: a view tag and a type of event. The supported event types are `typeWindowStateChanged`, `typeViewFocused`, and `typeViewClicked`.
```
import {Platform, UIManager, findNodeHandle} from 'react-native';
···
Here is how you do it: To define your `Cat` component, first use JavaScript’s `import` to import React and React Native’s `Text` Core Component:
```
import React from 'react';
import {Text} from 'react-native';
```
Your component starts as a function:
```
const Cat = () => {};
···
Here the `Cat` component will render a `<Text>` element:
```
const Cat = () => {
return <Text>Hello, I am your cat!</Text>;
···
```
You can export your function component with JavaScript’s `export default` for use throughout your app like so:
```
const Cat = () => {
···
First, you will want to import `useState` from React like so:
```
import React, {useState} from 'react';
```
Then you declare the component’s state by calling `useState` inside its function. In this example, `useState` creates an `isHungry` state variable:
```
const Cat = (props: CatProps) => {
···
It doesn’t matter what names you use. But it can be handy to think of the pattern as `[<getter>, <setter>] = useState(<initialValue>)`.
Next you add the `Button` Core Component and give it an `onPress` prop:
```
<Button
···
Now, when someone presses the button, `onPress` will fire, calling the `setIsHungry(false)`. This sets the state variable `isHungry` to `false`. When `isHungry` is false, the `Button`’s `disabled` prop is set to `true` and its `title` also changes:
```
<Button
//..
···
> You might’ve noticed that although `isHungry` is a const, it is seemingly reassignable! What is happening is when a state-setting function like `setIsHungry` is called, its component will re-render. In this case the `Cat` function will run again—and this time, `useState` will give us the next value of `isHungry`.
Finally, put your cats inside a `Cafe` component:
```
const Cafe = () => {
···
React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific.
```
import {Platform, StyleSheet} from 'react-native';
···
`Platform.OS` will be `ios` when running on iOS and `android` when running on Android.
There is also a `Platform.select` method available that, given an object where keys can be one of `'ios' | 'android' | 'native' | 'default'`, returns the most fitting value for the platform you are currently running on. That is, if you're running on a phone, `ios` and `android` keys will take preference. If those are not specified, `native` key will be used and then the `default` key.
```
import {Platform, StyleSheet} from 'react-native';
···
Since it accepts `any` value, you can also use it to return platform-specific components, like below:
```
const Component = Platform.select({
ios: () => require('ComponentIOS'),
···
<Component />;
```
```
const Component = Platform.select({
native: () => require('ComponentForNative'),
···
#### Detecting the Android versionAndroid
On Android, the `Platform` module can also be used to detect the version of the Android Platform in which the app is running:
```
import {Platform} from 'react-native';
···
On iOS, the `Version` is a result of `-[UIDevice systemVersion]`, which is a string with the current version of the operating system. An example of the system version is "10.3". For example, to detect the major version number on iOS:
```
import {Platform} from 'react-native';
···
You can then import the component as follows:
```
import BigButton from './BigButton';
```
···
```
You can still import it without the `.native` extension, as follows:
```
import Container from './Container';
···
Aside from rendering some UI, your components handle events like `onChangeText` for `TextInput` or `onPress` for `Button`. They may also contain other functions and event callbacks. Consider the following example:
```
function GroceryShoppingList() {
const [groceryItem, setGroceryItem] = useState('');
···
Component testing libraries such as React Native Testing Library facilitate writing user-centric tests by careful choice of provided APIs. The following example uses `fireEvent` methods `changeText` and `press` that simulate a user interacting with the component and a query function `getAllByText` that finds matching `Text` nodes in the rendered output.
```
test('given empty GroceryShoppingList, user can add an item to it', () => {
const {getByPlaceholderText, getByText, getAllByText} = render(
···
Snapshot testing is an advanced kind of testing enabled by Jest. It is a very powerful and low-level tool, so extra attention is advised when using it.
A "component snapshot" is a JSX-like string created by a custom React serializer built into Jest. This serializer lets Jest translate React component trees to string that's human-readable. Put another way: a component snapshot is a textual representation of your component’s render output _generated_ during a test run. It may look like this:
```
<Text
···
#### My TouchableX view isn't very responsive
Sometimes, if we do an action in the same frame that we are adjusting the opacity or highlight of a component that is responding to a touch, we won't see that effect until after the `onPress` function has returned. If `onPress` does a `setState` that results in a lot of work and a few frames dropped, this may occur. A solution to this is to wrap any action inside of your `onPress` handler in `requestAnimationFrame`:
```
handleOnPress() {
···
### Pattern
```
const subscription = BackHandler.addEventListener(
'hardwareBackPress',
···
#### `addEventListener()`
```
static addEventListener(
eventName: BackPressEventName,
···
---
#### `exitApp()`
```
static exitApp();
···
#### Use `memo()`
`React.memo()` creates a memoized component that will be re-rendered only when the props passed to the component change. We can use this function to optimize the components in the FlatList.
```
import React, {memo} from 'react';
···
For class components, move the `renderItem` function outside of the render function, so it won't recreate itself each time the render function is called.
```
const renderItem = useCallback(({item}) => (
<View key={item.key}>
···
### Advanced: Automatically inline `require` calls
If you use the React Native CLI to build your app, `require` calls (but not `import`s) will automatically be inlined for you, both in your code and inside any third-party packages (`node_modules`) you use.
```
import {useCallback, useState} from 'react';
···
Applications can schedule tasks to run after interactions with the following:
```
InteractionManager.runAfterInteractions(() => {
// ...long-running synchronous task...
···
The touch handling system considers one or more active touches to be an 'interaction' and will delay `runAfterInteractions()` callbacks until all touches have ended or been cancelled.
InteractionManager also allows applications to register animations by creating an interaction 'handle' on animation start, and clearing it upon completion:
```
const handle = InteractionManager.createInteractionHandle();
···
#### `configureNext()`
```
static configureNext(
config: LayoutAnimationConfig,
···
---
#### `create()`
```
static create(duration, type, creationProp)
···
#### `check()`
```
static check(permission: Permission): Promise<boolean>;
```
···
---
#### `request()`
```
static request(
···
---
#### `requestMultiple()`
```
static requestMultiple(
···
#### `show()`
```
static show(message: string, duration: number);
```
···
This property will only work on Android API 29 and below. For similar functionality on higher Android APIs, consider using snackbar or notification.
```
static showWithGravity(message: string, duration: number, gravity: number);
```
···
This property will only work on Android API 29 and below. For similar functionality on higher Android APIs, consider using snackbar or notification.
```
static showWithGravityAndOffset(
message: string,
···
Indicates the duration on the screen.
```
static SHORT: number;
```
···
#### `LONG`
Indicates the duration on the screen.
```
static LONG: number;
···
Indicates the position on the screen.
```
static TOP: number;
```
···
Indicates the position on the screen.
```
static BOTTOM: number;
```
···
Indicates the position on the screen.
```
static CENTER: number;
```
## Appearance
```
import {Appearance} from 'react-native';
···
### Example
You can use the `Appearance` module to determine if the user prefers a dark color scheme:
```
const colorScheme = Appearance.getColorScheme();
···
#### `getColorScheme()`
```
static getColorScheme(): 'light' | 'dark' | null;
```
···
#### `setColorScheme()`
```
static setColorScheme('light' | 'dark' | null): void;
```
···
#### `addChangeListener()`
```
static addChangeListener(
listener: (preferences: {colorScheme: 'light' | 'dark' | null}) => void,
···
`AppRegistry` is the JS entry point to running all React Native apps. App root components should register themselves with `AppRegistry.registerComponent`, then the native system can load the bundle for the app and then actually run the app when it's ready by invoking `AppRegistry.runApplication`.
```
import {Text, AppRegistry} from 'react-native';
···
#### `getAppKeys()`
```
static getAppKeys(): string[];
```
···
---
#### `getRegistry()`
```
static getRegistry(): {sections: string[]; runnables: Runnable[]};
···
---
#### `getRunnable()`
```
static getRunnable(appKey: string): : Runnable | undefined;
···
#### `getSectionKeys()`
```
static getSectionKeys(): string[];
```
···
#### `getSections()`
```
static getSections(): Record<string, Runnable>;
```
···
#### `registerCancellableHeadlessTask()`
```
static registerCancellableHeadlessTask(
taskKey: string,
···
---
#### `registerComponent()`
```
static registerComponent(
···
---
#### `registerConfig()`
```
static registerConfig(config: AppConfig[]);
···
#### `registerHeadlessTask()`
```
static registerHeadlessTask(
taskKey: string,
···
---
#### `registerRunnable()`
```
static registerRunnable(appKey: string, func: Runnable): string;
···
#### `registerSection()`
```
static registerSection(
appKey: string,
···
#### `runApplication()`
```
static runApplication(appKey: string, appParameters: any): void;
```
···
#### `setComponentProviderInstrumentationHook()`
```
static setComponentProviderInstrumentationHook(
hook: ComponentProviderInstrumentationHook,
···
#### `setWrapperComponentProvider()`
```
static setWrapperComponentProvider(
provider: WrapperComponentProvider,
···
---
#### `startHeadlessTask()`
```
static startHeadlessTask(
···
#### `unmountApplicationComponentAtRootTag()`
```
static unmountApplicationComponentAtRootTag(rootTag: number);
```
···
You should get a higher resolution image if you are on a high pixel density device. A good rule of thumb is to multiply the size of the image you display by the pixel ratio.
```
const image = getImage({
width: PixelRatio.getPixelSizeForLayoutSize(200),
···
### Methods
#### `get()`
```
static get(): number;
···
#### `getFontScale()`
```
static getFontScale(): number;
```
···
#### `getPixelSizeForLayoutSize()`
```
static getPixelSizeForLayoutSize(layoutSize: number): number;
```
···
---
#### `roundToNearestPixel()`
```
static roundToNearestPixel(layoutSize: number): number;
···
#### Require&#x64;**`renderItem`**&#x200B;
```
renderItem({
item: ItemT,
···
Example usage:
```
<FlatList
ItemSeparatorComponent={
···
#### `getItemLayout`
```
(data, index) => {length: number, offset: number, index: number}
```
`getItemLayout` is an optional optimization that allows skipping the measurement of dynamic content if you know the size (height or width) of items ahead of time. `getItemLayout` is efficient if you have fixed size items, for example:
```
getItemLayout={(data, index) => (
···
#### `keyExtractor`
```
(item: ItemT, index: number) => string;
```
···
---
#### `onRefresh`
```
() => void;
···
Error: Changing viewabilityConfig on the fly is not supported
```
```
constructor (props) {
super(props)
···
}
```
```
<FlatList
viewabilityConfig={this.viewabilityConfig}
···
#### `flashScrollIndicators()`
```
flashScrollIndicators();
```
···
---
#### `getNativeScrollRef()`
```
getNativeScrollRef(): React.ElementRef<typeof ScrollViewComponent>;
···
#### `getScrollResponder()`
```
getScrollResponder(): ScrollResponderMixin;
```
···
#### `getScrollableNode()`
```
getScrollableNode(): any;
```
···
Provides a handle to the underlying scroll node.
#### `scrollToEnd()`
```
scrollToEnd(params?: {animated?: boolean});
···
#### `scrollToIndex()`
```
scrollToIndex: (params: {
index: number;
···
#### `scrollToItem()`
```
scrollToItem(params: {
animated?: ?boolean,
···
---
#### `scrollToOffset()`
```
scrollToOffset(params: {
···
#### `addEventListener()`
```
static addEventListener(
eventName: AccessibilityChangeEventName | AccessibilityAnnouncementEventName,
···
#### `announceForAccessibility()`
```
static announceForAccessibility(announcement: string);
```
···
---
#### `announceForAccessibilityWithOptions()`
```
static announceForAccessibilityWithOptions(
···
#### `getRecommendedTimeoutMillis()`Android
```
static getRecommendedTimeoutMillis(originalTimeout: number): Promise<number>;
```
···
#### `isAccessibilityServiceEnabled()`Android
```
static isAccessibilityServiceEnabled(): Promise<boolean>;
```
···
#### `isBoldTextEnabled()`iOS
```
static isBoldTextEnabled(): Promise<boolean>:
```
···
---
#### `isGrayscaleEnabled()`iOS
```
static isGrayscaleEnabled(): Promise<boolean>;
···
#### `isInvertColorsEnabled()`iOS
```
static isInvertColorsEnabled(): Promise<boolean>;
```
···
#### `isReduceMotionEnabled()`
```
static isReduceMotionEnabled(): Promise<boolean>;
```
···
---
#### `isReduceTransparencyEnabled()`iOS
```
static isReduceTransparencyEnabled(): Promise<boolean>;
···
---
#### `isScreenReaderEnabled()`
```
static isScreenReaderEnabled(): Promise<boolean>;
···
#### `prefersCrossFadeTransitions()`iOS
```
static prefersCrossFadeTransitions(): Promise<boolean>;
```
···
---
#### `setAccessibilityFocus()`
```
static setAccessibilityFocus(reactTag: number);
···
#### `addEventListener()`
```
static addEventListener(
type: AppStateEvent,
···
#### `currentState`
```
static currentState: AppStateStatus;
```
···
### Properties
#### `constants`
```
static constants: PlatformConstants;
···
#### `isPad`iOS
```
static isPad: boolean;
```
···
#### `isTV`
```
static isTV: boolean;
```
···
#### `isVision`
```
static isVision: boolean;
```
···
---
#### `isTesting`
```
static isTesting: boolean;
···
---
#### `OS`
```
static OS: 'android' | 'ios';
···
#### `Version`
```
static Version: 'number' | 'string';
```
···
### Methods
#### `select()`
```
static select(config: Record<string, T>): T;
···
**Example usage:**
```
import {Platform, StyleSheet} from 'react-native';
···
Since the value of the corresponding platform key can be of type `any`, `select` method can also be used to return platform-specific components, like below:
```
const Component = Platform.select({
ios: () => require('ComponentIOS'),
···
<Component />;
```
```
const Component = Platform.select({
···
#### `flashScrollIndicators()`iOS
```
flashScrollIndicators();
```
···
#### `recordInteraction()`
```
recordInteraction();
```
···
#### `scrollToLocation()`
```
scrollToLocation(params: SectionListScrollParams);
```
···
#### `addMenuItem()`
```
static addMenuItem(title: string, handler: () => any);
```
···
**Example:**
```
DevSettings.addMenuItem('Show Secret Dev Screen', () => {
Alert.alert('Showing secret dev screen!');
···
---
#### `reload()`
```
static reload(reason?: string): void;
···
**Example:**
```
<Button title="Reload" onPress={() => DevSettings.reload()} />
```
···
### Reference
### Methods
```
static share(content: ShareContent, options?: ShareOptions);
···
#### `sharedAction`
```
static sharedAction: 'sharedAction';
```
···
---
#### `dismissedAction`iOS
```
static dismissedAction: 'dismissedAction';
···
#### Require&#x64;**`getItem`**&#x200B;
```
(data: any, index: number) => any;
```
···
#### Require&#x64;**`getItemCount`**&#x200B;
```
(data: any) => number;
```
···
---
#### Require&#x64;**`renderItem`**&#x200B;
```
(info: any) => ?React.Element<any>
···
#### `getItemLayout`
```
(
data: any,
···
#### `keyExtractor`
```
(item: any, index: number) => string;
```
···
#### `onRefresh`
```
() => void;
```
···
---
#### `onScrollToIndexFailed`
```
(info: {
···
#### `renderScrollComponent`
```
(props: object) => element;
```
···
#### `flashScrollIndicators()`
```
flashScrollIndicators();
```
···
#### `getScrollableNode()`
```
getScrollableNode(): any;
```
···
#### `getScrollRef()`
```
getScrollRef():
| React.ElementRef<typeof ScrollView>
···
---
#### `getScrollResponder()`
```
getScrollResponder () => ScrollResponderMixin | null;
···
#### `scrollToEnd()`
```
scrollToEnd(params?: {animated?: boolean});
```
···
#### `scrollToIndex()`
```
scrollToIndex(params: {
index: number;
···
---
#### `scrollToItem()`
```
scrollToItem(params: {
···
---
#### `scrollToOffset()`
```
scrollToOffset(params: {
···
#### `compose()`
```
static compose(style1: Object, style2: Object): Object | Object[];
```
···
#### `create()`
```
static create(styles: Object extends Record<string, ViewStyle | ImageStyle | TextStyle>): Object;
```
···
---
#### `flatten()`
```
static flatten(style: Array<Object extends Record<string, ViewStyle | ImageStyle | TextStyle>>): Object;
···
> **WARNING: EXPERIMENTAL.** Breaking changes will probably happen a lot and will not be reliably announced. The whole thing might be deleted, who knows? Use at your own risk.
```
static setStyleAttributePreprocessor(
property: string,
···
#### `setValue()`
```
setValue(value: number);
```
···
---
#### `setOffset()`
```
setOffset(offset: number);
···
#### `flattenOffset()`
```
flattenOffset();
```
···
#### `extractOffset()`
```
extractOffset();
```
···
---
#### `addListener()`
```
addListener(callback: (state: {value: number}) => void): string;
···
#### `removeListener()`
```
removeListener(id: string);
```
···
#### `removeAllListeners()`
```
removeAllListeners();
```
···
#### `stopAnimation()`
```
stopAnimation(callback?: (value: number) => void);
```
···
---
#### `resetAnimation()`
```
resetAnimation(callback?: (value: number) => void);
···
#### `interpolate()`
```
interpolate(config: InterpolationConfigType);
```
···
#### `animate()`
```
animate(animation, callback);
```
···
## Dimensions
> `useWindowDimensions` is the preferred API for React components. Unlike `Dimensions`, it updates as the window's dimensions update. This works nicely with the React paradigm.
```
import {Dimensions} from 'react-native';
···
You can get the application window's width and height using the following code:
```
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
···
#### `addEventListener()`
```
static addEventListener(
type: 'change',
···
---
#### `get()`
```
static get(dim: 'window' | 'screen'): ScaledSize;
···
#### `isEnabled()`
```
static isEnabled(): boolean;
```
···
---
#### `beginEvent()`
```
static beginEvent(eventName: string | (() => string), args?: EventArgs);
···
#### `endEvent()`
```
static endEvent(args?: EventArgs);
```
···
---
#### `beginAsyncEvent()`
```
static beginAsyncEvent(
···
#### `endAsyncEvent()`
```
static endAsyncEvent(
eventName: EventName,
···
---
#### `counterEvent()`
```
static counterEvent(eventName: string | (() => string), value: number);
···
#### `step0()`
```
static step0(n: number);
```
···
---
#### `step1()`
```
static step1(n: number);
···
#### `linear()`
```
static linear(t: number);
```
···
---
#### `ease()`
```
static ease(t: number);
···
#### `quad()`
```
static quad(t: number);
```
···
#### `cubic()`
```
static cubic(t: number);
```
···
---
#### `poly()`
```
static poly(n: number);
···
#### `sin()`
```
static sin(t: number);
```
···
#### `circle()`
```
static circle(t: number);
```
···
#### `exp()`
```
static exp(t: number);
```
···
---
#### `elastic()`
```
static elastic(bounciness: number);
···
#### `back()`
```
static back(s)
```
···
#### `bounce()`
```
static bounce(t: number);
```
···
---
#### `bezier()`
```
static bezier(x1: number, y1: number, x2: number, y2: number);
···
#### `in()`
```
static in(easing: number);
```
···
#### `out()`
```
static out(easing: number);
```
···
---
#### `inOut()`
```
static inOut(easing: number);
···
#### `cancel()`
```
static cancel();
```
···
#### `vibrate()`
```
static vibrate(
pattern?: number | number[],
···
#### `setValue()`
```
setValue(value: {x: number; y: number});
```
···
---
#### `setOffset()`
```
setOffset(offset: {x: number; y: number});
···
#### `flattenOffset()`
```
flattenOffset();
```
···
#### `extractOffset()`
```
extractOffset();
```
···
---
#### `addListener()`
```
addListener(callback: (value: {x: number; y: number}) => void);
···
#### `removeListener()`
```
removeListener(id: string);
```
···
#### `removeAllListeners()`
```
removeAllListeners();
```
···
---
#### `stopAnimation()`
```
stopAnimation(callback?: (value: {x: number; y: number}) => void);
···
#### `resetAnimation()`
```
resetAnimation(callback?: (value: {x: number; y: number}) => void);
```
···
#### `getLayout()`
```
getLayout(): {left: Animated.Value, top: Animated.Value};
```
Converts `{x, y}` into `{left, top}` for use in style, e.g.
```
style={this.state.anim.getLayout()}
···
#### `getTranslateTransform()`
```
getTranslateTransform(): [
{translateX: Animated.Value},
···
Converts `{x, y}` into a useable translation transform, e.g.
```
style={{
transform: this.state.anim.getTranslateTransform()
···
## useColorScheme
```
import {useColorScheme} from 'react-native';
```
···
## useWindowDimensions
```
import {useWindowDimensions} from 'react-native';
```
`useWindowDimensions` automatically updates all of its values when screen size or font scale changes. You can get your application window's width and height like so:
```
const {height, width} = useWindowDimensions();
···
#### `fontScale`
```
useWindowDimensions().fontScale;
```
···
---
#### `height`
```
useWindowDimensions().height;
···
#### `scale`
```
useWindowDimensions().scale;
```
···
#### `width`
```
useWindowDimensions().width;
```
···
### Methods
#### `addListener()`
```
static addListener: (
···
#### `dismiss()`
```
static dismiss();
```
···
#### `scheduleLayoutAnimation`
```
static scheduleLayoutAnimation(event: KeyboardEvent);
```
···
---
#### `isVisible()`
```
static isVisible(): boolean;
···
---
#### `metrics()`
```
static metrics(): KeyboardMetrics | undefined;
+28
src/unified.ts
···
parent.children.length = 0;
} else if (node.type === 'html') {
parent.children.splice(index, 1);
}
});
};
···
parent.children.length = 0;
} else if (node.type === 'html') {
parent.children.splice(index, 1);
+
} else if (node.type === 'heading') {
+
const child = node.children[0];
+
if (node.children.length === 0)
+
parent.children.splice(index, 1);
+
if (node.children.length > 1 || !child || child.type !== 'text')
+
return;
+
switch (child.value.trim()) {
+
case 'Example':
+
case 'Remarks':
+
case 'Note':
+
case '':
+
parent.children.splice(index, 1);
+
break;
+
default:
+
return;
+
}
+
} else if (node.type === 'text') {
+
if (!parent || parent.type !== 'paragraph' || parent.children.length > 1)
+
return;
+
switch (node.value.trim()) {
+
case 'Loading...':
+
case 'Caution':
+
case 'tsx':
+
parent.children.splice(index, 1);
+
break;
+
default:
+
return;
+
}
}
});
};