----
url: https://reactnative.dev/docs/next/the-new-architecture/create-module-library
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/create-module-library)** (0.87).

Version: Next

```
npx create-react-native-library@latest <Name of Your Library>
```

```
  "codegenConfig": {

    "name": "RN<your module name>Spec",

    "type": "all",

    "jsSrcsDir": "src",

    "outputDir": {

      "ios": "ios/generated",

      "android": "android/generated"

    },

    "android": {

      "javaPackageName": "com.<name-of-the-module>"

    }

  },
```

Finally, the library contains already all the infrastructure to let the library be linked with iOS and Android.

### 2. Copy the Code over from Your App[​](#2-copy-the-code-over-from-your-app "Direct link to 2. Copy the Code over from Your App")

The rest of the guide assumes that you have a local Turbo Native Module in your app, created following the guidelines shown in the other guides in the website: platform specific Turbo Native Modules, or [cross-platform Turbo Native Modules](/docs/next/the-new-architecture/pure-cxx-modules). But it works also for Components and legacy architecture modules and components. You'll have to adapt the files you need to copy and update.

1. **\[Not required for legacy architecture modules and components]** Move the code you have in the `specs` folder in your app into the `src` folder created by the `create-react-native-library` folder.
2. Update the `index.ts` file to properly export the Turbo Native Module spec so that it is accessible from the library. For example:

TypeScript

```
import NativeSampleModule from './NativeSampleModule';



export default NativeSampleModule;
```

```
Development

├── App

└── Library
```

You can use the library created with `create-react-native-library` also in this case.

1. add you library to your app by navigating into the `App` folder and running `yarn add ../Library`.
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:

React TSX

```
import NativeSampleModule from '../Library/src/index';
```

If you run your app right now, Metro would not find the JS files that it needs to serve to the app. That's because metro will be running starting from the `App` folder and it would not have access to the JS files located in the `Library` folder. To fix this, let's update the `metro.config.js` file as it follows

Diff

```
const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');



/**

 * Metro configuration

 * https://reactnative.dev/docs/metro

 *

 * @type {import('metro-config').MetroConfig}

 */

+ const path = require('path');



- const config = {}

+ const config = {

+  // Make Metro able to resolve required external dependencies

+  watchFolders: [

+    path.resolve(__dirname, '../Library'),

+  ],

+  resolver: {

+    extraNodeModules: {

+      'react-native': path.resolve(__dirname, 'node_modules/react-native'),

+    },

+  },

+};



module.exports = mergeConfig(getDefaultConfig(__dirname), config);
```

```
npm view <package.name>
```

where `package.name` is the `name` you set up in the `package.json` file during the initialization of the library.

Now, you can install the library in your application by running:

```
yarn add <package.name>
```

----
url: https://reactnative.dev/docs/next/layoutanimation
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/layoutanimation)** (0.87).

Version: Next

Automatically animates views to their new positions when the next layout happens.

A common way to use this API is to call it before updating the state hook in functional components and calling `setState` in class components.

note

On **Android**, when using the **Legacy Architecture**, you need to enable layout animations via `UIManager`. This flag enables layout animations globally and only needs to be called once (for example, in your app's root entry file `index.js` or root component) before triggering any layout animation:

JavaScript

```
if (Platform.OS === 'android') {

  if (UIManager.setLayoutAnimationEnabledExperimental) {

    UIManager.setLayoutAnimationEnabledExperimental(true);

  }

}
```

On the **New Architecture**, layout animations are enabled automatically, and calling `setLayoutAnimationEnabledExperimental` is unnecessary (it is a no-op).

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `configureNext()`[​](#configurenext "Direct link to configurenext")

React TSX

```
static configureNext(

  config: LayoutAnimationConfig,

  onAnimationDidEnd?: () => void,

  onAnimationDidFail?: () => void,

);
```

Schedules an animation to happen on the next layout.

#### Parameters:[​](#parameters "Direct link to Parameters:")

| Name               | Type     | Required | Description                         |
| ------------------ | -------- | -------- | ----------------------------------- |
| config             | object   | Yes      | See config description below.       |
| onAnimationDidEnd  | function | No       | Called when the animation finished. |
| onAnimationDidFail | function | No       | Called when the animation failed.   |

The `config` parameter is an object with the keys below. [`create`](/docs/next/layoutanimation#create) returns a valid object for `config`, and the [`Presets`](/docs/next/layoutanimation#presets) objects can also all be passed as the `config`.

* `duration` in milliseconds
* `create`, optional config for animating in new views
* `update`, optional config for animating views that have been updated
* `delete`, optional config for animating views as they are removed

The config that's passed to `create`, `update`, or `delete` has the following keys:

* `type`, the [animation type](/docs/next/layoutanimation#types) to use
* `property`, the [layout property](/docs/next/layoutanimation#properties) to animate (optional, but recommended for `create` and `delete`)
* `springDamping` (number, optional and only for use with `type: Type.spring`)
* `initialVelocity` (number, optional)
* `delay` (number, optional)
* `duration` (number, optional)

***

### `create()`[​](#create "Direct link to create")

React TSX

```
static create(duration, type, creationProp)
```

Helper that creates an object (with `create`, `update`, and `delete` fields) to pass into [`configureNext`](/docs/next/layoutanimation#configurenext). The `type` parameter is an [animation type](/docs/next/layoutanimation#types), and the `creationProp` parameter is a [layout property](/docs/next/layoutanimation#properties).

**Example:**

## Properties[​](#properties "Direct link to Properties")

### Types[​](#types "Direct link to Types")

An enumeration of animation types to be used in the [`create`](/docs/next/layoutanimation#create) method, or in the `create`/`update`/`delete` configs for [`configureNext`](/docs/next/layoutanimation#configurenext). (example usage: `LayoutAnimation.Types.easeIn`)

| Types         |
| ------------- |
| spring        |
| linear        |
| easeInEaseOut |
| easeIn        |
| easeOut       |
| keyboard      |

***

### Properties[​](#properties-1 "Direct link to Properties")

An enumeration of layout properties to be animated to be used in the [`create`](/docs/next/layoutanimation#create) method, or in the `create`/`update`/`delete` configs for [`configureNext`](/docs/next/layoutanimation#configurenext). (example usage: `LayoutAnimation.Properties.opacity`)

| Properties |
| ---------- |
| opacity    |
| scaleX     |
| scaleY     |
| scaleXY    |

***

### Presets[​](#presets "Direct link to Presets")

A set of predefined animation configs to pass into [`configureNext`](/docs/next/layoutanimation#configurenext).

| Presets       | Value                                                                                                                                                          |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| easeInEaseOut | `create(300, 'easeInEaseOut', 'opacity')`                                                                                                                      |
| linear        | `create(500, 'linear', 'opacity')`                                                                                                                             |
| spring        | `{duration: 700, create: {type: 'linear', property: 'opacity'}, update: {type: 'spring', springDamping: 0.4}, delete: {type: 'linear', property: 'opacity'} }` |

***

### `easeInEaseOut`[​](#easeineaseout "Direct link to easeineaseout")

Calls `configureNext()` with `Presets.easeInEaseOut`.

***

### `linear`[​](#linear "Direct link to linear")

Calls `configureNext()` with `Presets.linear`.

***

----
url: https://reactnative.dev/docs/next/the-new-architecture/layout-measurements
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/layout-measurements)** (0.87).

Version: Next

Sometimes, you need to measure the current layout to apply some changes to the overall layout or to make decisions and call some specific logic.

React Native provides some native methods to know what are the measurements of the views.

The best way to invoke those methods is in a `useLayoutEffect` hook: this will give you the most recent values for those measurements and it will let you apply changes in the same frame when the measurements are computed.

Typical code will look like this:

React TSX

```
function AComponent(children) {

  const targetRef = useRef(null)



  useLayoutEffect(() => {

    targetRef.current?.measure((x, y, width, height, pageX, pageY) => {

      //do something with the measurements

    });

  }, [ /* add dependencies here */]);



  return (

    <View ref={targetRef}>

     {children}

    <View />

  );

}
```

----
url: https://reactnative.dev/docs/upgrading
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
# {{VERSION}} and {{REACT_VERSION}} are the release versions showing in the diff

npm install react-native@{{VERSION}}

npm install react@{{REACT_VERSION}}
```

```
# {{VERSION}} and {{REACT_VERSION}} are the release versions showing in the diff

yarn add react-native@{{VERSION}}

yarn add react@{{REACT_VERSION}}
```

----
url: https://reactnative.dev/docs/next/intro-react
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/intro-react)** (0.87).

Version: Next

```
import {Text} from 'react-native';
```

Your component starts as a function:

React TSX

```
const Cat = () => {};
```

You can think of components as blueprints. Whatever a function component returns is rendered as a **React element.** React elements let you describe what you want to see on the screen.

Here the `Cat` component will render a `<Text>` element:

React TSX

```
const Cat = () => {

  return <Text>Hello, I am your cat!</Text>;

};
```

You can export your function component with JavaScript’s [`export default`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) for use throughout your app like so:

React TSX

```
const Cat = () => {

  return <Text>Hello, I am your cat!</Text>;

};



export default Cat;
```

You’ve already met [React Native’s Core Components](/docs/next/intro-react-native-components). React lets you nest these components inside each other to create new components. These nestable, reusable components are at the heart of the React paradigm.

For example, you can nest [`Text`](/docs/next/text) and [`TextInput`](/docs/next/textinput) inside a [`View`](/docs/next/view) below, and React Native will render them together:

#### Developer notes[​](#developer-notes "Direct link to Developer notes")

* Android
* Web

info

If you’re familiar with web development, `<View>` and `<Text>` might remind you of HTML! You can think of them as the `<div>` and `<p>` tags of application development.

info

On Android, you usually put your views inside `LinearLayout`, `FrameLayout`, `RelativeLayout`, etc. to define how the view’s children will be arranged on the screen. In React Native, `View` uses Flexbox for its children’s layout. You can learn more in [our guide to layout with Flexbox](/docs/next/flexbox).

Most of React Native’s Core Components can be customized with props, too. For example, when using [`Image`](/docs/next/image), you pass it a prop named [`source`](/docs/next/image#source) to define what image it shows:

`Image` has [many different props](/docs/next/image#props), including [`style`](/docs/next/image#style), which accepts a JS object of design and layout related property-value pairs.

note

Notice the double curly braces `{{ }}` surrounding `style`‘s width and height. In JSX, JavaScript values are referenced with `{}`. This is handy if you are passing something other than a string as props, like an array or number: `<Cat food={["fish", "kibble"]} age={2} />`. However, JS objects are ***also*** denoted with curly braces: `{width: 200, height: 200}`. Therefore, to pass a JS object in JSX, you must wrap the object in **another pair** of curly braces: `{{width: 200, height: 200}}`

You can build many things with props and the Core Components [`Text`](/docs/next/text), [`Image`](/docs/next/image), and [`View`](/docs/next/view)! But to build something interactive, you’ll need state.

```
import {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:

React TSX

```
const Cat = (props: CatProps) => {

  const [isHungry, setIsHungry] = useState(true);

  // ...

};
```

tip

You can use `useState` to track any kind of data: strings, numbers, Booleans, arrays, objects. For example, you can track the number of times a cat has been petted with `const [timesPetted, setTimesPetted] = useState(0)`!

Calling `useState` does two things:

* it creates a “state variable” with an initial value—in this case the state variable is `isHungry` and its initial value is `true`
* it creates a function to set that state variable’s value—`setIsHungry`

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`](/docs/next/button) Core Component and give it an `onPress` prop:

React TSX

```
<Button

  onPress={() => {

    setIsHungry(false);

  }}

  //..

/>
```

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:

React TSX

```
<Button

  //..

  disabled={!isHungry}

  title={isHungry ? 'Give me some food, please!' : 'Thank you!'}

/>
```

info

You might’ve noticed that although `isHungry` is a [const](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/const), it is seemingly reassignable! The `const` keyword here does not mean that the state itself is immutable. Rather, it means that the reference to the object, that contains the state and the function to update it, will not change. 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:

React TSX

```
const Cafe = () => {

  return (

    <>

      <Cat name="Munkustrap" />

      <Cat name="Spot" />

    </>

  );

};
```

info

See the `<>` and `</>` above? These bits of JSX are [fragments](https://react.dev/reference/react/Fragment). Adjacent JSX elements must be wrapped in an enclosing tag. Fragments let you do that without nesting an extra, unnecessary wrapping element like `View`.

***

Now that you’ve covered both React and React Native’s Core Components, let’s dive deeper on some of these core components by looking at [handling `<TextInput>`](/docs/next/handling-text-input).

* [Your first component](#your-first-component)
* [JSX](#jsx)
* [Custom Components](#custom-components)
* [Props](#props)
* [State](#state)

----
url: https://reactnative.dev/docs/next/text-style-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/text-style-props)** (0.87).

Version: Next

### Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

# Reference

## Props[​](#props "Direct link to Props")

### `color`[​](#color "Direct link to color")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `fontFamily`[​](#fontfamily "Direct link to fontfamily")

| Type   |
| ------ |
| string |

The generic font families `system-ui`, `ui-sans-serif`, `ui-serif`, `ui-monospace`, and `ui-rounded` are supported on iOS.

***

### `fontSize`[​](#fontsize "Direct link to fontsize")

| Type   |
| ------ |
| number |

***

### `fontStyle`[​](#fontstyle "Direct link to fontstyle")

| Type                         |
| ---------------------------- |
| enum(`'normal'`, `'italic'`) |

***

### `fontWeight`[​](#fontweight "Direct link to fontweight")

Specifies font weight. The values `'normal'` and `'bold'` are supported for most fonts. Not all fonts have a variant for each of the numeric values, in that case the closest one is chosen.

| Type                                                                                                                  | Default    |
| --------------------------------------------------------------------------------------------------------------------- | ---------- |
| enum(`'normal'`, `'bold'`, `'100'`, `'200'`, `'300'`, `'400'`, `'500'`, `'600'`, `'700'`, `'800'`, `'900'`) or number | `'normal'` |

***

### `includeFontPadding`Android[​](#includefontpadding-android "Direct link to includefontpadding-android")

Set to `false` to remove extra font padding intended to make space for certain ascenders / descenders. With some fonts, this padding can make text look slightly misaligned when centered vertically. For best results also set `textAlignVertical` to `center`.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `fontVariant`[​](#fontvariant "Direct link to fontvariant")

Allows you to set all the font variants for a font. Can be set by using an array of enums or a space-separated string e.g. `'small-caps common-ligatures'`.

| Type                                                                                                                 | Default |
| -------------------------------------------------------------------------------------------------------------------- | ------- |
| array of enum(`'small-caps'`, `'oldstyle-nums'`, `'lining-nums'`, `'tabular-nums'`, `'proportional-nums'`) or string | `[]`    |

***

### `fontVariationSettings`[​](#fontvariationsettings "Direct link to fontvariationsettings")

Configures variation axes for a variable font. Each axis is identified by a four-character OpenType tag, such as `wght` for weight, `wdth` for width, `opsz` for optical size, or a custom axis supported by the font. Settings can be provided as an object or as a CSS-compatible string.

The object and string forms below are equivalent; both set the wght axis to 500:

React TSX

```
<Text

  style={{

    fontVariationSettings: {wght: 500},

    // Equivalent CSS-compatible string:

    fontVariationSettings: "'wght' 500",

  }}>

  Variable font

</Text>
```

For more information about variation axes and the CSS string syntax, see MDN's font-variation-settings (<https://developer.mozilla.org/en-US/docs/Web/CSS/font-variation-settings>) documentation.

| Type                                         |
| -------------------------------------------- |
| string or object: `{[axis: string]: number}` |

***

### `letterSpacing`[​](#letterspacing "Direct link to letterspacing")

Increase or decrease the spacing between characters. By default there is no extra letter spacing.

| Type   |
| ------ |
| number |

***

### `lineHeight`[​](#lineheight "Direct link to lineheight")

Numeric value that controls the vertical spacing between lines of text within a text element. It specifies the distance between the baselines of consecutive lines of text.

| Type   |
| ------ |
| number |

***

### `textAlign`[​](#textalign "Direct link to textalign")

Specifies text alignment. On Android, the value 'justify' is only supported on Oreo (8.0) or above (API level >= 26). The value will fallback to `left` on lower Android versions.

| Type                                                         | Default  |
| ------------------------------------------------------------ | -------- |
| enum(`'auto'`, `'left'`, `'right'`, `'center'`, `'justify'`) | `'auto'` |

***

### `textAlignVertical`Android[​](#textalignvertical-android "Direct link to textalignvertical-android")

An alias for `verticalAlign` style prop, if you use both properties, `verticalAlign` will take precedence over `textAlignVertical`

| Type                                            | Default  |
| ----------------------------------------------- | -------- |
| enum(`'auto'`, `'top'`, `'bottom'`, `'center'`) | `'auto'` |

***

### `textDecorationColor`iOS[​](#textdecorationcolor-ios "Direct link to textdecorationcolor-ios")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `textDecorationLine`[​](#textdecorationline "Direct link to textdecorationline")

| Type                                                                        | Default  |
| --------------------------------------------------------------------------- | -------- |
| enum(`'none'`, `'underline'`, `'line-through'`, `'underline line-through'`) | `'none'` |

***

### `textDecorationStyle`iOS[​](#textdecorationstyle-ios "Direct link to textdecorationstyle-ios")

| Type                                                | Default   |
| --------------------------------------------------- | --------- |
| enum(`'solid'`, `'double'`, `'dotted'`, `'dashed'`) | `'solid'` |

***

### `textShadowColor`[​](#textshadowcolor "Direct link to textshadowcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `textShadowOffset`[​](#textshadowoffset "Direct link to textshadowoffset")

| Type                                        |
| ------------------------------------------- |
| object: `{width?: number, height?: number}` |

***

### `textShadowRadius`[​](#textshadowradius "Direct link to textshadowradius")

| Type   |
| ------ |
| number |

***

### `textTransform`[​](#texttransform "Direct link to texttransform")

| Type                                                         | Default  |
| ------------------------------------------------------------ | -------- |
| enum(`'none'`, `'uppercase'`, `'lowercase'`, `'capitalize'`) | `'none'` |

***

### `verticalAlign`Android[​](#verticalalign-android "Direct link to verticalalign-android")

| Type                                            | Default  |
| ----------------------------------------------- | -------- |
| enum(`'auto'`, `'top'`, `'bottom'`, `'middle'`) | `'auto'` |

***

### `writingDirection`iOS[​](#writingdirection-ios "Direct link to writingdirection-ios")

| Type                             | Default  |
| -------------------------------- | -------- |
| enum(`'auto'`, `'ltr'`, `'rtl'`) | `'auto'` |

***

### `userSelect`[​](#userselect "Direct link to userselect")

It allows the user to select text and to use the native copy and paste functionality. Has precedence over the `selectable` prop.

| Type                                                     | Default |
| -------------------------------------------------------- | ------- |
| enum(`'auto'`, `'text'`, `'none'`, `'contain'`, `'all'`) | `none`  |

    [Android](#includefontpadding-android)
  * [`fontVariant`](#fontvariant)
  * [`fontVariationSettings`](#fontvariationsettings)
  * [`letterSpacing`](#letterspacing)
  * [`lineHeight`](#lineheight)
  * [`textAlign`](#textalign)
  * [`textAlignVertical`](#textalignvertical-android)

    [Android](#textalignvertical-android)
  * [`textDecorationColor`](#textdecorationcolor-ios)

    [iOS](#textdecorationcolor-ios)
  * [`textDecorationLine`](#textdecorationline)
  * [`textDecorationStyle`](#textdecorationstyle-ios)

    [iOS](#textdecorationstyle-ios)
  * [`textShadowColor`](#textshadowcolor)
  * [`textShadowOffset`](#textshadowoffset)
  * [`textShadowRadius`](#textshadowradius)
  * [`textTransform`](#texttransform)
  * [`verticalAlign`](#verticalalign-android)

    [Android](#verticalalign-android)
  * [`writingDirection`](#writingdirection-ios)

    [iOS](#writingdirection-ios)
  * [`userSelect`](#userselect)

----
url: https://reactnative.dev/docs/appearance
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React TSX

```
import {Appearance} from 'react-native';
```

```
const colorScheme = Appearance.getColorScheme();

if (colorScheme === 'dark') {

  // Use dark color scheme

}
```

Although the color scheme is available immediately, this may change when not overridden via `setColorScheme()` (e.g. scheduled color scheme change at sunrise or sunset). Any rendering logic or styles that depend on the user preferred color scheme should try to call this function on every render, rather than caching the value.

**Recommended:** Use the [`useColorScheme`](/docs/usecolorscheme) hook.

### App-level overriding[​](#app-level-overriding "Direct link to App-level overriding")

`setColorScheme()` overrides the color scheme at the application level — it does not affect the system setting or other applications. Passing `'auto'` removes any override, restoring the system preference.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `getColorScheme()`[​](#getcolorscheme "Direct link to getcolorscheme")

React TSX

```
static getColorScheme(): 'light' | 'dark' | null;
```

Returns the active color scheme. This value may change at runtime, either at the system level (e.g. scheduled color scheme change at sunrise or sunset) or when overridden at the app level via `setColorScheme()`.

Return values:

* `'light'`: The light color scheme is applied.
* `'dark'`: The dark color scheme is applied.
* `null`: May be returned if the native Appearance module is not available.

See also: [`useColorScheme`](/docs/usecolorscheme) (hook).

***

### `setColorScheme()`[​](#setcolorscheme "Direct link to setcolorscheme")

React TSX

```
static setColorScheme('light' | 'dark' | 'auto' | 'unspecified'): void;
```

***

### `addChangeListener()`[​](#addchangelistener "Direct link to addchangelistener")

React TSX

```
static addChangeListener(

  listener: (preferences: {colorScheme: 'light' | 'dark' | null}) => void,

): EventSubscription;
```

----
url: https://reactnative.dev/docs/touchableopacity
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

tip

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the [Pressable](/docs/pressable) API.

A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, dimming it.

Opacity is controlled by wrapping the children in an `Animated.View`, which is added to the view hierarchy. Be aware that this can affect layout.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [TouchableWithoutFeedback Props](/docs/touchablewithoutfeedback#props)[​](#touchablewithoutfeedback-props "Direct link to touchablewithoutfeedback-props")

Inherits [TouchableWithoutFeedback Props](/docs/touchablewithoutfeedback#props).

***

### `style`[​](#style "Direct link to style")

| Type                                 |
| ------------------------------------ |
| [View.style](/docs/view-style-props) |

***

### `activeOpacity`[​](#activeopacity "Direct link to activeopacity")

Determines what the opacity of the wrapped view should be when touch is active. Defaults to `0.2`.

| Type   |
| ------ |
| number |

***

### `hasTVPreferredFocus`iOS[​](#hastvpreferredfocus-ios "Direct link to hastvpreferredfocus-ios")

*(Apple TV only)* TV preferred focus (see documentation for the View component).

| Type |
| ---- |
| bool |

***

### `nextFocusDown`Android[​](#nextfocusdown-android "Direct link to nextfocusdown-android")

TV next focus down (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`Android[​](#nextfocusforward-android "Direct link to nextfocusforward-android")

TV next focus forward (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`Android[​](#nextfocusleft-android "Direct link to nextfocusleft-android")

TV next focus left (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`Android[​](#nextfocusright-android "Direct link to nextfocusright-android")

TV next focus right (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`Android[​](#nextfocusup-android "Direct link to nextfocusup-android")

TV next focus up (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/element-nodes) when mounted.

* [Example](#example)

* [Props](#props)

  * [TouchableWithoutFeedback Props](#touchablewithoutfeedback-props)
  * [`style`](#style)
  * [`activeOpacity`](#activeopacity)
  * [`hasTVPreferredFocus`](#hastvpreferredfocus-ios)

    [iOS](#hastvpreferredfocus-ios)
  * [`nextFocusDown`](#nextfocusdown-android)

    [Android](#nextfocusdown-android)
  * [`nextFocusForward`](#nextfocusforward-android)

    [Android](#nextfocusforward-android)
  * [`nextFocusLeft`](#nextfocusleft-android)

    [Android](#nextfocusleft-android)
  * [`nextFocusRight`](#nextfocusright-android)

    [Android](#nextfocusright-android)
  * [`nextFocusUp`](#nextfocusup-android)

    [Android](#nextfocusup-android)
  * [`ref`](#ref)

----
url: https://reactnative.dev/docs/virtualview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

`VirtualView` is a core component that behaves similar to [`View`](/docs/view).

When it is the descendent of a [`ScrollView`](/docs/scrollview), it gains additional virtualization capabilities to reduce its memory footprint when obscured by the scroll viewport.

React TSX

```
<ScrollView>

  <VirtualView>

    <Text>Hello world!</Text>

  </VirtualView>

</ScrollView>
```

A `VirtualView` without an ancestor[`ScrollView`](/docs/scrollview) does not have any virtualization capabilities.

## Virtualization[​](#virtualization "Direct link to Virtualization")

When a `VirtualView` leaves the visible region of a [`ScrollView`](/docs/scrollview), it becomes hidden. When hidden, a `VirtualView` will cache its most recent layout and may unmount its children — a process called virtualization.

When a `VirtualView` returns to the visible region of a [`ScrollView`](/docs/scrollview), it becomes visible. When visible, its children are *guaranteed* to be rendered. This guarantee is maintained by blocking the main thread from rendering the next frame that would reveal the `VirtualView` until its children can be rendered.

note

In future developments, a hidden `VirtualView` may instead render its children in an [`<Activity mode="hidden">`](https://react.dev/reference/react/Activity) to preserve state for as long as possible while balancing memory overhead.

### Blocking the Main Thread[​](#blocking-the-main-thread "Direct link to Blocking the Main Thread")

This is the first time in React Native’s feature set where rendering a React component can block the main thread. This is a new capability enabled by the [New Architecture](/architecture/landing-page)!

Blocking the main thread can provide a better user experience by preventing flashes of blank frames that sometimes occur when using components like [`FlatList`](/docs/flatlist). It can also enable better performance by using main thread priority, which is also typically run on higher performance cores.

However, blocking the main thread also comes with tradeoffs. If an update operation, such as mounting the children of a `VirtualView`, takes too long to finish, it can now drop frames. Dropping more than a couple frames can lead to a worse user experience by making the app feel sluggish and non-responsive. Dropping too many frames may cause the operating system to display a modal indicating the app is not responsive, or it may even terminate your app!

warning

DevTools does not currently support debugging JavaScript on the main thread. This means if you are using breakpoints to debug code called from `onModeChange`, that is executed on the main thread, your debugger may freeze.

Debugging all other parts of your JavaScript code should work as expected. We are working on closing this gap before releasing `VirtualView` to stable channels of React Native.

### Prerendering[​](#prerendering "Direct link to Prerendering")

`VirtualView` enables you to benefit from main thread rendering while mitigating the disadvantages of dropped frames by rendering earlier before it is needed. This is called “prerendering”.

By default, each `VirtualView` will prerender its children when it approaches the visible region of a [`ScrollView`](/docs/scrollview). When this happens, its children will be rendered on a background thread at a lower priority (using a [transition](https://react.dev/reference/react/startTransition)). This ensures that the main thread and React are available to handle other critical user interactions at a higher priority.

note

`VirtualView`'s prerender logic is not currently configurable. The algorithm for determining this is undergoing active design iteration and is likely to change in a future release.

***

## Props[​](#props "Direct link to Props")

### `children`[​](#children "Direct link to children")

Content to render inside this `VirtualView`.

| Type                           |
| ------------------------------ |
| [React Node](/docs/react-node) |

***

### `onModeChange`[​](#onmodechange "Direct link to onmodechange")

Invoked when the `VirtualView` changes how it renders its children.

If a callback is supplied, it may be invoked from different threads and priorities depending on the internal state change. This can be detected by checking the `mode` property on the event:

* If `mode` is [`VirtualViewMode.Visible`](#virtualviewmode), the callback is being invoked from the main thread with immediate priority.
* If `mode` is [`VirtualViewMode.Prerender`](#virtualviewmode) or [`VirtualViewMode.Hidden`](#virtualviewmode), the callback is being invoked from a background thread with transition priority.

The callback will never be invoked consecutively with the same `mode` value. However, there are few guarantees about sequencing of events. Also, the callback may never be invoked with [`VirtualViewMode.Visible`](#virtualviewmode) even if it becomes visible, if the children were successfully prerendered.

| Type                        |
| --------------------------- |
| `(ModeChangeEvent) => void` |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

An identifier for locating this view from native classes.

| Type   |
| ------ |
| string |

***

### `style`[​](#style "Direct link to style")

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

***

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### `ModeChangeEvent`[​](#modechangeevent "Direct link to modechangeevent")

Argument supplied to [`onModeChange`](#onmodechange).

| Type   |
| ------ |
| object |

**Properties:**

| Name          | Type                                | Description                                                                                       |
| ------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------- |
| mode          | [VirtualViewMode](#virtualviewmode) | New mode of the `VirtualView`.                                                                    |
| target        | element                             | `VirtualView` emitting this event.                                                                |
| targetRect    | [Rect](/docs/rect)                  | Layout of `target` relative to the nearest ancestor `ScrollView`.                                 |
| thresholdRect | [Rect](/docs/rect)                  | Layout of the threshold that triggered this event, relative to the nearest ancestor `ScrollView`. |

note

For example, if a `VirtualView` enters the visible region of a [`ScrollView`](/docs/scrollview)...

* `mode` would be [`VirtualViewMode.Visible`](#virtualviewmode)
* `thresholdRect` would describe the visible viewport of the nearest ancestor [`ScrollView`](/docs/scrollview)
* `targetRect` would be the layout of `target` that overlaps with `thresholdRect` (i.e. it is within the visible region of the [`ScrollView`](/docs/scrollview))

### `VirtualViewMode`[​](#virtualviewmode "Direct link to virtualviewmode")

Possible modes of a `VirtualView`.

| Name      | Value | Description                                    |
| --------- | ----- | ---------------------------------------------- |
| Visible   | `0`   | Target view is visible.                        |
| Prerender | `1`   | Target view is hidden, but can be prerendered. |
| Hidden    | `2`   | Target view is hidden.                         |

***

## Static Methods[​](#static-methods "Direct link to Static Methods")

### `createHiddenVirtualView()`[​](#createhiddenvirtualview "Direct link to createhiddenvirtualview")

React TSX

```
static createHiddenVirtualView(height: number): typeof VirtualView;
```

`VirtualView` initially renders its children as visible, even if it is initially obscured by an ancestor [`ScrollView`](/docs/scrollview). This is because when a component is initially rendered, the presence of an ancestor [`ScrollView`](/docs/scrollview) — let alone its size and scroll position — are unknown.

For advanced use cases, `createHiddenVirtualView()` creates a component that renders an initially hidden `VirtualView` with the supplied estimated layout.

React TSX

```
const HiddenVirtualView = createHiddenVirtualView(100);



<ScrollView>

  <HiddenVirtualView>

    <Text>Hello world!</Text>

  </HiddenVirtualView>

</ScrollView>;
```

**Parameters:**

| Name           | Type   | Description                                            |
| -------------- | ------ | ------------------------------------------------------ |
| heightRequired | number | Estimated height of initially rendering `VirtualView`. |

----
url: https://reactnative.dev/docs/next/datepickerandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/datepickerandroid)** (0.87).

Version: Next

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=datepicker) instead.

----
url: https://reactnative.dev/docs/using-a-listview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React Native provides a suite of components for presenting lists of data. Generally, you'll want to use either [FlatList](/docs/flatlist) or [SectionList](/docs/sectionlist).

The `FlatList` component displays a scrolling list of changing, but similarly structured, data. `FlatList` works well for long lists of data, where the number of items might change over time. Unlike the more generic [`ScrollView`](/docs/using-a-scrollview), the `FlatList` only renders elements that are currently showing on the screen, not all the elements at once.

The `FlatList` component requires two props: `data` and `renderItem`. `data` is the source of information for the list. `renderItem` takes one item from the source and returns a formatted component to render.

This example creates a basic `FlatList` of hardcoded data. Each item in the `data` props is rendered as a `Text` component. The `FlatListBasics` component then renders the `FlatList` and all `Text` components.

If you want to render a set of data broken into logical sections, maybe with section headers, similar to `UITableView` on iOS, then a [SectionList](/docs/sectionlist) is the way to go.

One of the most common uses for a list view is displaying data that you fetch from a server. To do that, you will need to [learn about networking in React Native](/docs/network).

----
url: https://reactnative.dev/docs/actionsheetios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Displays native to iOS [Action Sheet](https://developer.apple.com/design/human-interface-guidelines/action-sheets) component.

## Example[​](#example "Direct link to Example")

# Reference

## Methods[​](#methods "Direct link to Methods")

### `showActionSheetWithOptions()`[​](#showactionsheetwithoptions "Direct link to showactionsheetwithoptions")

React TSX

```
static showActionSheetWithOptions: (

  options: ActionSheetIOSOptions,

  callback: (buttonIndex: number) => void,

);
```

Display an iOS action sheet. The `options` object must contain one or more of:

* `options` (array of strings) - a list of button titles (required)
* `cancelButtonIndex` (int) - index of cancel button in `options`
* `cancelButtonTintColor` (string) - the [color](/docs/colors) used for the change the text color of the cancel button
* `destructiveButtonIndex` (int or array of ints) - indices of destructive buttons in `options`
* `title` (string) - a title to show above the action sheet
* `message` (string) - a message to show below the title
* `anchor` (number) - the node to which the action sheet should be anchored (used for iPad)
* `tintColor` (string) - the [color](/docs/colors) used for non-destructive button titles
* `disabledButtonIndices` (array of numbers) - a list of button indices which should be disabled
* `userInterfaceStyle` (string) - the interface style used for the action sheet, can be set to `light` or `dark`, otherwise the default system style will be used

The 'callback' function takes one parameter, the zero-based index of the selected item.

Minimal example:

React TSX

```
ActionSheetIOS.showActionSheetWithOptions(

  {

    options: ['Cancel', 'Remove'],

    destructiveButtonIndex: 1,

    cancelButtonIndex: 0,

  },

  buttonIndex => {

    if (buttonIndex === 1) {

      /* destructive action */

    }

  },

);
```

***

### `dismissActionSheet()`[​](#dismissactionsheet "Direct link to dismissactionsheet")

React TSX

```
static dismissActionSheet();
```

Dismisses the most upper iOS action sheet presented, if no action sheet is present a warning is displayed.

***

### `showShareActionSheetWithOptions()`[​](#showshareactionsheetwithoptions "Direct link to showshareactionsheetwithoptions")

React TSX

```
static showShareActionSheetWithOptions: (

  options: ShareActionSheetIOSOptions,

  failureCallback: (error: Error) => void,

  successCallback: (success: boolean, method: string) => void,

);
```

----
url: https://reactnative.dev/docs/global-PerformanceMeasure
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`PerformanceMeasure`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMeasure) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/pressevent
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`PressEvent` object is returned in the callback as a result of user press interaction, for example `onPress` in [Button](/docs/button) component.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

    changedTouches: [PressEvent],

    identifier: 1,

    locationX: 8,

    locationY: 4.5,

    pageX: 24,

    pageY: 49.5,

    target: 1127,

    timestamp: 85131876.58868201,

    touches: []

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `changedTouches`[​](#changedtouches "Direct link to changedtouches")

Array of all PressEvents that have changed since the last event.

| Type                 | Optional |
| -------------------- | -------- |
| array of PressEvents | No       |

### `force`iOS[​](#force-ios "Direct link to force-ios")

Amount of force used during the 3D Touch press. Returns the float value in range from `0.0` to `1.0`.

| Type   | Optional |
| ------ | -------- |
| number | Yes      |

### `identifier`[​](#identifier "Direct link to identifier")

Unique numeric identifier assigned to the event.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `locationX`[​](#locationx "Direct link to locationx")

Touch origin X coordinate inside touchable area (relative to the element).

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `locationY`[​](#locationy "Direct link to locationy")

Touch origin Y coordinate inside touchable area (relative to the element).

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `pageX`[​](#pagex "Direct link to pagex")

Touch origin X coordinate on the screen (relative to the root view).

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `pageY`[​](#pagey "Direct link to pagey")

Touch origin Y coordinate on the screen (relative to the root view).

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `target`[​](#target "Direct link to target")

The node id of the element receiving the PressEvent.

| Type                        | Optional |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

### `timestamp`[​](#timestamp "Direct link to timestamp")

Timestamp value when a PressEvent occurred. Value is represented in milliseconds.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `touches`[​](#touches "Direct link to touches")

Array of all current PressEvents on the screen.

| Type                 | Optional |
| -------------------- | -------- |
| array of PressEvents | No       |

## Used by[​](#used-by "Direct link to Used by")

* [`Button`](/docs/button)
* [`PanResponder`](/docs/panresponder)
* [`Pressable`](/docs/pressable)
* [`ScrollView`](/docs/scrollview)
* [`Text`](/docs/text)
* [`TextInput`](/docs/textinput)
* [`TouchableHighlight`](/docs/touchablenativefeedback)
* [`TouchableOpacity`](/docs/touchablewithoutfeedback)
* [`TouchableNativeFeedback`](/docs/touchablenativefeedback)
* [`TouchableWithoutFeedback`](/docs/touchablewithoutfeedback)
* [`View`](/docs/view)

- [Example](#example)

- [Keys and values](#keys-and-values)

  * [`changedTouches`](#changedtouches)
  * [`force`](#force-ios)

    [iOS](#force-ios)

----
url: https://reactnative.dev/docs/safeareaview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Deprecated

Use [react-native-safe-area-context](https://github.com/AppAndFlow/react-native-safe-area-context) instead.

The purpose of `SafeAreaView` is to render content within the safe area boundaries of a device. It is currently only applicable to iOS devices with iOS version 11 or later.

`SafeAreaView` renders nested content and automatically applies padding to reflect the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. Moreover, and most importantly, Safe Area's paddings reflect the physical limitation of the screen, such as rounded corners or camera notches (i.e. the sensor housing area on iPhone 13).

## Example[​](#example "Direct link to Example")

To use, wrap your top level view with a `SafeAreaView` with a `flex: 1` style applied to it. You may also want to use a background color that matches your application's design.

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

note

As padding is used to implement the behavior of the component, padding rules in styles applied to a `SafeAreaView` will be ignored and can cause different results depending on the platform. See [#22211](https://github.com/react/react-native/issues/22211) for details.

* [Example](#example)
* [Props](#props)
  * [View Props](#view-props)

----
url: https://reactnative.dev/docs/next/debugging-release-builds
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/debugging-release-builds)** (0.87).

Version: Next

## Symbolicating a stack trace[​](#symbolicating-a-stack-trace "Direct link to Symbolicating a stack trace")

If a React Native app throws an unhandled exception in a release build, the output may be obfuscated and hard to read.

```
07-15 10:58:25.820 18979 18998 E AndroidRuntime: FATAL EXCEPTION: mqt_native_modules

07-15 10:58:25.820 18979 18998 E AndroidRuntime: Process: com.awesomeproject, PID: 18979 07-15 10:58:25.820 18979 18998 E AndroidRuntime: com.facebook.react.common.JavascriptException: Failed, js engine: hermes, stack:

07-15 10:58:25.820 18979 18998 E AndroidRuntime: p@1:132161

07-15 10:58:25.820 18979 18998 E AndroidRuntime: p@1:132084

07-15 10:58:25.820 18979 18998 E AndroidRuntime: f@1:131854

07-15 10:58:25.820 18979 18998 E AndroidRuntime: anonymous@1:131119
```

```
react {

    hermesFlags = ["-O", "-output-source-map"]

}
```

If done correctly you should see the output location of the source map during Metro build output.

Text

```
Writing bundle output to:, android/app/build/generated/assets/react/release/index.android.bundle

Writing sourcemap output to:, android/app/build/intermediates/sourcemaps/react/release/index.android.bundle.packager.map
```

info

On iOS, source maps are **disabled** by default. Use the following instructions to enable them.

To enable source map generation:

* Open Xcode and edit the build phase "Bundle React Native code and images".
* Above the other exports, add a `SOURCEMAP_FILE` entry with the desired output path.

Diff

```
+ export SOURCEMAP_FILE="$(pwd)/../main.jsbundle.map"

  WITH_ENVIRONMENT="../node_modules/react-native/scripts/xcode/with-environment.sh"
```

If done correctly you should see the output location of the source map during Metro build output.

Text

```
Writing bundle output to:, Build/Intermediates.noindex/ArchiveIntermediates/application/BuildProductsPath/Release-iphoneos/main.jsbundle

Writing sourcemap output to:, Build/Intermediates.noindex/ArchiveIntermediates/application/BuildProductsPath/Release-iphoneos/main.jsbundle.map
```

### Using `metro-symbolicate`[​](#using-metro-symbolicate "Direct link to using-metro-symbolicate")

With source maps being generated, we can now translate our stack traces.

```
# Print usage instructions

npx metro-symbolicate



# From a file containing the stack trace

npx metro-symbolicate android/app/build/generated/sourcemaps/react/release/index.android.bundle.map < stacktrace.txt



# From adb logcat (Android)

adb logcat -d | npx metro-symbolicate android/app/build/generated/sourcemaps/react/release/index.android.bundle.map
```

----
url: https://reactnative.dev/docs/other-debugging-methods
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This page covers how to use legacy JavaScript debugging methods. If you are getting started with a new React Native or Expo app, we recommend using [React Native DevTools](/docs/react-native-devtools).

----
url: https://reactnative.dev/docs/next/global-window
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-window)** (0.87).

Version: Next

[`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window/window) is an alias for [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), as defined in Web specifications.

The use of `globalThis` is recommended over `window`.

----
url: https://reactnative.dev/docs/global-global
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

[`global`](https://nodejs.org/api/globals.html#global) is a legacy alias for [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), as defined in Node.js.

The use of `globalThis` is recommended over `global`.

----
url: https://reactnative.dev/docs/next/optimizing-flatlist-configuration
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/optimizing-flatlist-configuration)** (0.87).

Version: Next

| Type    | Default                              |
| ------- | ------------------------------------ |
| Boolean | `true` on Android, otherwise `false` |

If `true`, views that are outside of the viewport are automatically detached from the native view hierarchy.

**Pros:** This reduces time spent on the main thread, and thus reduces the risk of dropped frames, by excluding views outside of the viewport from the native rendering and drawing traversals.

**Cons:** Be aware that this implementation can have bugs, such as missing content (mainly observed on iOS), especially if you are doing complex things with transforms and/or absolute positioning. Also note this does not save significant memory because the views are not deallocated, only detached.

### `maxToRenderPerBatch`[​](#maxtorenderperbatch "Direct link to maxtorenderperbatch")

| Type   | Default |
| ------ | ------- |
| Number | 10      |

It is a `VirtualizedList` prop that can be passed through `FlatList`. This controls the amount of items rendered per batch, which is the next chunk of items rendered on every scroll.

**Pros:** Setting a bigger number means less visual blank areas when scrolling (increases the fill rate).

**Cons:** More items per batch means longer periods of JavaScript execution potentially blocking other event processing, like presses, hurting responsiveness.

### `updateCellsBatchingPeriod`[​](#updatecellsbatchingperiod "Direct link to updatecellsbatchingperiod")

| Type   | Default |
| ------ | ------- |
| Number | 50      |

While `maxToRenderPerBatch` tells the amount of items rendered per batch, setting `updateCellsBatchingPeriod` tells your `VirtualizedList` the delay in milliseconds between batch renders (how frequently your component will be rendering the windowed items).

**Pros:** Combining this prop with `maxToRenderPerBatch` gives you the power to, for example, render more items in a less frequent batch, or less items in a more frequent batch.

**Cons:** Less frequent batches may cause blank areas, More frequent batches may cause responsiveness issues.

### initialNumToRender[​](#initialnumtorender "Direct link to initialNumToRender")

| Type   | Default |
| ------ | ------- |
| Number | 10      |

The initial amount of items to render.

**Pros:** Define precise number of items that would cover the screen for every device. This can be a big performance boost for the initial render.

**Cons:** Setting a low `initialNumToRender` may cause blank areas, especially if it's too small to cover the viewport on initial render.

### `windowSize`[​](#windowsize "Direct link to windowsize")

| Type   | Default |
| ------ | ------- |
| Number | 21      |

```
import {memo} from 'react';

import {View, Text} from 'react-native';



const MyListItem = memo(

  ({title}: {title: string}) => (

    <View>

      <Text>{title}</Text>

    </View>

  ),

  (prevProps, nextProps) => {

    return prevProps.title === nextProps.title;

  },

);



export default MyListItem;
```

In this example, we have determined that MyListItem should be re-rendered only when the title changes. We passed the comparison function as the second argument to React.memo() so that the component is re-rendered only when the specified prop is changed. If the comparison function returns true, the component will not be re-rendered.

### Use cached optimized images[​](#use-cached-optimized-images "Direct link to Use cached optimized images")

You can use the community packages (such as [@d11/react-native-fast-image](https://github.com/ds-horizon/react-native-fast-image) from [Dream11](https://github.com/ds-horizon)) for more performant images. Every image in your list is a `new Image()` instance. The faster it reaches the `loaded` hook, the faster your JavaScript thread will be free again.

### Use `getItemLayout`[​](#use-getitemlayout "Direct link to use-getitemlayout")

If all your list item components have the same height (or width, for a horizontal list), providing the [getItemLayout](/docs/next/flatlist#getitemlayout) prop removes the need for your `FlatList` to manage async layout calculations. This is a very desirable optimization technique.

If your components have dynamic size and you really need performance, consider asking your design team if they may think of a redesign in order to perform better.

### Use `keyExtractor` or `key`[​](#use-keyextractor-or-key "Direct link to use-keyextractor-or-key")

You can set the [`keyExtractor`](/docs/next/flatlist#keyextractor) to your `FlatList` component. This prop is used for caching and as the React `key` to track item re-ordering.

You can also use a `key` prop in your item component.

### Avoid anonymous function on `renderItem`[​](#avoid-anonymous-function-on-renderitem "Direct link to avoid-anonymous-function-on-renderitem")

For functional components, move the `renderItem` function outside of the returned JSX. Also, ensure that it is wrapped in a `useCallback` hook to prevent it from being recreated each render.

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.

React TSX

```
const renderItem = useCallback(({item}) => (

   <View key={item.key}>

      <Text>{item.title}</Text>

   </View>

 ), []);



return (

  // ...

  <FlatList data={items} renderItem={renderItem} />;

  // ...

);
```

----
url: https://reactnative.dev/docs/next/release-levels
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/release-levels)** (0.87).

Version: Next

```
DefaultNewArchitectureEntryPoint.releaseLevel = ReleaseLevel.CANARY

DefaultNewArchitectureEntryPoint.load()
```

The build system generates different feature flag override classes for each release level, ensuring the correct features are enabled for each stage.

### iOS[​](#ios "Direct link to iOS")

The `RCTReactNativeFactory` class now has an initializer that accepts a `releaseLevel` parameter. The feature flag setup uses this parameter to select the correct feature flag overrides. Create the factory from your `SceneDelegate` (or `AppDelegate` if you are not using the UIScene lifecycle).

* ObjectiveC
* Swift

SceneDelegate.m

```
self.reactNativeFactory = [[RCTReactNativeFactory alloc] initWithDelegate:self releaseLevel:Canary];
```

SceneDelegate.swift

```
reactNativeFactory = RCTReactNativeFactory(delegate: self, releaseLevel: RCTReleaseLevel.Canary)
```

Apps without UIScene lifecycle

* ObjectiveC
* Swift

AppDelegate.mm

```
[[RCTReactNativeFactory alloc] initWithDelegate:delegate releaseLevel:Canary];
```

AppDelegate.swift

```
let factory = RCTReactNativeFactory(delegate: delegate, releaseLevel: RCTReleaseLevel.Canary)
```

The system ensures that only one release level is active per app instance, and will crash if multiple factories are created with different release levels.

* [When to Use Each Release Level](#when-to-use-each-release-level)

* [How to initialize React Native using Canary & Experimental](#how-to-initialize-react-native-using-canary--experimental)

  * [Android](#android)
  * [iOS](#ios)

----
url: https://reactnative.dev/docs/debugging-native-code
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

### Projects with Native Code Only

The following section only applies to projects with native code exposed. If you are using the managed Expo workflow, see the guide on [prebuild](https://docs.expo.dev/workflow/prebuild/) to use this API.

## Accessing Logs[​](#accessing-logs "Direct link to Accessing Logs")

You can display the native logs for an iOS or Android app by using the following commands in a terminal while the app is running:

```
# For Android:

npx react-native log-android

# Or, for iOS:

npx react-native log-ios
```

You may also access these through Debug > Open System Log… in the iOS Simulator or by running `adb logcat "*:S" ReactNative:V ReactNativeJS:V` in a terminal while an Android app is running on a device or emulator.

**💡 Custom Native Logs**

If you are writing a Native Module and want to add custom logs to your module for debugging purposes, you can use the following method:

#### Android (Java/Kotlin)[​](#android-javakotlin "Direct link to Android (Java/Kotlin)")

In your native module, use the `Log` class to add logs that can be viewed in Logcat:

Java

```
import android.util.Log;



private void log(String message) {

    Log.d("YourModuleName", message);

}
```

To view these logs in Logcat, use this command, replacing `YourModuleName` with your custom tag:

```
adb logcat "*:S" ReactNative:V ReactNativeJS:V YourModuleName:D
```

#### iOS (Objective-C/Swift)[​](#ios-objective-cswift "Direct link to iOS (Objective-C/Swift)")

In your native module, use `NSLog` for custom logs:

Objective-C

```
NSLog(@"YourModuleName: %@", message);
```

Or, in Swift:

Swift

```
print("YourModuleName: \(message)")
```

----
url: https://reactnative.dev/docs/next/segmentedcontrolios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/segmentedcontrolios)** (0.87).

Version: Next

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=segmentedcontrol) instead.

***

----
url: https://reactnative.dev/docs/statusbar
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

***

# Reference

## Constants[​](#constants "Direct link to Constants")

### `currentHeight`Android[​](#currentheight-android "Direct link to currentheight-android")

The height of the status bar, which includes the notch height, if present.

***

## Props[​](#props "Direct link to Props")

### `animated`[​](#animated "Direct link to animated")

If the transition between status bar property changes should be animated. Supported for `barStyle` and `hidden` properties.

| Type    | Required | Default |
| ------- | -------- | ------- |
| boolean | No       | `false` |

***

### `barStyle`[​](#barstyle "Direct link to barstyle")

Sets the color of the status bar text.

On Android, this will only have an impact on API versions 23 and above.

| Type                                             | Required | Default     |
| ------------------------------------------------ | -------- | ----------- |
| [StatusBarStyle](/docs/statusbar#statusbarstyle) | No       | `'default'` |

***

### `hidden`[​](#hidden "Direct link to hidden")

If the status bar is hidden.

| Type    | Required | Default |
| ------- | -------- | ------- |
| boolean | No       | `false` |

***

### `showHideTransition`iOS[​](#showhidetransition-ios "Direct link to showhidetransition-ios")

The transition effect when showing and hiding the status bar using the `hidden` prop.

| Type                                                     | Default  |
| -------------------------------------------------------- | -------- |
| [StatusBarAnimation](/docs/statusbar#statusbaranimation) | `'fade'` |

## Methods[​](#methods "Direct link to Methods")

### `popStackEntry()`[​](#popstackentry "Direct link to popstackentry")

React TSX

```
static popStackEntry(entry: StatusBarProps);
```

Get and remove the last StatusBar entry from the stack.

**Parameters:**

| Name          | Type | Description                           |
| ------------- | ---- | ------------------------------------- |
| entryRequired | any  | Entry returned from `pushStackEntry`. |

***

### `pushStackEntry()`[​](#pushstackentry "Direct link to pushstackentry")

React TSX

```
static pushStackEntry(props: StatusBarProps): StatusBarProps;
```

Push a StatusBar entry onto the stack. The return value should be passed to `popStackEntry` when complete.

**Parameters:**

| Name          | Type | Description                                                      |
| ------------- | ---- | ---------------------------------------------------------------- |
| propsRequired | any  | Object containing the StatusBar props to use in the stack entry. |

***

### `replaceStackEntry()`[​](#replacestackentry "Direct link to replacestackentry")

React TSX

```
static replaceStackEntry(

  entry: StatusBarProps,

  props: StatusBarProps

): StatusBarProps;
```

Replace an existing StatusBar stack entry with new props.

**Parameters:**

| Name          | Type | Description                                                                  |
| ------------- | ---- | ---------------------------------------------------------------------------- |
| entryRequired | any  | Entry returned from `pushStackEntry` to replace.                             |
| propsRequired | any  | Object containing the StatusBar props to use in the replacement stack entry. |

***

### `setBarStyle()`[​](#setbarstyle "Direct link to setbarstyle")

React TSX

```
static setBarStyle(style: StatusBarStyle, animated?: boolean);
```

Set the status bar style.

**Parameters:**

| Name          | Type                                             | Description               |
| ------------- | ------------------------------------------------ | ------------------------- |
| styleRequired | [StatusBarStyle](/docs/statusbar#statusbarstyle) | Status bar style to set.  |
| animated      | boolean                                          | Animate the style change. |

***

### `setHidden()`[​](#sethidden "Direct link to sethidden")

React TSX

```
static setHidden(hidden: boolean, animation?: StatusBarAnimation);
```

Show or hide the status bar.

**Parameters:**

| Name           | Type                                                     | Description                                             |
| -------------- | -------------------------------------------------------- | ------------------------------------------------------- |
| hiddenRequired | boolean                                                  | Hide the status bar.                                    |
| animationiOS   | [StatusBarAnimation](/docs/statusbar#statusbaranimation) | Animation when changing the status bar hidden property. |

***

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### StatusBarAnimation[​](#statusbaranimation "Direct link to StatusBarAnimation")

Status bar animation type for transitions on the iOS.

| Type |
| ---- |
| enum |

**Constants:**

| Value     | Type   | Description     |
| --------- | ------ | --------------- |
| `'fade'`  | string | Fade animation  |
| `'slide'` | string | Slide animation |
| `'none'`  | string | No animation    |

***

### StatusBarStyle[​](#statusbarstyle "Direct link to StatusBarStyle")

Status bar style type.

| Type |
| ---- |
| enum |

**Constants:**

| Value             | Type   | Description                                                                                                                         |
| ----------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `'default'`       | string | Default status bar style (light for Android, dark for iOS)                                                                          |
| `'auto'`          | string | Automatically picks `light-content` or `dark-content` based on the current color scheme. Updates whenever the color scheme changes. |
| `'light-content'` | string | White texts and icons                                                                                                               |
| `'dark-content'`  | string | Dark texts and icons (requires API>=23 on Android)                                                                                  |

* [Usage with Navigator](#usage-with-navigator)

* [Imperative API](#imperative-api)

* [Constants](#constants)
  * [`currentHeight`](#currentheight-android)

    [Android](#currentheight-android)

* [Props](#props)

  * [`animated`](#animated)
  * [`barStyle`](#barstyle)
  * [`hidden`](#hidden)
  * [`showHideTransition`](#showhidetransition-ios)

    [iOS](#showhidetransition-ios)

----
url: https://reactnative.dev/docs/next/alert
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/alert)** (0.87).

Version: Next

Launches an alert dialog with the specified title and message.

Optionally provide a list of buttons. Tapping any button will fire the respective onPress callback and dismiss the alert. By default, the only button will be an 'OK' button.

This is an API that works both on Android and iOS and can show static alerts. Alert that prompts the user to enter some information is available on iOS only.

## Example[​](#example "Direct link to Example")

## iOS[​](#ios "Direct link to iOS")

On iOS you can specify any number of buttons. Each button can optionally specify a style or be emphasized, available options are represented by the [AlertButtonStyle](#alertbuttonstyle-ios) enum and the `isPreferred` field on [AlertButton](/docs/next/alert#alertbutton).

## Android[​](#android "Direct link to Android")

On Android at most three buttons can be specified. Android has a concept of a neutral, negative and a positive button:

* If you specify one button, it will be the 'positive' one (such as 'OK')
* Two buttons mean 'negative', 'positive' (such as 'Cancel', 'OK')
* Three buttons mean 'neutral', 'negative', 'positive' (such as 'Later', 'Cancel', 'OK')

Alerts on Android can be dismissed by tapping outside of the alert box. It is disabled by default and can be enabled by providing an optional [AlertOptions](/docs/next/alert#alertoptions) parameter with the cancelable property set to `true` i.e.\
`{cancelable: true}`.

The cancel event can be handled by providing an `onDismiss` callback property inside the `options` parameter.

### ExampleAndroid[​](#example-android "Direct link to example-android")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `alert()`[​](#alert "Direct link to alert")

React TSX

```
static alert (

  title: string,

  message?: string,

  buttons?: AlertButton[],

  options?: AlertOptions,

);
```

**Parameters:**

| Name          | Type                                           | Description                                                             |
| ------------- | ---------------------------------------------- | ----------------------------------------------------------------------- |
| titleRequired | string                                         | The dialog's title. Passing `null` or empty string will hide the title. |
| message       | string                                         | An optional message that appears below the dialog's title.              |
| buttons       | [AlertButton](/docs/next/alert#alertbutton)\[] | An optional array containing buttons configuration.                     |
| options       | [AlertOptions](/docs/next/alert#alertoptions)  | An optional Alert configuration.                                        |

***

### `prompt()`iOS[​](#prompt-ios "Direct link to prompt-ios")

React TSX

```
static prompt: (

  title: string,

  message?: string,

  callbackOrButtons?: ((text: string) => void) | AlertButton[],

  type?: AlertType,

  defaultValue?: string,

  keyboardType?: string,

);
```

Create and display a prompt to enter some text in form of Alert.

**Parameters:**

| Name              | Type                                                      | Description                                                                                                                                                                                     |
| ----------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| titleRequired     | string                                                    | The dialog's title.                                                                                                                                                                             |
| message           | string                                                    | An optional message that appears above the text input.                                                                                                                                          |
| callbackOrButtons | function***[AlertButton](/docs/next/alert#alertbutton)\[] | If passed a function, it will be called with the prompt's value `(text: string) => void`, when the user taps 'OK'.***If passed an array, buttons will be configured based on the array content. |
| type              | [AlertType](/docs/next/alert#alerttype-ios)               | This configures the text input.                                                                                                                                                                 |
| defaultValue      | string                                                    | The default text in text input.                                                                                                                                                                 |
| keyboardType      | string                                                    | The keyboard type of first text field (if exists). One of TextInput [keyboardTypes](/docs/next/textinput#keyboardtype).                                                                         |
| options           | [AlertOptions](/docs/next/alert#alertoptions)             | An optional Alert configuration.                                                                                                                                                                |

***

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### AlertButtonStyleiOS[​](#alertbuttonstyle-ios "Direct link to alertbuttonstyle-ios")

An iOS Alert button style.

| Type |
| ---- |
| enum |

**Constants:**

| Value           | Description               |
| --------------- | ------------------------- |
| `'default'`     | Default button style.     |
| `'cancel'`      | Cancel button style.      |
| `'destructive'` | Destructive button style. |

***

### AlertTypeiOS[​](#alerttype-ios "Direct link to alerttype-ios")

An iOS Alert type.

| Type |
| ---- |
| enum |

**Constants:**

| Value              | Description                  |
| ------------------ | ---------------------------- |
| `'default'`        | Default alert with no inputs |
| `'plain-text'`     | Plain text input alert       |
| `'secure-text'`    | Secure text input alert      |
| `'login-password'` | Login and password alert     |

***

### AlertButton[​](#alertbutton "Direct link to AlertButton")

An object describing the configuration of a button in the alert.

| Type             |
| ---------------- |
| array of objects |

**Objects properties:**

| Name           | Type                                                      | Description                                                                    |
| -------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------ |
| text           | string                                                    | Button label.                                                                  |
| onPress        | function                                                  | Callback function when button is pressed.                                      |
| styleiOS       | [AlertButtonStyle](/docs/next/alert#alertbuttonstyle-ios) | Button style, on Android this property will be ignored.                        |
| isPreferrediOS | boolean                                                   | Whether button should be emphasized, on Android this property will be ignored. |

***

### AlertOptions[​](#alertoptions "Direct link to AlertOptions")

| Type   |
| ------ |
| object |

**Properties:**

| Name                  | Type     | Description                                                                                                               |
| --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
| cancelableAndroid     | boolean  | Defines if alert can be dismissed by tapping outside of the alert box.                                                    |
| userInterfaceStyleiOS | string   | The interface style used for the alert, can be set to `light` or `dark`, otherwise the default system style will be used. |
| onDismissAndroid      | function | Callback function fired when alert has been dismissed.                                                                    |

* [Example](#example)

* [iOS](#ios)

* [Android](#android)
  * [Example](#example-android)

    [Android](#example-android)

* [Methods](#methods)

  * [`alert()`](#alert)
  * [`prompt()`](#prompt-ios)

    [iOS](#prompt-ios)

* [Type Definitions](#type-definitions)

  * [AlertButtonStyle](#alertbuttonstyle-ios)

    [iOS](#alertbuttonstyle-ios)
  * [AlertType](#alerttype-ios)

    [iOS](#alerttype-ios)
  * [AlertButton](#alertbutton)
  * [AlertOptions](#alertoptions)

----
url: https://reactnative.dev/docs/next/legacy/native-modules-setup
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/legacy/native-modules-setup)** (0.87).

Version: Next

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

Native modules are usually distributed as npm packages, except that on top of the usual JavaScript they will include some native code per platform. To understand more about npm packages you may find [this guide](https://docs.npmjs.com/packages-and-modules/contributing-packages-to-the-registry) useful.

To get set up with the basic project structure for a native module we will use the community tool called [create-react-native-library](https://callstack.github.io/react-native-builder-bob/create). You can go ahead further and dive deep into how that library works, but for our needs we will only execute the basic script:

```
npx create-react-native-library@latest react-native-awesome-module
```

Where `react-native-awesome-module` is the name you would like for the new module. After doing this you will navigate into `react-native-awesome-module` folder and bootstrap the example project by running:

```
yarn
```

When the bootstrap is done, you will be able to start the example app by executing one of the following commands:

```
# Android app

yarn example android

# iOS app

yarn example ios
```

When all steps above are done, you will be able to continue with [Android Native Modules](/docs/next/legacy/native-modules-android) or [iOS Native Modules](/docs/next/legacy/native-modules-ios) guides to add in some code.

----
url: https://reactnative.dev/docs/next/pressable
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/pressable)** (0.87).

Version: Next

Pressable is a Core Component wrapper that can detect various stages of press interactions on any of its defined children.

React TSX

```
<Pressable onPress={onPressFunction}>

  <Text>I'm pressable!</Text>

</Pressable>
```

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

### `android_ripple`Android[​](#android_ripple-android "Direct link to android_ripple-android")

Enables the Android ripple effect and configures its properties. The `color` field accepts both plain colors and [`PlatformColor`](/docs/next/platformcolor) values, so you can reference theme attributes like `?attr/colorAccent`. When a `PlatformColor` is used, the ripple is automatically updated when the system configuration changes (for example, when switching between light and dark mode).

| Type                                              |
| ------------------------------------------------- |
| [RippleConfig](/docs/next/pressable#rippleconfig) |

### `children`[​](#children "Direct link to children")

Either children or a function that receives a boolean reflecting whether the component is currently pressed.

| Type                                |
| ----------------------------------- |
| [React Node](/docs/next/react-node) |

### `unstable_pressDelay`[​](#unstable_pressdelay "Direct link to unstable_pressdelay")

Duration (in milliseconds) to wait after press down before calling `onPressIn`.

| Type   |
| ------ |
| number |

### `delayLongPress`[​](#delaylongpress "Direct link to delaylongpress")

Duration (in milliseconds) from `onPressIn` before `onLongPress` is called.

| Type   | Default |
| ------ | ------- |
| number | `500`   |

### `disabled`[​](#disabled "Direct link to disabled")

Whether the press behavior is disabled.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

### `hitSlop`[​](#hitslop "Direct link to hitslop")

Sets additional distance outside of element in which a press can be detected.

| Type                              |
| --------------------------------- |
| [Rect](/docs/next/rect) or number |

### `onHoverIn`[​](#onhoverin "Direct link to onhoverin")

Called when the hover is activated to provide visual feedback.

| Type                                    |
| --------------------------------------- |
| `({ nativeEvent: MouseEvent }) => void` |

### `onHoverOut`[​](#onhoverout "Direct link to onhoverout")

Called when the hover is deactivated to undo visual feedback.

| Type                                    |
| --------------------------------------- |
| `({ nativeEvent: MouseEvent }) => void` |

### `onLongPress`[​](#onlongpress "Direct link to onlongpress")

Called if the time after `onPressIn` lasts longer than 500 milliseconds. This time period can be customized with [`delayLongPress`](#delaylongpress).

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `onPress`[​](#onpress "Direct link to onpress")

Called after `onPressOut`.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `onPressIn`[​](#onpressin "Direct link to onpressin")

Called immediately when a touch is engaged, before `onPressOut` and `onPress`.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `onPressMove`[​](#onpressmove "Direct link to onpressmove")

Called when the press location moves.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `onPressOut`[​](#onpressout "Direct link to onpressout")

Called when a touch is released.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `pressRetentionOffset`[​](#pressretentionoffset "Direct link to pressretentionoffset")

Additional distance outside of this view in which a touch is considered a press before `onPressOut` is triggered.

| Type                              | Default                                      |
| --------------------------------- | -------------------------------------------- |
| [Rect](/docs/next/rect) or number | `{bottom: 30, left: 20, right: 20, top: 20}` |

### `style`[​](#style "Direct link to style")

Either view styles or a function that receives a boolean reflecting whether the component is currently pressed and returns view styles.

| Type                                                                                |
| ----------------------------------------------------------------------------------- |
| [View Style](/docs/next/view-style-props) or `({ pressed: boolean }) => View Style` |

### `testOnly_pressed`[​](#testonly_pressed "Direct link to testonly_pressed")

Used only for documentation or testing (e.g. snapshot testing).

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### RippleConfig[​](#rippleconfig "Direct link to RippleConfig")

Ripple effect configuration for the `android_ripple` property.

| Type   |
| ------ |
| object |

**Properties:**

| Name       | Type                                                                    | Required | Description                                                                                                                                                                                                                                                  |
| ---------- | ----------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| color      | [color](/docs/next/colors) or [PlatformColor](/docs/next/platformcolor) | No       | Defines the color of the ripple effect.                                                                                                                                                                                                                      |
| borderless | boolean                                                                 | No       | Defines if ripple effect should not include border.                                                                                                                                                                                                          |
| radius     | number                                                                  | No       | Defines the radius of the ripple effect.                                                                                                                                                                                                                     |
| foreground | boolean                                                                 | No       | Set to true to add the ripple effect to the foreground of the view, instead of the background. This is useful if one of your child views has a background of its own, or you're e.g. displaying images, and you don't want the ripple to be covered by them. |
| alpha      | number                                                                  | No       | Controls the opacity of the ripple. Accepts a value between `0.0` (fully transparent) and `1.0` (fully opaque). The value is applied on top of any alpha already present in the color.                                                                       |

* [How it works](#how-it-works)

* [Example](#example)

* [Props](#props)

  * [`android_disableSound`](#android_disablesound-android)

    [Android](#android_disablesound-android)
  * [`android_ripple`](#android_ripple-android)

    [Android](#android_ripple-android)

----
url: https://reactnative.dev/docs/fast-refresh
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Fast Refresh is a React Native feature that allows you to get near-instant feedback for changes in your React components. Fast Refresh is enabled by default, and you can toggle "Enable Fast Refresh" in the [React Native Dev Menu](/docs/debugging#opening-the-dev-menu). With Fast Refresh enabled, most edits should be visible within a second or two.

----
url: https://reactnative.dev/docs/next/image
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/image)** (0.87).

Version: Next

```
dependencies {

  // If your app supports Android versions before Ice Cream Sandwich (API level 14)

  implementation 'com.facebook.fresco:animated-base-support:1.3.0'



  // For animated GIF support

  implementation 'com.facebook.fresco:animated-gif:3.6.0'



  // For WebP support, including animated WebP

  implementation 'com.facebook.fresco:animated-webp:3.6.0'

  implementation 'com.facebook.fresco:webpsupport:3.6.0'



  // For WebP support, without animations

  implementation 'com.facebook.fresco:webpsupport:3.6.0'

}
```

note

The version listed above may not be updated in time. Please check [`packages/react-native/gradle/libs.versions.toml`](https://github.com/react/react-native/blob/main/packages/react-native/gradle/libs.versions.toml) in the main repo to see which fresco version is being used in a specific tagged version.

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### `accessible`[​](#accessible "Direct link to accessible")

When true, indicates the image is an accessibility element.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

The text that's read by the screen reader when the user interacts with the image.

| Type   |
| ------ |
| string |

***

### `alt`[​](#alt "Direct link to alt")

A string that defines an alternative text description of the image, which will be read by the screen reader when the user interacts with it. Using this will automatically mark this element as accessible.

| Type   |
| ------ |
| string |

***

### `blurRadius`[​](#blurradius "Direct link to blurradius")

blurRadius: the blur radius of the blur filter added to the image.

| Type   |
| ------ |
| number |

tip

On IOS, you will need to increase `blurRadius` by more than `5`.

***

### `capInsets`iOS[​](#capinsets-ios "Direct link to capinsets-ios")

When the image is resized, the corners of the size specified by `capInsets` will stay a fixed size, but the center content and borders of the image will be stretched. This is useful for creating resizable rounded buttons, shadows, and other resizable assets. More info in the [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).

| Type                    |
| ----------------------- |
| [Rect](/docs/next/rect) |

***

### `crossOrigin`[​](#crossorigin "Direct link to crossorigin")

A string of a keyword specifying the CORS mode to use when fetching the image resource. It works similar to crossorigin attribute in HTML.

* `anonymous`: No exchange of user credentials in the image request.
* `use-credentials`: Sets `Access-Control-Allow-Credentials` header value to `true` in the image request.

| Type                                     | Default       |
| ---------------------------------------- | ------------- |
| enum(`'anonymous'`, `'use-credentials'`) | `'anonymous'` |

***

### `defaultSource`[​](#defaultsource "Direct link to defaultsource")

A static image to display while loading the image source.

| Type                                        |
| ------------------------------------------- |
| [ImageSource](/docs/next/image#imagesource) |

note

On Android, the default source prop is ignored on debug builds.

***

### `fadeDuration`Android[​](#fadeduration-android "Direct link to fadeduration-android")

Fade animation duration in milliseconds.

| Type   | Default |
| ------ | ------- |
| number | `300`   |

***

### `height`[​](#height "Direct link to height")

Height of the image component.

| Type   |
| ------ |
| number |

***

### `loadingIndicatorSource`[​](#loadingindicatorsource "Direct link to loadingindicatorsource")

Similarly to `source`, this property represents the resource used to render the loading indicator for the image. The loading indicator is displayed until image is ready to be displayed, typically after the image is downloaded.

| Type                                                             |
| ---------------------------------------------------------------- |
| [ImageSource](/docs/next/image#imagesource) (`uri` only), number |

***

### `onError`[​](#onerror "Direct link to onerror")

Invoked on load error.

| Type                                |
| ----------------------------------- |
| (`{nativeEvent: {error} }`) => void |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: LayoutEvent} => void` |

***

### `onLoad`[​](#onload "Direct link to onload")

Invoked when load completes successfully.

**Example:** `onLoad={({nativeEvent: {source: {width, height}}}) => setImageRealSize({width, height})}`

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: ImageLoadEvent} => void` |

***

### `onLoadEnd`[​](#onloadend "Direct link to onloadend")

Invoked when load either succeeds or fails.

| Type       |
| ---------- |
| () => void |

***

### `onLoadStart`[​](#onloadstart "Direct link to onloadstart")

Invoked on load start.

**Example:** `onLoadStart={() => this.setState({loading: true})}`

| Type       |
| ---------- |
| () => void |

***

### `onPartialLoad`iOS[​](#onpartialload-ios "Direct link to onpartialload-ios")

Invoked when a partial load of the image is complete. The definition of what constitutes a "partial load" is loader specific though this is meant for progressive JPEG loads.

| Type       |
| ---------- |
| () => void |

***

### `onProgress`[​](#onprogress "Direct link to onprogress")

Invoked on download progress.

| Type                                        |
| ------------------------------------------- |
| (`{nativeEvent: {loaded, total} }`) => void |

***

### `progressiveRenderingEnabled`Android[​](#progressiverenderingenabled-android "Direct link to progressiverenderingenabled-android")

When `true`, enables progressive jpeg streaming - <https://frescolib.org/docs/progressive-jpegs>.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `referrerPolicy`[​](#referrerpolicy "Direct link to referrerpolicy")

A string indicating which referrer to use when fetching the resource. Sets the value for `Referrer-Policy` header in the image request. Works similar to `referrerpolicy` attribute in HTML.

| Type                                                                                                                                                                                     | Default                             |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| enum(`'no-referrer'`, `'no-referrer-when-downgrade'`, `'origin'`, `'origin-when-cross-origin'`, `'same-origin'`, `'strict-origin'`, `'strict-origin-when-cross-origin'`, `'unsafe-url'`) | `'strict-origin-when-cross-origin'` |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/next/element-nodes) when mounted.

***

| Type                                            | Default  |
| ----------------------------------------------- | -------- |
| enum(`'auto'`, `'resize'`, `'scale'`, `'none'`) | `'auto'` |

***

| Type                                                              | Default   |
| ----------------------------------------------------------------- | --------- |
| enum(`'cover'`, `'contain'`, `'stretch'`, `'repeat'`, `'center'`) | `'cover'` |

***

### `resizeMultiplier`Android[​](#resizemultiplier-android "Direct link to resizemultiplier-android")

When the `resizeMethod` is set to `resize`, the destination dimensions are multiplied by this value. The `scale` method is used to perform the remainder of the resize. A default of `1.0` means the bitmap size is designed to fit the destination dimensions. A multiplier greater than `1.0` will set the resize options larger than that of the destination dimensions, and the resulting bitmap will be scaled down from the hardware size. Defaults to `1.0`.

This prop is most useful in cases where the destination dimensions are quite small and the source image is significantly larger. The `resize` resize method performs downsampling and significant image quality is lost between the source and destination image sizes, often resulting in a blurry image. By using a multiplier, the decoded image is slightly larger than the target size but smaller than the source image (if the source image is large enough). This allows aliasing artifacts to produce faux quality through scaling operations on the multiplied image.

If you have a source image with dimensions 200x200 and destination dimensions of 24x24, a resizeMultiplier of `2.0` will tell Fresco to downsample the image to 48x48. Fresco picks the closest power of 2 (so, 50x50) and decodes the image into a bitmap of that size. Without the multiplier, the closest power of 2 would be 25x25. The resultant image is scaled down by the system.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

### `source`[​](#source "Direct link to source")

The image source (either a remote URL or a local file resource).

This prop can also contain several remote URLs, specified together with their width and height and potentially with scale/other URI arguments. The native side will then choose the best `uri` to display based on the measured size of the image container. A `cache` property can be added to control how networked request interacts with the local cache. (For more information see [Cache Control for Images](/docs/next/images#cache-control)).

The currently supported formats are `png`, `jpg`, `jpeg`, `bmp`, `gif`, `webp`, `psd` (iOS only). In addition, iOS supports several RAW image formats. Refer to Apple's documentation for the current list of supported camera models (for iOS 12, see <https://support.apple.com/en-ca/HT208967>).

Please note that the `webp` format is supported on iOS **only** when bundled with the JavaScript code.

| Type                                        |
| ------------------------------------------- |
| [ImageSource](/docs/next/image#imagesource) |

***

### `src`[​](#src "Direct link to src")

A string representing the remote URL of the image. This prop has precedence over `source` prop.

**Example:** `src={'https://reactnative.dev/img/tiny_logo.png'}`

| Type   |
| ------ |
| string |

***

### `srcSet`[​](#srcset "Direct link to srcset")

A string representing comma separated list of possible candidate image source. Each image source contains a URL of an image and a pixel density descriptor. If no descriptor is specified, it defaults to descriptor of `1x`.

If `srcSet` does not contain a `1x` descriptor, the value in `src` is used as image source with `1x` descriptor (if provided).

This prop has precedence over both the `src` and `source` props.

**Example:** `srcSet={'https://reactnative.dev/img/tiny_logo.png 1x, https://reactnative.dev/img/header_logo.svg 2x'}`

| Type   |
| ------ |
| string |

***

### `style`[​](#style "Direct link to style")

| Type                                                                                                                                                                                                 |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Image Style Props](/docs/next/image-style-props#props), [Layout Props](/docs/next/layout-props#props), [Shadow Props](/docs/next/shadow-props#props), [Transforms](/docs/next/transforms#transform) |

***

### `testID`[​](#testid "Direct link to testid")

A unique identifier for this element to be used in UI Automation testing scripts.

| Type   |
| ------ |
| string |

***

### `tintColor`[​](#tintcolor "Direct link to tintcolor")

Changes the color of all non-transparent pixels to the `tintColor`.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `width`[​](#width "Direct link to width")

Width of the image component.

| Type   |
| ------ |
| number |

## Methods[​](#methods "Direct link to Methods")

### `abortPrefetch()`Android[​](#abortprefetch-android "Direct link to abortprefetch-android")

React TSX

```
static abortPrefetch(requestId: number);
```

Abort prefetch request.

**Parameters:**

| Name              | Type   | Description                             |
| ----------------- | ------ | --------------------------------------- |
| requestIdRequired | number | Request id as returned by `prefetch()`. |

***

### `getSize()`[​](#getsize "Direct link to getsize")

React TSX

```
static getSize(uri: string): Promise<{width: number, height: number}>;
```

Retrieve the width and height (in pixels) of an image prior to displaying it. This method can fail if the image cannot be found, or fails to download.

In order to retrieve the image dimensions, the image may first need to be loaded or downloaded, after which it will be cached. This means that in principle you could use this method to preload images, however it is not optimized for that purpose, and may in future be implemented in a way that does not fully load/download the image data. A proper, supported way to preload images will be provided as a separate API.

**Parameters:**

| Name        | Type   | Description                |
| ----------- | ------ | -------------------------- |
| uriRequired | string | The location of the image. |

***

### `getSizeWithHeaders()`[​](#getsizewithheaders "Direct link to getsizewithheaders")

React TSX

```
static getSizeWithHeaders(

  uri: string,

  headers: {[index: string]: string}

): Promise<{width: number, height: number}>;
```

Retrieve the width and height (in pixels) of an image prior to displaying it with the ability to provide the headers for the request. This method can fail if the image cannot be found, or fails to download. It also does not work for static image resources.

In order to retrieve the image dimensions, the image may first need to be loaded or downloaded, after which it will be cached. This means that in principle you could use this method to preload images, however it is not optimized for that purpose, and may in future be implemented in a way that does not fully load/download the image data. A proper, supported way to preload images will be provided as a separate API.

**Parameters:**

| Name            | Type   | Description                  |
| --------------- | ------ | ---------------------------- |
| uriRequired     | string | The location of the image.   |
| headersRequired | object | The headers for the request. |

***

### `prefetch()`[​](#prefetch "Direct link to prefetch")

React TSX

```
await Image.prefetch(url);
```

Prefetches a remote image for later use by downloading it to the disk cache. Returns a promise which resolves to a boolean.

**Parameters:**

| Name        | Type            | Description                                            |
| ----------- | --------------- | ------------------------------------------------------ |
| urlRequired | string          | The remote location of the image.                      |
| callback    | functionAndroid | The function that will be called with the `requestId`. |

***

### `queryCache()`[​](#querycache "Direct link to querycache")

React TSX

```
static queryCache(

  urls: string[],

): Promise<Record<string, 'memory' | 'disk' | 'disk/memory'>>;
```

Perform cache interrogation. Returns a promise which resolves to a mapping from URL to cache status, such as "disk", "memory" or "disk/memory". If a requested URL is not in the mapping, it means it's not in the cache.

**Parameters:**

| Name         | Type  | Description                                |
| ------------ | ----- | ------------------------------------------ |
| urlsRequired | array | List of image URLs to check the cache for. |

***

### `resolveAssetSource()`[​](#resolveassetsource "Direct link to resolveassetsource")

React TSX

```
static resolveAssetSource(source: ImageSourcePropType): {

  height: number;

  width: number;

  scale: number;

  uri: string;

};
```

Resolves an asset reference into an object which has the properties `uri`, `scale`, `width`, and `height`.

**Parameters:**

| Name           | Type                                                | Description                                                                  |
| -------------- | --------------------------------------------------- | ---------------------------------------------------------------------------- |
| sourceRequired | [ImageSource](/docs/next/image#imagesource), number | A number (opaque type returned by `require('./foo.png')`) or an ImageSource. |

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### ImageCacheEnumiOS[​](#imagecacheenum-ios "Direct link to imagecacheenum-ios")

Enum which can be used to set the cache handling or strategy for the potentially cached responses.

| Type                                                               | Default     |
| ------------------------------------------------------------------ | ----------- |
| enum(`'default'`, `'reload'`, `'force-cache'`, `'only-if-cached'`) | `'default'` |

* `default`: Use the native platforms default strategy.
* `reload`: The data for the URL will be loaded from the originating source. No existing cache data should be used to satisfy a URL load request.
* `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.

### ImageLoadEvent[​](#imageloadevent "Direct link to ImageLoadEvent")

Object returned in the `onLoad` callback.

| Type   |
| ------ |
| object |

**Properties:**

| Name   | Type   | Description                         |
| ------ | ------ | ----------------------------------- |
| source | object | The [source object](#source-object) |

#### Source Object[​](#source-object "Direct link to Source Object")

**Properties:**

| Name   | Type   | Description                                                  |
| ------ | ------ | ------------------------------------------------------------ |
| width  | number | The width of loaded image.                                   |
| height | number | The height of loaded image.                                  |
| uri    | string | A string representing the resource identifier for the image. |

### ImageSource[​](#imagesource "Direct link to ImageSource")

| Type                             |
| -------------------------------- |
| object, array of objects, number |

**Properties (if passing as object or array of objects):**

| Name      | Type                                                  | Description                                                                                                                                                                          |
| --------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| uri       | string                                                | A string representing the resource identifier for the image, which could be an http address, a local file path, or the name of a static image resource.                              |
| width     | number                                                | Can be specified if known at build time, in which case the value will be used to set the default `<Image/>` component dimension.                                                     |
| height    | number                                                | Can be specified if known at build time, in which case the value will be used to set the default `<Image/>` component dimension.                                                     |
| scale     | number                                                | Used to indicate the scale factor of the image. Defaults to `1.0` if unspecified, meaning that one image pixel equates to one display point / DIP.                                   |
| bundleiOS | string                                                | The iOS asset bundle which the image is included in. This will default to `[NSBundle mainBundle]` if not set.                                                                        |
| method    | string                                                | The HTTP Method to use. Defaults to `'GET'` if not specified.                                                                                                                        |
| headers   | object                                                | An object representing the HTTP headers to send along with the request for a remote image.                                                                                           |
| body      | string                                                | The HTTP body to send with the request. This must be a valid UTF-8 string, and will be sent exactly as specified, with no additional encoding (e.g. URL-escaping or base64) applied. |
| cacheiOS  | [ImageCacheEnum](/docs/next/image#imagecacheenum-ios) | Determines how the requests handles potentially cached responses.                                                                                                                    |

    [iOS](#capinsets-ios)
  * [`crossOrigin`](#crossorigin)
  * [`defaultSource`](#defaultsource)
  * [`fadeDuration`](#fadeduration-android)

    [Android](#fadeduration-android)

    [iOS](#onpartialload-ios)
  * [`onProgress`](#onprogress)
  * [`progressiveRenderingEnabled`](#progressiverenderingenabled-android)

    [Android](#progressiverenderingenabled-android)
  * [`referrerPolicy`](#referrerpolicy)
  * [`ref`](#ref)
  * [`resizeMethod`](#resizemethod-android)

    [Android](#resizemethod-android)
  * [`resizeMode`](#resizemode)
  * [`resizeMultiplier`](#resizemultiplier-android)

    [Android](#resizemultiplier-android)

    [Android](#abortprefetch-android)

    [iOS](#imagecacheenum-ios)
  * [ImageLoadEvent](#imageloadevent)
  * [ImageSource](#imagesource)

----
url: https://reactnative.dev/docs/javascript-environment
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

## JavaScript Runtime[​](#javascript-runtime "Direct link to JavaScript Runtime")

When using React Native, you're going to be running your JavaScript code in up to three environments:

* In most cases, React Native will use [Hermes](/docs/hermes), an open-source JavaScript engine optimized for React Native.

| Transformation                                                                                              | Code                                                                               |
| ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| ECMAScript 5                                                                                                |                                                                                    |
| Reserved Words                                                                                              | ```
promise.catch(function() {...});
```                                           |
| ECMAScript 2015 (ES6)                                                                                       |                                                                                    |
| [Arrow functions](https://babeljs.io/docs/learn-es2015/#arrows)                                             | ```
<C onPress={() => this.setState({pressed: true})} />
```                       |
| [Block scoping](https://babeljs.io/docs/learn-es2015/#let-const)                                            | ```
let greeting = 'hi';
```                                                       |
| [Call spread](https://babeljs.io/docs/learn-es2015/#default-rest-spread)                                    | ```
Math.max(...array);
```                                                        |
| [Classes](https://babeljs.io/docs/learn-es2015/#classes)                                                    | ```
class C extends React.Component {render() { return <View />; }}
```            |
| [Computed Properties](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals)                       | ```
const key = 'abc'; const obj = {[key]: 10};
```                                |
| [Constants](https://babeljs.io/docs/learn-es2015/#let-const)                                                | ```
const answer = 42;
```                                                         |
| [Destructuring](https://babeljs.io/docs/learn-es2015/#destructuring)                                        | ```
const {isActive, style} = this.props;
```                                      |
| [for…of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)             | ```
for (var num of [1, 2, 3]) {...};
```                                          |
| [Function Name](https://babeljs.io/docs/en/babel-plugin-transform-function-name)                            | ```
let number = x => x;
```                                                       |
| [Literals](https://babeljs.io/docs/en/babel-plugin-transform-literals)                                      | ```
const b = 0b11; const o = 0o7; const u = 'Hello\u{000A}\u{0009}!';
```         |
| [Modules](https://babeljs.io/docs/learn-es2015/#modules)                                                    | ```
import {Component} from 'react';
```                                           |
| [Object Concise Method](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals)                     | ```
const obj = {method() { return 10; }};
```                                     |
| [Object Short Notation](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals)                     | ```
const name = 'vjeux'; const obj = {name};
```                                  |
| [Parameters](https://babeljs.io/docs/en/babel-plugin-transform-parameters)                                  | ```
function test(x = 'hello', {a, b}, ...args) {}
```                             |
| [Rest Params](https://github.com/sebmarkbage/ecmascript-rest-spread)                                        | ```
function(type, ...args) {};
```                                                |
| [Shorthand Properties](https://babeljs.io/docs/en/babel-plugin-transform-shorthand-properties)              | ```
const o = {a, b, c};
```                                                       |
| [Sticky Regex](https://babeljs.io/docs/en/babel-plugin-transform-sticky-regex)                              | ```
const a = /o+/y;
```                                                           |
| [Template Literals](https://babeljs.io/docs/learn-es2015/#template-strings)                                 | ```
const who = 'world'; const str = `Hello ${who}`;
```                           |
| [Unicode Regex](https://babeljs.io/docs/en/babel-plugin-transform-unicode-regex)                            | ```
const string = 'foo💩bar'; const match = string.match(/foo(.)bar/u);
```       |
| ECMAScript 2016 (ES7)                                                                                       |                                                                                    |
| [Exponentiation Operator](https://babeljs.io/docs/en/babel-plugin-transform-exponentiation-operator)        | ```
let x = 10 ** 2;
```                                                           |
| ECMAScript 2017 (ES8)                                                                                       |                                                                                    |
| [Async Functions](https://github.com/tc39/ecmascript-asyncawait)                                            | ```
async function doStuffAsync() {const foo = await doOtherStuffAsync();};
```    |
| [Function Trailing Comma](https://github.com/jeffmo/es-trailing-function-commas)                            | ```
function f(a, b, c,) {};
```                                                   |
| ECMAScript 2018 (ES9)                                                                                       |                                                                                    |
| [Object Spread](https://github.com/tc39/proposal-object-rest-spread)                                        | ```
const extended = {...obj, a: 10};
```                                          |
| ECMAScript 2019 (ES10)                                                                                      |                                                                                    |
| [Optional Catch Binding](https://babeljs.io/docs/en/babel-plugin-proposal-optional-catch-binding)           | ```
try {throw 0; } catch { doSomethingWhichDoesNotCareAboutTheValueThrown();}
``` |
| ECMAScript 2020 (ES11)                                                                                      |                                                                                    |
| [Dynamic Imports](https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import)                            | ```
const package = await import('package'); package.function()
```                |
| [Nullish Coalescing Operator](https://babeljs.io/docs/en/babel-plugin-proposal-nullish-coalescing-operator) | ```
const foo = object.foo ?? 'default';
```                                       |
| [Optional Chaining](https://github.com/tc39/proposal-optional-chaining)                                     | ```
const name = obj.user?.name;
```                                               |
| ECMAScript 2022 (ES13)                                                                                      |                                                                                    |
| [Class Fields](https://babeljs.io/docs/en/babel-plugin-proposal-class-properties)                           | ```
class Bork {static a = 'foo'; static b; x = 'bar'; y;}
```                     |
| Stage 1 Proposal                                                                                            |                                                                                    |
| [Export Default From](https://babeljs.io/docs/en/babel-plugin-proposal-export-default-from)                 | ```
export v from 'mod';
```                                                       |
| Miscellaneous                                                                                               |                                                                                    |
| [Babel Template](https://babeljs.io/docs/en/babel-template)                                                 | ```
template(`const %%importName%% = require(%%source%%);`);
```                   |
| [Flow](https://flowtype.org/)                                                                               | ```
function foo(x: ?number): string {};
```                                       |
| [ESM to CJS](https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs)                            | ```
export default 42;
```                                                         |
| [JSX](https://react.dev/learn/writing-markup-with-jsx)                                                      | ```
<View style={{color: 'red'}} />
```                                            |
| [Object Assign](https://babeljs.io/docs/en/babel-plugin-transform-object-assign)                            | ```
Object.assign(a, b);
```                                                       |
| [React Display Name](https://babeljs.io/docs/en/babel-plugin-transform-react-display-name)                  | ```
const bar = createReactClass({});
```                                          |
| [TypeScript](https://www.typescriptlang.org/)                                                               | ```
function foo(x: {hello: true, target: 'react native!'}): string {};
```        |

## Polyfills[​](#polyfills "Direct link to Polyfills")

Many standard functions are also available on all the supported JavaScript runtimes.

#### Browser[​](#browser "Direct link to Browser")

* [CommonJS `require`](https://nodejs.org/docs/latest/api/modules.html)
* `console.{log, warn, error, info, debug, trace, table, group, groupCollapsed, groupEnd}`
* [`XMLHttpRequest`, `fetch`](/docs/network)
* [`{set, clear}{Timeout, Interval, Immediate}, {request, cancel}AnimationFrame`](/docs/timers)

#### ECMAScript 2015 (ES6)[​](#ecmascript-2015-es6 "Direct link to ECMAScript 2015 (ES6)")

* [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
* `Array.prototype.{find, findIndex}`
* [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
* `String.prototype.{startsWith, endsWith, repeat, includes}`

#### ECMAScript 2016 (ES7)[​](#ecmascript-2016-es7 "Direct link to ECMAScript 2016 (ES7)")

* `Array.prototype.includes`

#### ECMAScript 2017 (ES8)[​](#ecmascript-2017-es8 "Direct link to ECMAScript 2017 (ES8)")

* `Object.{entries, values}`

#### Specific[​](#specific "Direct link to Specific")

* `__DEV__`

- [JavaScript Runtime](#javascript-runtime)
- [JavaScript Syntax Transformers](#javascript-syntax-transformers)
- [Polyfills](#polyfills)

----
url: https://reactnative.dev/docs/next/handling-text-input
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/handling-text-input)** (0.87).

Version: Next

[`TextInput`](/docs/next/textinput) is a [Core Component](/docs/next/intro-react-native-components) that allows the user to enter text. It has an `onChangeText` prop that takes a function to be called every time the text changed, and an `onSubmitEditing` prop that takes a function to be called when the text is submitted.

For example, let's say that as the user types, you're translating their words into a different language. In this new language, every single word is written the same way: 🍕. So the sentence "Hello there Bob" would be translated as "🍕 🍕 🍕".

In this example, we store `text` in the state, because it changes over time.

There are a lot more things you might want to do with a text input. For example, you could validate the text inside while the user types. For more detailed examples, see the [React docs on controlled components](https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable), or the [reference docs for TextInput](/docs/next/textinput).

A `TextInput` is one of many ways for the user to interact with your app. For examples of other ways to handle input, see the documentation on [how to handle touches](/docs/next/handling-touches).

Now, let's take a look at [ScrollView](/docs/next/using-a-scrollview), another Core Component.

----
url: https://reactnative.dev/docs/global-requestIdleCallback
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) for more information.

The global `requestIdleCallback` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/linking-libraries-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/linking-libraries-ios)** (0.87).

Version: Next

```
npm install <library-with-native-dependencies> --save
```

----
url: https://reactnative.dev/docs/next/running-on-simulator-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/running-on-simulator-ios)** (0.87).

Version: Next

## Starting the simulator[​](#starting-the-simulator "Direct link to Starting the simulator")

Once you have your React Native project initialized, you can run the following command inside the newly created project directory.

* npm
* Yarn

```
npm run ios
```

```
yarn ios
```

If everything is set up correctly, you should see your new app running in the iOS Simulator shortly.

## Specifying a device[​](#specifying-a-device "Direct link to Specifying a device")

You can specify the device the simulator should run with the `--simulator` flag, followed by the device name as a string. The default is `"iPhone 14"`. If you wish to run your app on an iPhone SE (3rd generation), run the following command:

* npm
* Yarn

```
npm run ios -- --simulator="iPhone SE (3rd generation)"
```

```
yarn ios --simulator "iPhone SE (3rd generation)"
```

The device names correspond to the list of devices available in Xcode. You can check your available devices by running `xcrun simctl list devices` from the console.

### Specifying a version of device[​](#specifying-a-version-of-device "Direct link to Specifying a version of device")

If you have multiple iOS versions installed, you also need to specify its appropriate version. E.g. To run your app on an iPhone 14 Pro (16.0) run the following command:

* npm
* Yarn

```
npm run ios -- --simulator="iPhone 14 Pro (16.0)"
```

```
yarn ios --simulator "iPhone 14 Pro (16.0)"
```

## Specifying an UDID[​](#specifying-an-udid "Direct link to Specifying an UDID")

You can specify the device UDID returned from `xcrun simctl list devices` command. E.g. To run your app with UDID `AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA` run the following command:

* npm
* Yarn

```
npm run ios -- --udid="AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"
```

```
yarn ios --udid "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"
```

* [Starting the simulator](#starting-the-simulator)
* [Specifying a device](#specifying-a-device)
  * [Specifying a version of device](#specifying-a-version-of-device)
* [Specifying an UDID](#specifying-an-udid)

----
url: https://reactnative.dev/docs/next/turbo-native-modules-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/turbo-native-modules-ios)** (0.87).

Version: Next

Now it's time to write some iOS platform code to make sure `localStorage` survives after the application is closed.

## Prepare your Xcode Project[​](#prepare-your-xcode-project "Direct link to Prepare your Xcode Project")

We need to prepare your iOS project using Xcode. After completing these **6 steps** you'll have `RCTNativeLocalStorage` that implements the generated `NativeLocalStorageSpec` interface.

1. Open the CocoaPods generated Xcode Workspace:

```
cd ios

open TurboModuleExample.xcworkspace
```

```
//  RCTNativeLocalStorage.h

//  TurboModuleExample



#import <Foundation/Foundation.h>

#import <NativeLocalStorageSpec/NativeLocalStorageSpec.h>



NS_ASSUME_NONNULL_BEGIN



@interface RCTNativeLocalStorage : NSObject

@interface RCTNativeLocalStorage : NSObject <NativeLocalStorageSpec>



@end
```

Then update our implementation to use `NSUserDefaults` with a custom [suite name](https://developer.apple.com/documentation/foundation/nsuserdefaults/1409957-initwithsuitename).

NativeLocalStorage/RCTNativeLocalStorage.mm

```
//  RCTNativeLocalStorage.m

//  TurboModuleExample



#import "RCTNativeLocalStorage.h"



static NSString *const RCTNativeLocalStorageKey = @"local-storage";



@interface RCTNativeLocalStorage()

@property (strong, nonatomic) NSUserDefaults *localStorage;

@end



@implementation RCTNativeLocalStorage



- (id) init {

  if (self = [super init]) {

    _localStorage = [[NSUserDefaults alloc] initWithSuiteName:RCTNativeLocalStorageKey];

  }

  return self;

}



- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {

  return std::make_shared<facebook::react::NativeLocalStorageSpecJSI>(params);

}



- (NSString * _Nullable)getItem:(NSString *)key {

  return [self.localStorage stringForKey:key];

}



- (void)setItem:(NSString *)value

          key:(NSString *)key {

  [self.localStorage setObject:value forKey:key];

}



- (void)removeItem:(NSString *)key {

  [self.localStorage removeObjectForKey:key];

}



- (void)clear {

  NSDictionary *keys = [self.localStorage dictionaryRepresentation];

  for (NSString *key in keys) {

    [self removeItem:key];

  }

}



+ (NSString *)moduleName

{

  return @"NativeLocalStorage";

}



@end
```

Important things to note:

* You can use Xcode to jump to the Codegen `@protocol NativeLocalStorageSpec`. You can also use Xcode to generate stubs for you.

## Register the Native Module in your app[​](#register-the-native-module-in-your-app "Direct link to Register the Native Module in your app")

The last step consist in updating the `package.json` to tell React Native about the link between the JS specs of the Native Module and the concrete implementation of those specs in native code.

Modify the `package.json` as it follows:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "NativeLocalStorageSpec",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.nativelocalstorage"

     },

     "ios": {

        "modulesProvider": {

          "NativeLocalStorage": "RCTNativeLocalStorage"

        }

     }

   },



   "dependencies": {
```

At this point, you need to re-install the pods to make sure that codegen runs again to generate the new files:

```
# from the ios folder

bundle exec pod install

open TurboModuleExample.xcworkspace
```

If you now build your application from Xcode, you should be able to build successfully.

## Build and run your code on a Simulator[​](#build-and-run-your-code-on-a-simulator "Direct link to Build and run your code on a Simulator")

* npm
* Yarn

```
npm run ios
```

```
yarn run ios
```

* [Prepare your Xcode Project](#prepare-your-xcode-project)
* [Implement localStorage with NSUserDefaults](#implement-localstorage-with-nsuserdefaults)
* [Register the Native Module in your app](#register-the-native-module-in-your-app)
* [Build and run your code on a Simulator](#build-and-run-your-code-on-a-simulator)

----
url: https://reactnative.dev/docs/dimensions
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

info

[`useWindowDimensions`](/docs/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.

React TSX

```
import {Dimensions} from 'react-native';
```

You can get the application window's width and height using the following code:

React TSX

```
const windowWidth = Dimensions.get('window').width;

const windowHeight = Dimensions.get('window').height;
```

```
static addEventListener(

  type: 'change',

  handler: ({

    window,

    screen,

  }: DimensionsPayload) => void,

): EventSubscription;
```

Add an event handler. Supported events:

* `change`: Fires when a property within the `Dimensions` object changes. The argument to the event handler is a [`DimensionsPayload`](#dimensionspayload) object.

***

### `get()`[​](#get "Direct link to get")

React TSX

```
static get(dim: string): DisplayMetrics | DisplayMetricsAndroid;
```

Initial dimensions are set before `runApplication` is called so they should be available before any other require's are run, but may be updated later.

Example: `const {height, width} = Dimensions.get('window');`

**Parameters:**

| Name        | Type   | Description                                                                       |
| ----------- | ------ | --------------------------------------------------------------------------------- |
| dimRequired | string | Name of dimension as defined when calling `set`. Returns value for the dimension. |

note

For Android the `window` dimension will be reduced by the size of status bar (if not translucent) and bottom navigation bar.

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### DimensionsPayload[​](#dimensionspayload "Direct link to DimensionsPayload")

**Properties:**

| Name                 | Type                                                            | Description                             |
| -------------------- | --------------------------------------------------------------- | --------------------------------------- |
| window               | [DisplayMetrics](/docs/dimensions#displaymetrics)               | Size of the visible application window. |
| screen               | [DisplayMetrics](/docs/dimensions#displaymetrics)               | Size of the device's screen.            |
| windowPhysicalPixels | [DisplayMetricsAndroid](/docs/dimensions#displaymetricsandroid) | Physical pixels for the Android window. |
| screenPhysicalPixels | [DisplayMetricsAndroid](/docs/dimensions#displaymetricsandroid) | Physical pixels for the Android screen. |

### DisplayMetrics[​](#displaymetrics "Direct link to DisplayMetrics")

| Type   |
| ------ |
| object |

**Properties:**

| Name      | Type   |
| --------- | ------ |
| width     | number |
| height    | number |
| scale     | number |
| fontScale | number |

### DisplayMetricsAndroid[​](#displaymetricsandroid "Direct link to DisplayMetricsAndroid")

`DisplayMetricsAndroid` includes all [`DisplayMetrics`](/docs/dimensions#displaymetrics) properties and the following property:

| Name       | Type   |
| ---------- | ------ |
| densityDpi | number |

----
url: https://reactnative.dev/docs/next/global-PerformanceLongTaskTiming
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-PerformanceLongTaskTiming)** (0.87).

Version: Next

The global [`PerformanceLongTaskTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceLongTaskTiming) class, as defined in Web specifications.

Partial support

The value for the `attribution` property is always an empty array.

----
url: https://reactnative.dev/docs/global-__DEV__
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

You can use the `__DEV__` pseudo-global variable in the codebase to guard development-only blocks of code.

It is inlined during compilation and gets completely stripped out with the `if` blocks it guards in the minified build.

----
url: https://reactnative.dev/docs/touchablehighlight
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

tip

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the [Pressable](/docs/pressable) API.

A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, which allows the underlay color to show through, darkening or tinting the view.

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.

React TSX

```
function MyComponent(props: MyComponentProps) {

  return (

    <View {...props} style={{flex: 1, backgroundColor: '#fff'}}>

      <Text>My Component</Text>

    </View>

  );

}



<TouchableHighlight

  activeOpacity={0.6}

  underlayColor="#DDDDDD"

  onPress={() => alert('Pressed!')}>

  <MyComponent />

</TouchableHighlight>;
```

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [TouchableWithoutFeedback Props](/docs/touchablewithoutfeedback#props)[​](#touchablewithoutfeedback-props "Direct link to touchablewithoutfeedback-props")

Inherits [TouchableWithoutFeedback Props](/docs/touchablewithoutfeedback#props).

***

### `activeOpacity`[​](#activeopacity "Direct link to activeopacity")

Determines what the opacity of the wrapped view should be when touch is active. The value should be between 0 and 1. Defaults to 0.85. Requires `underlayColor` to be set.

| Type   |
| ------ |
| number |

***

### `onHideUnderlay`[​](#onhideunderlay "Direct link to onhideunderlay")

Called immediately after the underlay is hidden.

| Type     |
| -------- |
| function |

***

### `onShowUnderlay`[​](#onshowunderlay "Direct link to onshowunderlay")

Called immediately after the underlay is shown.

| Type     |
| -------- |
| function |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/element-nodes) when mounted.

***

### `style`[​](#style "Direct link to style")

| Type        |
| ----------- |
| View\.style |

***

### `underlayColor`[​](#underlaycolor "Direct link to underlaycolor")

The color of the underlay that will show through when the touch is active.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `hasTVPreferredFocus`iOS[​](#hastvpreferredfocus-ios "Direct link to hastvpreferredfocus-ios")

*(Apple TV only)* TV preferred focus (see documentation for the View component).

| Type |
| ---- |
| bool |

***

### `nextFocusDown`Android[​](#nextfocusdown-android "Direct link to nextfocusdown-android")

TV next focus down (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`Android[​](#nextfocusforward-android "Direct link to nextfocusforward-android")

TV next focus forward (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`Android[​](#nextfocusleft-android "Direct link to nextfocusleft-android")

TV next focus left (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`Android[​](#nextfocusright-android "Direct link to nextfocusright-android")

TV next focus right (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`Android[​](#nextfocusup-android "Direct link to nextfocusup-android")

TV next focus up (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `testOnly_pressed`[​](#testonly_pressed "Direct link to testonly_pressed")

Handy for snapshot tests.

| Type |
| ---- |
| bool |

    [iOS](#hastvpreferredfocus-ios)
  * [`nextFocusDown`](#nextfocusdown-android)

    [Android](#nextfocusdown-android)
  * [`nextFocusForward`](#nextfocusforward-android)

    [Android](#nextfocusforward-android)
  * [`nextFocusLeft`](#nextfocusleft-android)

    [Android](#nextfocusleft-android)
  * [`nextFocusRight`](#nextfocusright-android)

    [Android](#nextfocusright-android)
  * [`nextFocusUp`](#nextfocusup-android)

    [Android](#nextfocusup-android)
  * [`testOnly_pressed`](#testonly_pressed)

----
url: https://reactnative.dev/docs/the-new-architecture/codegen-cli
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Calling Gradle or manually calling a script might be hard to remember and it requires a lot of ceremony.

To simplify it, we created a CLI tool that can help you running those tasks: the **Codegen** cli. This command runs [@react-native/codegen](https://www.npmjs.com/package/@react-native/codegen) for your project. The following options are available:

```
npx @react-native-community/cli codegen --help

Usage: rnc-cli codegen [options]



Options:

  --verbose            Increase logging verbosity

  --path <path>        Path to the React Native project root. (default: "/Users/MyUsername/projects/my-app")

  --platform <string>  Target platform. Supported values: "android", "ios", "all". (default: "all")

  --outputPath <path>  Path where generated artifacts will be output to.

  -h, --help           display help for command
```

## Examples[​](#examples "Direct link to Examples")

* Read `package.json` from the current working directory, generate code based on its codegenConfig.

```
npx @react-native-community/cli codegen
```

* Read `package.json` from the current working directory, generate iOS code in the location defined in the codegenConfig.

```
npx @react-native-community/cli codegen --platform ios
```

* Read `package.json` from `third-party/some-library`, generate Android code in `third-party/some-library/android/generated`.

```
npx @react-native-community/cli codegen \

    --path third-party/some-library \

    --platform android \

    --outputPath third-party/some-library/android/generated
```

----
url: https://reactnative.dev/docs/next/fabric-native-components-introduction
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/fabric-native-components-introduction)** (0.87).

Version: Next

```
npx @react-native-community/cli@latest init Demo --install-pods false
```

## Creating a WebView Component[​](#creating-a-webview-component "Direct link to Creating a WebView Component")

This guide will show you how to create a Web View component. We will be creating the component by using the Android's [`WebView`](https://developer.android.com/reference/android/webkit/WebView) component, and the iOS [`WKWebView`](https://developer.apple.com/documentation/webkit/wkwebview?language=objc) component.

Let's start by creating the folders structure to hold our component's code:

```
mkdir -p Demo/{specs,android/app/src/main/java/com/webview}
```

This gives you the following layout where you'll working:

```
Demo

├── android/app/src/main/java/com/webview

└── ios

└── specs
```

* The `android/app/src/main/java/com/webview` folder is the folder that will contain our Android code.
* The `ios` folder is the folder that will contain our iOS code.
* The `specs` folder is the folder that will contain the Codegen's specification file.

## 1. Define Specification for Codegen[​](#1-define-specification-for-codegen "Direct link to 1. Define Specification for Codegen")

Your specification must be defined in either [TypeScript](https://www.typescriptlang.org/) or [Flow](https://flow.org/) (see [Codegen](/docs/next/the-new-architecture/what-is-codegen) documentation for more details). This is used by Codegen to generate the C++, Objective-C++ and Java to connect your platform code to the JavaScript runtime that React runs in.

The specification file must be named `<MODULE_NAME>NativeComponent.{ts|js}` to work with Codegen. The suffix `NativeComponent` is not only a convention, it is actually used by Codegen to detect a spec file.

Use this specification for our WebView Component:

* TypeScript
* Flow

Demo/specs/WebViewNativeComponent.ts

```
import type {

  CodegenTypes,

  HostComponent,

  ViewProps,

} from 'react-native';

import {codegenNativeComponent} from 'react-native';



type WebViewScriptLoadedEvent = {

  result: 'success' | 'error';

};



export interface NativeProps extends ViewProps {

  sourceURL?: string;

  onScriptLoaded?: CodegenTypes.BubblingEventHandler<WebViewScriptLoadedEvent> | null;

}



export default codegenNativeComponent<NativeProps>(

  'CustomWebView',

) as HostComponent<NativeProps>;
```

Demo/RCTWebView/js/RCTWebViewNativeComponent.js

```
// @flow strict-local



import type {CodegenTypes, HostComponent, ViewProps} from 'react-native';

import {codegenNativeComponent} from 'react-native';



type WebViewScriptLoadedEvent = $ReadOnly<{|

  result: "success" | "error",

|}>;



type NativeProps = $ReadOnly<{|

  ...ViewProps,

  sourceURL?: string;

  onScriptLoaded?: CodegenTypes.BubblingEventHandler<WebViewScriptLoadedEvent>?;

|}>;



export default (codegenNativeComponent<NativeProps>(

  'CustomWebView',

): HostComponent<NativeProps>);
```

This specification is composed of three main parts, excluding the imports:

* The `WebViewScriptLoadedEvent` is a supporting data type for the data the event needs to pass from native to JavaScript.
* The `NativeProps` is a definition of the props that we can set on the component.
* The `codegenNativeComponent` statement allows us to codegenerate the code for the custom component and that defines a name for the component used to match the native implementations.

As with Native Modules, you can have multiple specification files in the `specs/` directory. For more information about the types you can use, and the platform types these map to, see the [appendix](/docs/next/appendix#ii-codegen-typings).

## 2. Configure Codegen to run[​](#2-configure-codegen-to-run "Direct link to 2. Configure Codegen to run")

The specification is used by the React Native's Codegen tools to generate platform specific interfaces and boilerplate for us. To do this, Codegen needs to know where to find our specification and what to do with it. Update your `package.json` to include:

JSON

```
    "start": "react-native start",

    "test": "jest"

  },

  "codegenConfig": {

    "name": "AppSpec",

    "type": "components",

    "jsSrcsDir": "specs",

    "android": {

      "javaPackageName": "com.webview"

    },

    "ios": {

      "componentProvider": {

        "CustomWebView": "RCTWebView"

      }

    }

  },

  "dependencies": {
```

```
cd android

./gradlew generateCodegenArtifactsFromSchema
```

```
package com.webview;



import android.content.Context;

import android.util.AttributeSet;

import android.webkit.WebView;

import android.webkit.WebViewClient;



import com.facebook.react.bridge.Arguments;

import com.facebook.react.bridge.WritableMap;

import com.facebook.react.bridge.ReactContext;

import com.facebook.react.uimanager.UIManagerHelper;

import com.facebook.react.uimanager.events.Event;



public class ReactWebView extends WebView {

  public ReactWebView(Context context) {

    super(context);

    configureComponent();

  }



  public ReactWebView(Context context, AttributeSet attrs) {

    super(context, attrs);

    configureComponent();

  }



  public ReactWebView(Context context, AttributeSet attrs, int defStyleAttr) {

    super(context, attrs, defStyleAttr);

    configureComponent();

  }



  private void configureComponent() {

    this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    this.setWebViewClient(new WebViewClient() {

      @Override

      public void onPageFinished(WebView view, String url) {

        emitOnScriptLoaded(OnScriptLoadedEventResult.success);

      }

    });

  }



  public void emitOnScriptLoaded(OnScriptLoadedEventResult result) {

    ReactContext reactContext = (ReactContext) context;

    int surfaceId = UIManagerHelper.getSurfaceId(reactContext);

    EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());

    WritableMap payload = Arguments.createMap();

    payload.putString("result", result.name());



    OnScriptLoadedEvent event = new OnScriptLoadedEvent(surfaceId, getId(), payload);

    if (eventDispatcher != null) {

      eventDispatcher.dispatchEvent(event);

    }

  }



  public enum OnScriptLoadedEventResult {

    success,

    error

  }



  private class OnScriptLoadedEvent extends Event<OnScriptLoadedEvent> {

    private final WritableMap payload;



    OnScriptLoadedEvent(int surfaceId, int viewId, WritableMap payload) {

      super(surfaceId, viewId);

      this.payload = payload;

    }



    @Override

    public String getEventName() {

      return "onScriptLoaded";

    }



    @Override

    public WritableMap getEventData() {

      return payload;

    }

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebView\.kt

```
package com.webview



import android.content.Context

import android.util.AttributeSet

import android.webkit.WebView

import android.webkit.WebViewClient

import com.facebook.react.bridge.Arguments

import com.facebook.react.bridge.WritableMap

import com.facebook.react.bridge.ReactContext

import com.facebook.react.uimanager.UIManagerHelper

import com.facebook.react.uimanager.events.Event



class ReactWebView: WebView {

  constructor(context: Context) : super(context) {

    configureComponent()

  }



  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {

    configureComponent()

  }



  constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {

    configureComponent()

  }



  private fun configureComponent() {

    this.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)

    this.webViewClient = object : WebViewClient() {

      override fun onPageFinished(view: WebView, url: String) {

        emitOnScriptLoaded(OnScriptLoadedEventResult.success)

      }

    }

  }



  fun emitOnScriptLoaded(result: OnScriptLoadedEventResult) {

    val reactContext = context as ReactContext

    val surfaceId = UIManagerHelper.getSurfaceId(reactContext)

    val eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id)

    val payload =

        Arguments.createMap().apply {

          putString("result", result.name)

        }

    val event = OnScriptLoadedEvent(surfaceId, id, payload)



    eventDispatcher?.dispatchEvent(event)

  }



  enum class OnScriptLoadedEventResult {

    success,

    error;

  }



  inner class OnScriptLoadedEvent(

      surfaceId: Int,

      viewId: Int,

      private val payload: WritableMap

  ) : Event<OnScriptLoadedEvent>(surfaceId, viewId) {

    override fun getEventName() = "onScriptLoaded"



    override fun getEventData() = payload

  }

}
```

```
package com.webview;



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.annotations.ReactModule;

import com.facebook.react.uimanager.SimpleViewManager;

import com.facebook.react.uimanager.ThemedReactContext;

import com.facebook.react.uimanager.ViewManagerDelegate;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;

import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;



import java.util.HashMap;

import java.util.Map;



@ReactModule(name = ReactWebViewManager.REACT_CLASS)

class ReactWebViewManager extends SimpleViewManager<ReactWebView> implements CustomWebViewManagerInterface<ReactWebView> {

  private final CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> delegate =

          new CustomWebViewManagerDelegate<>(this);



  @Override

  public ViewManagerDelegate<ReactWebView> getDelegate() {

    return delegate;

  }



  @Override

  public String getName() {

    return REACT_CLASS;

  }



  @Override

  public ReactWebView createViewInstance(ThemedReactContext context) {

    return new ReactWebView(context);

  }



  @ReactProp(name = "sourceUrl")

  @Override

  public void setSourceURL(ReactWebView view, String sourceURL) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error);

      return;

    }

    view.loadUrl(sourceURL, new HashMap<>());

  }



  public static final String REACT_CLASS = "CustomWebView";



  @Override

  public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {

    Map<String, Object> map = new HashMap<>();

    Map<String, Object> bubblingMap = new HashMap<>();

    bubblingMap.put("phasedRegistrationNames", new HashMap<String, String>() {{

      put("bubbled", "onScriptLoaded");

      put("captured", "onScriptLoadedCapture");

    }});

    map.put("onScriptLoaded", bubblingMap);

    return map;

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebViewManager.kt

```
package com.webview



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.annotations.ReactModule;

import com.facebook.react.uimanager.SimpleViewManager;

import com.facebook.react.uimanager.ThemedReactContext;

import com.facebook.react.uimanager.ViewManagerDelegate;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;

import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;



@ReactModule(name = ReactWebViewManager.REACT_CLASS)

class ReactWebViewManager(context: ReactApplicationContext) : SimpleViewManager<ReactWebView>(), CustomWebViewManagerInterface<ReactWebView> {

  private val delegate: CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> =

    CustomWebViewManagerDelegate(this)



  override fun getDelegate(): ViewManagerDelegate<ReactWebView> = delegate



  override fun getName(): String = REACT_CLASS



  override fun createViewInstance(context: ThemedReactContext): ReactWebView = ReactWebView(context)



  @ReactProp(name = "sourceUrl")

  override fun setSourceURL(view: ReactWebView, sourceURL: String?) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error)

      return;

    }

    view.loadUrl(sourceURL, emptyMap())

  }



  companion object {

    const val REACT_CLASS = "CustomWebView"

  }



  override fun getExportedCustomBubblingEventTypeConstants(): Map<String, Any> =

      mapOf(

          "onScriptLoaded" to

              mapOf(

                  "phasedRegistrationNames" to

                      mapOf(

                          "bubbled" to "onScriptLoaded",

                          "captured" to "onScriptLoadedCapture"

                      )))

}
```

```
package com.webview;



import com.facebook.react.BaseReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.model.ReactModuleInfo;

import com.facebook.react.module.model.ReactModuleInfoProvider;

import com.facebook.react.uimanager.ViewManager;



import java.util.Collections;

import java.util.HashMap;

import java.util.List;

import java.util.Map;



public class ReactWebViewPackage extends BaseReactPackage {

  @Override

  public List<ViewManager<?, ?>> createViewManagers(ReactApplicationContext reactContext) {

    return Collections.singletonList(new ReactWebViewManager(reactContext));

  }



  @Override

  public NativeModule getModule(String s, ReactApplicationContext reactApplicationContext) {

    if (ReactWebViewManager.REACT_CLASS.equals(s)) {

      return new ReactWebViewManager(reactApplicationContext);

    }

    return null;

  }



  @Override

  public ReactModuleInfoProvider getReactModuleInfoProvider() {

    return new ReactModuleInfoProvider() {

      @Override

      public Map<String, ReactModuleInfo> getReactModuleInfos() {

        Map<String, ReactModuleInfo> map = new HashMap<>();

        map.put(ReactWebViewManager.REACT_CLASS, new ReactModuleInfo(

                ReactWebViewManager.REACT_CLASS, // name

                ReactWebViewManager.REACT_CLASS, // className

                false,                           // canOverrideExistingModule

                false,                           // needsEagerInit

                false,                           // isCxxModule

                true                             // isTurboModule

        ));

        return map;

      }

    };

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebViewPackage.kt

```
package com.webview



import com.facebook.react.BaseReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.module.model.ReactModuleInfo

import com.facebook.react.module.model.ReactModuleInfoProvider

import com.facebook.react.uimanager.ViewManager



class ReactWebViewPackage : BaseReactPackage() {

  override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {

    return listOf(ReactWebViewManager(reactContext))

  }



  override fun getModule(s: String, reactApplicationContext: ReactApplicationContext): NativeModule? {

    when (s) {

      ReactWebViewManager.REACT_CLASS -> ReactWebViewManager(reactApplicationContext)

    }

    return null

  }



  override fun getReactModuleInfoProvider(): ReactModuleInfoProvider = ReactModuleInfoProvider {

    mapOf(ReactWebViewManager.REACT_CLASS to ReactModuleInfo(

      name = ReactWebViewManager.REACT_CLASS,

      className = ReactWebViewManager.REACT_CLASS,

      canOverrideExistingModule = false,

      needsEagerInit = false,

      isCxxModule = false,

      isTurboModule = true,

    )

    )

  }

}
```

```
package com.demo



import android.app.Application

import com.facebook.react.PackageList

import com.facebook.react.ReactApplication

import com.facebook.react.ReactHost

import com.facebook.react.ReactNativeHost

import com.facebook.react.ReactPackage

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

import com.facebook.react.defaults.DefaultReactNativeHost

import com.facebook.react.soloader.OpenSourceMergedSoMapping

import com.facebook.soloader.SoLoader

import com.webview.ReactWebViewPackage



class MainApplication : Application(), ReactApplication {



  override val reactNativeHost: ReactNativeHost =

      object : DefaultReactNativeHost(this) {

        override fun getPackages(): List<ReactPackage> =

            PackageList(this).packages.apply {

              add(ReactWebViewPackage())

            }



        override fun getJSMainModuleName(): String = "index"



        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG



        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

      }



  override val reactHost: ReactHost

    get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

    SoLoader.init(this, OpenSourceMergedSoMapping)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      load()

    }

  }

}
```

Now it's time to write some iOS platform code to be able to render the web view. The steps you need to follow are:

* Run Codegen.
* Write the code for the `RCTWebView`
* Register the `RCTWebView` in the application

### 1. Run Codegen[​](#1-run-codegen "Direct link to 1. Run Codegen")

You can [manually run](/docs/next/the-new-architecture/codegen-cli) the Codegen, however it's simpler to use the application you're going to demo the component in to do this for you.

```
cd ios

bundle install

bundle exec pod install
```

Importantly you will see logging output from Codegen, which we're going to use in Xcode to build our WebView native component.

warning

You should be careful about committing generated code to your repository. Generated code is specific to each version of React Native. Use npm [peerDependencies](https://nodejs.org/en/blog/npm/peer-dependencies) to restrict compatibility with version of React Native.

### 3. Write the `RCTWebView`[​](#3-write-the-rctwebview "Direct link to 3-write-the-rctwebview")

We need to prepare your iOS project using Xcode by completing these **5 steps**:

1. Open the CocoaPods generated Xcode Workspace:

```
cd ios

open Demo.xcworkspace
```

2. Right click on app and select `New Group`, call the new group `WebView`.

3) In the `WebView` group, create `New`→`File from Template`.

4. Use the `Objective-C File` template, and name it `RCTWebView`.

5) Repeat step 4 and create a header file named `RCTWebView.h`.

6) Rename `RCTWebView.m` → `RCTWebView.mm` making it an Objective-C++ file.

Demo/ios

```
Podfile

...

Demo

├── AppDelegate.swift

├── SceneDelegate.swift

...

├── RCTWebView.h

└── RCTWebView.mm
```

After creating the header file and the implementation file, you can start implementing them.

This is the code for the `RCTWebView.h` file, which declares the component interface.

Demo/RCTWebView/RCTWebView\.h

```
#import <React/RCTViewComponentView.h>

#import <UIKit/UIKit.h>



NS_ASSUME_NONNULL_BEGIN



@interface RCTWebView : RCTViewComponentView



// You would declare native methods you'd want to access from the view here



@end



NS_ASSUME_NONNULL_END
```

This class defines an `RCTWebView` which extends the `RCTViewComponentView` class. This is the base class for all the native components and it is provided by React Native.

The code for the implementation file (`RCTWebView.mm`) is the following:

Demo/RCTWebView/RCTWebView\.mm

```
#import "RCTWebView.h"



#import <react/renderer/components/AppSpec/ComponentDescriptors.h>

#import <react/renderer/components/AppSpec/EventEmitters.h>

#import <react/renderer/components/AppSpec/Props.h>

#import <react/renderer/components/AppSpec/RCTComponentViewHelpers.h>

#import <WebKit/WebKit.h>



using namespace facebook::react;



@interface RCTWebView () <RCTCustomWebViewViewProtocol, WKNavigationDelegate>

@end



@implementation RCTWebView {

  NSURL * _sourceURL;

  WKWebView * _webView;

}



-(instancetype)init

{

  if(self = [super init]) {

    _webView = [WKWebView new];

    _webView.navigationDelegate = self;

    [self addSubview:_webView];

  }

  return self;

}



- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps

{

  const auto &oldViewProps = *std::static_pointer_cast<CustomWebViewProps const>(_props);

  const auto &newViewProps = *std::static_pointer_cast<CustomWebViewProps const>(props);



  // Handle your props here

  if (oldViewProps.sourceURL != newViewProps.sourceURL) {

    NSString *urlString = [NSString stringWithCString:newViewProps.sourceURL.c_str() encoding:NSUTF8StringEncoding];

    _sourceURL = [NSURL URLWithString:urlString];

    if ([self urlIsValid:newViewProps.sourceURL]) {

      [_webView loadRequest:[NSURLRequest requestWithURL:_sourceURL]];

    }

  }



  [super updateProps:props oldProps:oldProps];

}



-(void)layoutSubviews

{

  [super layoutSubviews];

  _webView.frame = self.bounds;



}



#pragma mark - WKNavigationDelegate



-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{

  CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Success};

  self.eventEmitter.onScriptLoaded(result);

}



- (BOOL)urlIsValid:(std::string)propString

{

  if (propString.length() > 0 && !_sourceURL) {

    CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Error};



    self.eventEmitter.onScriptLoaded(result);

    return NO;

  }

  return YES;

}



// Event emitter convenience method

- (const CustomWebViewEventEmitter &)eventEmitter

{

  return static_cast<const CustomWebViewEventEmitter &>(*_eventEmitter);

}



+ (ComponentDescriptorProvider)componentDescriptorProvider

{

  return concreteComponentDescriptorProvider<CustomWebViewComponentDescriptor>();

}



@end
```

```
import {Alert, StyleSheet, View} from 'react-native';

import WebView from './specs/WebViewNativeComponent';



function App(): React.JSX.Element {

  return (

    <View style={styles.container}>

      <WebView

        sourceURL="https://react.dev/"

        style={styles.webview}

        onScriptLoaded={() => {

          Alert.alert('Page Loaded');

        }}

      />

    </View>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    alignItems: 'center',

    alignContent: 'center',

  },

  webview: {

    width: '100%',

    height: '100%',

  },

});



export default App;
```

This code creates an app that uses the new `WebView` component we created to load the `react.dev` website.

The app also shows an alert when the web page is loaded.

## 4. Run your App using the WebView Component[​](#4-run-your-app-using-the-webview-component "Direct link to 4. Run your App using the WebView Component")

* Android
* iOS

```
yarn run android
```

```
yarn run ios
```

| Android | iOS |
| ------- | --- |
|         |     |

* [Creating a WebView Component](#creating-a-webview-component)
* [1. Define Specification for Codegen](#1-define-specification-for-codegen)
* [2. Configure Codegen to run](#2-configure-codegen-to-run)
* [2. Building your Native Code](#2-building-your-native-code)
* [3. Use your Native Component](#3-use-your-native-component)
* [4. Run your App using the WebView Component](#4-run-your-app-using-the-webview-component)

----
url: https://reactnative.dev/docs/next/global-XMLHttpRequest
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-XMLHttpRequest)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) for more information.

The global `XMLHttpRequest` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/global-PerformanceObserverEntryList
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-PerformanceObserverEntryList)** (0.87).

Version: Next

The global [`PerformanceObserverEntryList`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/the-new-architecture/native-modules-lifecycle
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/native-modules-lifecycle)** (0.87).

Version: Next

```
+ #import <React/RCTInitializing.h>



//...



- @interface NativeModule : NSObject <NativeModuleSpec>

+ @interface NativeModule : NSObject <NativeModuleSpec, RCTInitializing>

//...

@end
```

2. Implement the `initialize` method in the `NativeModule.mm` file:

NativeModule.mm

```
// ...



@implementation NativeModule



+- (void)initialize {

+ // add the initialization code here

+}



@end
```

These are some Native Modules from core that implements the `initialize` method: [RCTBlobManager](https://github.com/react/react-native/blob/0617accecdcb11159ba15c34885f294bc206aa89/packages/react-native/Libraries/Blob/RCTBlobManager.mm#L58-L68), [RCTTiming](https://github.com/react/react-native/blob/0617accecdcb11159ba15c34885f294bc206aa89/packages/react-native/React/CoreModules/RCTTiming.mm#L121-L124).

If your module needs to run some cleanup code, then you can conform to the `RCTInvalidating` protocol and implement the `invalidate` method. To do so, you have to:

1. Moduify the `NativeModule.h` file by adding the following lines:

NativeModule.h

```
+ #import <React/RCTInvalidating.h>



//...



- @interface NativeModule : NSObject <NativeModuleSpec>

+ @interface NativeModule : NSObject <NativeModuleSpec, RCTInvalidating>



//...



@end
```

2. Implement the `invalidate` method in the `NativeModule.mm` file:

NativeModule.mm

```


// ...



@implementation NativeModule



+- (void)invalidate {

+ // add the cleanup code here

+}



@end
```

These are some Native Modules from core that implements the `invalidate` method: [RCTAppearance](https://github.com/react/react-native/blob/0617accecdcb11159ba15c34885f294bc206aa89/packages/react-native/React/CoreModules/RCTAppearance.mm#L151-L155), [RCTDeviceInfo](https://github.com/react/react-native/blob/0617accecdcb11159ba15c34885f294bc206aa89/packages/react-native/React/CoreModules/RCTDeviceInfo.mm#L127-L133).

* [Android](#android)
* [iOS](#ios)

----
url: https://reactnative.dev/docs/the-new-architecture/fabric-component-native-commands
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
import type {HostComponent, ViewProps} from 'react-native';

import type {BubblingEventHandler} from 'react-native/Libraries/Types/CodegenTypes';

import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

+import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands';



type WebViewScriptLoadedEvent = {

  result: 'success' | 'error';

};



export interface NativeProps extends ViewProps {

  sourceURL?: string;

  onScriptLoaded?: BubblingEventHandler<WebViewScriptLoadedEvent> | null;

}



+interface NativeCommands {

+    reload: (viewRef: React.ElementRef<HostComponent<NativeProps>>) => void;

+}



+export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({

+    supportedCommands: ['reload'],

+});



export default codegenNativeComponent<NativeProps>(

  'CustomWebView',

) as HostComponent<NativeProps>;
```

Update the `WebViewNativeComponent.js` as it follows:

Demo/specs/WebViewNativeComponent.js

```
// @flow strict-local



import type {HostComponent, ViewProps} from 'react-native';

import type {BubblingEventHandler} from 'react-native/Libraries/Types/CodegenTypes';

import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

+import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands';



type WebViewScriptLoadedEvent = $ReadOnly<{|

  result: "success" | "error",

|}>;



type NativeProps = $ReadOnly<{|

  ...ViewProps,

  sourceURL?: string;

  onScriptLoaded?: BubblingEventHandler<WebViewScriptLoadedEvent>?;

|}>;



+interface NativeCommands {

+    reload: (viewRef: React.ElementRef<HostComponent<NativeProps>>) => void;

+}



+export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({

+    supportedCommands: ['reload'],

+});



export default (codegenNativeComponent<NativeProps>(

  'CustomWebView',

): HostComponent<NativeProps>);
```

```
-import {Alert, StyleSheet, View} from 'react-native';

-import WebView from '../specs/WebViewNativeComponent';

+import {Alert, StyleSheet, Pressable, Text, View} from 'react-native';

+import WebView, {Commands} from '../specs/WebViewNativeComponent';



function App(): React.JSX.Element {

+    const webViewRef = React.useRef<React.ElementRef<typeof View> | null>(null);

+

+    const refresh = () => {

+        if (webViewRef.current) {

+            Commands.reload(webViewRef.current);

+        }

+    };



  return (

    <View style={styles.container}>

      <WebView

+       ref={webViewRef}

        sourceURL="https://react.dev/"

        style={styles.webview}

        onScriptLoaded={() => {

          Alert.alert('Page Loaded');

        }}

      />

+      <View style={styles.tabbar}>

+        <Pressable onPress={refresh} style={styles.button}>

+            {({pressed}) => (

+                !pressed ? <Text style={styles.buttonText}>Refresh</Text> : <Text style={styles.buttonTextPressed}>Refresh</Text>) }

+        </Pressable>

+      </View>

    </View>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    alignItems: 'center',

    alignContent: 'center',

  },

  webview: {

    width: '100%',

-    height: '100%',

+    height: '90%',

  },

+  tabbar: {

+    flex: 1,

+    backgroundColor: 'gray',

+    width: '100%',

+    alignItems: 'center',

+    alignContent: 'center',

+  },

+  button: {

+    margin: 10,

+  },

+  buttonText: {

+    fontSize: 20,

+    fontWeight: 'bold',

+    color: '#00D6FF',

+    width: '100%',

+  },

+  buttonTextPressed: {

+    fontSize: 20,

+    fontWeight: 'bold',

+    color: '#00D6FF77',

+    width: '100%',

+  },

});



export default App;
```

Open the `App.tsx` file and modify it as it follows:

App.jsx

```
-import {Alert, StyleSheet, View} from 'react-native';

-import WebView from '../specs/WebViewNativeComponent';

+import {Alert, StyleSheet, Pressable, Text, View} from 'react-native';

+import WebView, {Commands} from '../specs/WebViewNativeComponent';



function App(): React.JSX.Element {

+    const webViewRef = React.useRef<React.ElementRef<typeof View> | null>(null);

+

+    const refresh = () => {

+        if (webViewRef.current) {

+            Commands.reload(webViewRef.current);

+        }

+    };



  return (

    <View style={styles.container}>

      <WebView

+       ref={webViewRef}

        sourceURL="https://react.dev/"

        style={styles.webview}

        onScriptLoaded={() => {

          Alert.alert('Page Loaded');

        }}

      />

+      <View style={styles.tabbar}>

+        <Pressable onPress={refresh} style={styles.button}>

+            {({pressed}) => (

+                !pressed ? <Text style={styles.buttonText}>Refresh</Text> : <Text style={styles.buttonTextPressed}>Refresh</Text>) }

+        </Pressable>

+      </View>

    </View>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    alignItems: 'center',

    alignContent: 'center',

  },

  webview: {

    width: '100%',

-    height: '100%',

+    height: '90%',

  },

+  tabbar: {

+    flex: 1,

+    backgroundColor: 'gray',

+    width: '100%',

+    alignItems: 'center',

+    alignContent: 'center',

+  },

+  button: {

+    margin: 10,

+  },

+  buttonText: {

+    fontSize: 20,

+    fontWeight: 'bold',

+    color: '#00D6FF',

+    width: '100%',

+  },

+  buttonTextPressed: {

+    fontSize: 20,

+    fontWeight: 'bold',

+    color: '#00D6FF77',

+    width: '100%',

+  },

});



export default App;
```

```
cd android

./gradlew generateCodegenArtifactsFromSchema



BUILD SUCCESSFUL in 837ms

14 actionable tasks: 3 executed, 11 up-to-date
```

This is automatically run when you build your Android application.

Codegen is run as part of the script phases that's automatically added to the project generated by CocoaPods.

```
cd ios

bundle install

bundle exec pod install
```

The output will look like this:

```
...

Framework build type is static library

[Codegen] Adding script_phases to ReactCodegen.

[Codegen] Generating ./build/generated/ios/ReactCodegen.podspec.json

[Codegen] Analyzing /Users/me/src/TurboModuleExample/package.json

[Codegen] Searching for codegen-enabled libraries in the app.

[Codegen] Found TurboModuleExample

[Codegen] Searching for codegen-enabled libraries in the project dependencies.

[Codegen] Found react-native

...
```

```


//...

  @ReactProp(name = "sourceUrl")

  @Override

  public void setSourceURL(ReactWebView view, String sourceURL) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error);

      return;

    }

    view.loadUrl(sourceURL, new HashMap<>());

  }



+  @Override

+  public void reload(ReactWebView view) {

+    view.reload();

+  }



  public static final String REACT_CLASS = "CustomWebView";

//...
```

ReactWebViewManager.kt

```
  @ReactProp(name = "sourceUrl")

  override fun setSourceURL(view: ReactWebView, sourceURL: String?) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error)

      return;

    }

    view.loadUrl(sourceURL, emptyMap())

  }



+  override fun reload(view: ReactWebView) {

+    view.reload()

+  }



  companion object {

    const val REACT_CLASS = "CustomWebView"

  }
```

In this case, it's enough to call directly the `view.reload()` method because our ReactWebView inherits from the Android's `WebView` and it has a reload method directly available. If you are implementing a custom function, that is not available in your custom view, you might also have to implement the required method in the Android's View that is managed by the React Native's `ViewManager`.

To let your view respond to the Native Command, we need to implement a couple of methods on iOS.

Let's open the `RCTWebView.mm` file and let's modify it as it follows:

RCTWebView\.mm

```
  // Event emitter convenience method

  - (const CustomWebViewEventEmitter &)eventEmitter

  {

  return static_cast<const CustomWebViewEventEmitter &>(*_eventEmitter);

  }



+  - (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args

+  {

+  RCTCustomWebViewHandleCommand(self, commandName, args);

+  }

+

+  - (void)reload

+  {

+  [_webView reloadFromOrigin];

+  }



  + (ComponentDescriptorProvider)componentDescriptorProvider

  {

  return concreteComponentDescriptorProvider<CustomWebViewComponentDescriptor>();

  }
```

To make your view respond to the Native Commands, you need to apply the following changes:

1. Add a `handleCommand:args` function. This function is invoked by the components infrastructure to handle the commands. The function implementation is similar for every component: you need to call an `RCT<componentNameInJS>HandleCommand` function that is generated by Codegen for you. The `RCT<componentNameInJS>HandleCommand` perform a bunch of validation, verifying that the command that we need to invoke is among the supported ones and that the parameters passed matches the one expected. If all the checks pass, the `RCT<componentNameInJS>HandleCommand` will then invoke the proper native method.
2. Implement the `reload` method. In this example, the `reload` method calls the `reloadFromOrigin` function of the WebKit's WebView.

## 5. Run your app[​](#5-run-your-app "Direct link to 5. Run your app")

Finally, you can run your app with the usual commands. Once the app is running, you can tap on the refresh button to see the page getting reloaded.

| Android | iOS |
| ------- | --- |
|         |     |

* [1. Update your component specs](#1-update-your-component-specs)
* [2. Update the App code to use the new command](#2-update-the-app-code-to-use-the-new-command)
* [3. Rerun Codegen](#3-rerun-codegen)
* [4. Implement the Native Code](#4-implement-the-native-code)
* [5. Run your app](#5-run-your-app)

----
url: https://reactnative.dev/docs/next/global-performance
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-performance)** (0.87).

Version: Next

The global [`performance`](https://developer.mozilla.org/en-US/docs/Web/API/Window/performance) object, as defined in Web specifications.

***

```
get rnStartupTiming(): ReactNativeStartupTiming;
```

The `ReactNativeStartupTiming` interface provides the following fields:

| Name                                     | Type           | Description                                               |
| ---------------------------------------- | -------------- | --------------------------------------------------------- |
| `startTime`                              | number \| void | When the React Native runtime initialization was started. |
| `executeJavaScriptBundleEntryPointStart` | number \| void | When the execution of the application bundle was started. |
| `endTime`                                | number \| void | When the React Native runtime was fully initialized.      |

----
url: https://reactnative.dev/docs/next/appearance
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/appearance)** (0.87).

Version: Next

React TSX

```
import {Appearance} from 'react-native';
```

```
const colorScheme = Appearance.getColorScheme();

if (colorScheme === 'dark') {

  // Use dark color scheme

}
```

Although the color scheme is available immediately, this may change when not overridden via `setColorScheme()` (e.g. scheduled color scheme change at sunrise or sunset). Any rendering logic or styles that depend on the user preferred color scheme should try to call this function on every render, rather than caching the value.

**Recommended:** Use the [`useColorScheme`](/docs/next/usecolorscheme) hook.

### App-level overriding[​](#app-level-overriding "Direct link to App-level overriding")

`setColorScheme()` overrides the color scheme at the application level — it does not affect the system setting or other applications. Passing `'auto'` removes any override, restoring the system preference.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `getColorScheme()`[​](#getcolorscheme "Direct link to getcolorscheme")

React TSX

```
static getColorScheme(): 'light' | 'dark' | null;
```

Returns the active color scheme. This value may change at runtime, either at the system level (e.g. scheduled color scheme change at sunrise or sunset) or when overridden at the app level via `setColorScheme()`.

Return values:

* `'light'`: The light color scheme is applied.
* `'dark'`: The dark color scheme is applied.
* `null`: May be returned if the native Appearance module is not available.

See also: [`useColorScheme`](/docs/next/usecolorscheme) (hook).

***

### `setColorScheme()`[​](#setcolorscheme "Direct link to setcolorscheme")

React TSX

```
static setColorScheme('light' | 'dark' | 'auto' | 'unspecified'): void;
```

***

### `addChangeListener()`[​](#addchangelistener "Direct link to addchangelistener")

React TSX

```
static addChangeListener(

  listener: (preferences: {colorScheme: 'light' | 'dark' | null}) => void,

): EventSubscription;
```

----
url: https://reactnative.dev/docs/next/global-Request
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-Request)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Request) for more information.

The global `Request` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/reactnativeversion
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/reactnativeversion)** (0.87).

Version: Next

React TSX

```
import {ReactNativeVersion} from 'react-native';
```

The `ReactNativeVersion` API exposes the version of the resolved `react-native` package on JS side. Apps and libraries can use it to check compatibility or enable version-specific behavior.

note

Also, we have [`Platform.constants.reactNativeVersion`](/docs/next/platform#constants) in our public API already. **However**, this is the per-platform ***native-reported*** React Native version.

## Example[​](#example "Direct link to Example")

React TSX

```
import {ReactNativeVersion} from 'react-native';



const version = ReactNativeVersion.getVersionString(); // 0.88.1

const {major, minor, patch, prerelease} = ReactNativeVersion;

major; // 0

minor; // 88

patch; // 1

prerelease; // null
```

***

# Reference

## Properties[​](#properties "Direct link to Properties")

### `major`[​](#major "Direct link to major")

React TSX

```
static major: number;
```

The major version number of the resolved `react-native` package.

***

### `minor`[​](#minor "Direct link to minor")

React TSX

```
static minor: number;
```

The minor version number of the resolved `react-native` package.

***

### `patch`[​](#patch "Direct link to patch")

React TSX

```
static patch: number;
```

The patch version number of the resolved `react-native` package.

***

### `prerelease`[​](#prerelease "Direct link to prerelease")

React TSX

```
static prerelease: string | null;
```

The prerelease tag for the resolved `react-native` package, or `null` for stable releases.

## Methods[​](#methods "Direct link to Methods")

### `getVersionString()`[​](#getversionstring "Direct link to getversionstring")

React TSX

```
static getVersionString(): string;
```

----
url: https://reactnative.dev/docs/global-navigator
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator) for more information.

The global `navigator` object, as defined in Web specifications.

----
url: https://reactnative.dev/docs/viewtoken
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`ViewToken` object is returned as one of the properties in the `onViewableItemsChanged` callback (for example, in the [FlatList](/docs/flatlist) component). It is exported by [`ViewabilityHelper.js`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Lists/ViewabilityHelper.js).

## Example[​](#example "Direct link to Example")

JavaScript

```
{

  item: {key: "key-12"},

  key: "key-12",

  index: 11,

  isViewable: true

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `index`[​](#index "Direct link to index")

Unique numeric identifier assigned to the data element.

This property may be `null` when the viewable element is not an item from the data array, for example when a section header or section footer becomes viewable in [`SectionList`](/docs/sectionlist).

| Type   | Optional |
| ------ | -------- |
| number | Yes      |

### `isViewable`[​](#isviewable "Direct link to isviewable")

Specifies if at least some part of list element is visible in the viewport.

| Type    | Optional |
| ------- | -------- |
| boolean | No       |

### `item`[​](#item "Direct link to item")

Item data

| Type | Optional |
| ---- | -------- |
| any  | No       |

### `key`[​](#key "Direct link to key")

Key identifier assigned to the data element extracted to the top level.

| Type   | Optional |
| ------ | -------- |
| string | No       |

### `section`[​](#section "Direct link to section")

Item section data when used with `SectionList`.

| Type | Optional |
| ---- | -------- |
| any  | Yes      |

## Used by[​](#used-by "Direct link to Used by")

* [`FlatList`](/docs/flatlist)
* [`SectionList`](/docs/sectionlist)
* [`VirtualizedList`](/docs/virtualizedlist)

----
url: https://reactnative.dev/docs/next/performance
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/performance)** (0.87).

Version: Next

A compelling reason to use React Native instead of WebView-based tools is to achieve at least 60 frames per second and provide a native look and feel to your apps. Whenever feasible, we aim for React Native to handle optimizations automatically, allowing you to focus on your app without worrying about performance. However, there are certain areas where we haven't quite reached that level yet, and others where React Native (similar to writing native code directly) cannot determine the best optimization approach for you. In such cases, manual intervention becomes necessary. We strive to deliver buttery-smooth UI performance by default, but there may be instances where that isn't possible.

This guide is intended to teach you some basics to help you to [troubleshoot performance issues](/docs/next/profiling), as well as discuss [common sources of problems and their suggested solutions](/docs/next/performance#common-sources-of-performance-problems).

## What you need to know about frames[​](#what-you-need-to-know-about-frames "Direct link to What you need to know about frames")

Your grandparents' generation called movies ["moving pictures"](https://www.youtube.com/watch?v=F1i40rnpOsA) for a reason: realistic motion in video is an illusion created by quickly changing static images at a consistent speed. We refer to each of these images as frames. The number of frames that is displayed each second has a direct impact on how smooth and ultimately life-like a video (or user interface) seems to be. iOS and Android devices display at least 60 frames per second, which gives you and the UI system at most 16.67ms to do all of the work needed to generate the static image (frame) that the user will see on the screen for that interval. If you are unable to do the work necessary to generate that frame within the allotted time slot, then you will "drop a frame" and the UI will appear unresponsive.

Now to confuse the matter a little bit, open up the [Dev Menu](/docs/next/debugging#opening-the-dev-menu) in your app and toggle `Show Perf Monitor`. You will notice that there are two different frame rates.

JavaScript thread performance suffers greatly when running in dev mode. This is unavoidable: a lot more work needs to be done at runtime to provide you with good warnings and error messages. Always make sure to test performance in [release builds](/docs/next/running-on-device#building-your-app-for-production).

### Using `console.log` statements[​](#using-consolelog-statements "Direct link to using-consolelog-statements")

When running a bundled app, these statements can cause a big bottleneck in the JavaScript thread. This includes calls from debugging libraries such as [redux-logger](https://github.com/evgenyrodionov/redux-logger), so make sure to remove them before bundling. You can also use this [babel plugin](https://babeljs.io/docs/plugins/transform-remove-console/) that removes all the `console.*` calls. You need to install it first with `npm i babel-plugin-transform-remove-console --save-dev`, and then edit the `.babelrc` file under your project directory like this:

JSON

```
{

  "env": {

    "production": {

      "plugins": ["transform-remove-console"]

    }

  }

}
```

This will automatically remove all `console.*` calls in the release (production) versions of your project.

It is recommended to use the plugin even if no `console.*` calls are made in your project. A third party library could also call them.

### `FlatList` rendering is too slow or scroll performance is bad for large lists[​](#flatlist-rendering-is-too-slow-or-scroll-performance-is-bad-for-large-lists "Direct link to flatlist-rendering-is-too-slow-or-scroll-performance-is-bad-for-large-lists")

If your [`FlatList`](/docs/next/flatlist) is rendering slowly, be sure that you've implemented [`getItemLayout`](/docs/next/flatlist#getitemlayout) to optimize rendering speed by skipping measurement of the rendered items.

There are also other third-party list libraries that are optimized for performance, including [FlashList](https://github.com/shopify/flash-list) and [Legend List](https://github.com/legendapp/legend-list).

### Dropping JS thread FPS because of doing a lot of work on the JavaScript thread at the same time[​](#dropping-js-thread-fps-because-of-doing-a-lot-of-work-on-the-javascript-thread-at-the-same-time "Direct link to Dropping JS thread FPS because of doing a lot of work on the JavaScript thread at the same time")

"Slow Navigator transitions" is the most common manifestation of this, but there are other times this can happen. Deferring work until the JS thread is idle (for example, with `requestIdleCallback`) can be a good approach, but if the user experience cost is too high to delay work during an animation, then you might want to consider [`LayoutAnimation`](/docs/next/layoutanimation).

The [`Animated API`](/docs/next/animated) currently calculates each keyframe on-demand on the JavaScript thread unless you [set `useNativeDriver: true`](/blog/2017/02/14/using-native-driver-for-animated#how-do-i-use-this-in-my-app), while [`LayoutAnimation`](/docs/next/layoutanimation) leverages Core Animation and is unaffected by JS thread and main thread frame drops.

One case for using this is animating in a modal (sliding down from top and fading in a translucent overlay) while initializing and perhaps receiving responses for several network requests, rendering the contents of the modal, and updating the view where the modal was opened from. See the [Animations guide](/docs/next/animations) for more information about how to use `LayoutAnimation`.

**Caveats:**

* `LayoutAnimation` only works for fire-and-forget animations ("static" animations) -- if it must be interruptible, you will need to use [`Animated`](/docs/next/animated).

### Moving a view on the screen (scrolling, translating, rotating) drops UI thread FPS[​](#moving-a-view-on-the-screen-scrolling-translating-rotating-drops-ui-thread-fps "Direct link to Moving a view on the screen (scrolling, translating, rotating) drops UI thread FPS")

This is especially true on Android when you have text with a transparent background positioned on top of an image, or any other situation where alpha compositing would be required to re-draw the view on each frame. You will find that enabling `renderToHardwareTextureAndroid` can help with this significantly. For iOS, `shouldRasterizeIOS` is already enabled by default.

Be careful not to overuse this or your memory usage could go through the roof. Profile your performance and memory usage when using these props. If you don't plan to move a view anymore, turn this property off.

### Animating the size of an image drops UI thread FPS[​](#animating-the-size-of-an-image-drops-ui-thread-fps "Direct link to Animating the size of an image drops UI thread FPS")

On iOS, each time you adjust the width or height of an [`Image` component](/docs/next/image) it is re-cropped and scaled from the original image. This can be very expensive, especially for large images. Instead, use the `transform: [{scale}]` style property to animate the size. An example of when you might do this is when you tap an image and zoom it in to full screen.

### My TouchableX view isn't very responsive[​](#my-touchablex-view-isnt-very-responsive "Direct link to 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. This may occur if `onPress` sets a state that results in a heavy re-render and a few frames are dropped as a result. A solution to this is to wrap any action inside of your `onPress` handler in `requestAnimationFrame`:

React TSX

```
function handleOnPress() {

  requestAnimationFrame(() => {

    this.doExpensiveAction();

  });

}
```

----
url: https://reactnative.dev/docs/checkbox
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=checkbox) instead.

----
url: https://reactnative.dev/docs/drawerlayoutandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Deprecated

Use [`react-native-drawer-layout`](https://reactnavigation.org/docs/drawer-layout/) instead.

React component that wraps the platform `DrawerLayout` (Android only). The Drawer (typically used for navigation) is rendered with `renderNavigationView` and direct children are the main view (where your content goes). The navigation view is initially not visible on the screen, but can be pulled in from the side of the window specified by the `drawerPosition` prop and its width can be set by the `drawerWidth` prop.

## Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### `drawerBackgroundColor`[​](#drawerbackgroundcolor "Direct link to 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:

React TSX

```
return (

  <DrawerLayoutAndroid drawerBackgroundColor="rgba(0,0,0,0.5)" />

);
```

| Type                  | Required |
| --------------------- | -------- |
| [color](/docs/colors) | No       |

***

### `drawerLockMode`[​](#drawerlockmode "Direct link to drawerlockmode")

Specifies the lock mode of the drawer. The drawer can be locked in 3 states:

* unlocked (default), meaning that the drawer will respond (open/close) to touch gestures.
* locked-closed, meaning that the drawer will stay closed and not respond to gestures.
* locked-open, meaning that the drawer will stay opened and not respond to gestures. The drawer may still be opened and closed programmatically (`openDrawer`/`closeDrawer`).

| Type                                             | Required |
| ------------------------------------------------ | -------- |
| enum('unlocked', 'locked-closed', 'locked-open') | No       |

***

### `drawerPosition`[​](#drawerposition "Direct link to drawerposition")

Specifies the side of the screen from which the drawer will slide in. By default it is set to `left`.

| Type                  | Required |
| --------------------- | -------- |
| enum('left', 'right') | No       |

***

### `drawerWidth`[​](#drawerwidth "Direct link to drawerwidth")

Specifies the width of the drawer, more precisely the width of the view that be pulled in from the edge of the window.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `keyboardDismissMode`[​](#keyboarddismissmode "Direct link to keyboarddismissmode")

Determines whether the keyboard gets dismissed in response to a drag.

* 'none' (the default), drags do not dismiss the keyboard.
* 'on-drag', the keyboard is dismissed when a drag begins.

| Type                    | Required |
| ----------------------- | -------- |
| enum('none', 'on-drag') | No       |

***

### `onDrawerClose`[​](#ondrawerclose "Direct link to ondrawerclose")

Function called whenever the navigation view has been closed.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `onDrawerOpen`[​](#ondraweropen "Direct link to ondraweropen")

Function called whenever the navigation view has been opened.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `onDrawerSlide`[​](#ondrawerslide "Direct link to ondrawerslide")

Function called whenever there is an interaction with the navigation view.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `onDrawerStateChanged`[​](#ondrawerstatechanged "Direct link to ondrawerstatechanged")

Function called when the drawer state has changed. The drawer can be in 3 states:

* idle, meaning there is no interaction with the navigation view happening at the time
* dragging, meaning there is currently an interaction with the navigation view
* settling, meaning that there was an interaction with the navigation view, and the navigation view is now finishing its closing or opening animation

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `renderNavigationView`[​](#rendernavigationview "Direct link to rendernavigationview")

The navigation view that will be rendered to the side of the screen and can be pulled in.

| Type     | Required |
| -------- | -------- |
| function | Yes      |

***

### `statusBarBackgroundColor`[​](#statusbarbackgroundcolor "Direct link to statusbarbackgroundcolor")

Make the drawer take the entire screen and draw the background of the status bar to allow it to open over the status bar. It will only have an effect on API 21+.

| Type                  | Required |
| --------------------- | -------- |
| [color](/docs/colors) | No       |

## Methods[​](#methods "Direct link to Methods")

### `closeDrawer()`[​](#closedrawer "Direct link to closedrawer")

React TSX

```
closeDrawer();
```

Closes the drawer.

***

### `openDrawer()`[​](#opendrawer "Direct link to opendrawer")

React TSX

```
openDrawer();
```

----
url: https://reactnative.dev/docs/the-new-architecture/create-module-library
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
npx create-react-native-library@latest <Name of Your Library>
```

```
  "codegenConfig": {

    "name": "RN<your module name>Spec",

    "type": "all",

    "jsSrcsDir": "src",

    "outputDir": {

      "ios": "ios/generated",

      "android": "android/generated"

    },

    "android": {

      "javaPackageName": "com.<name-of-the-module>"

    }

  },
```

Finally, the library contains already all the infrastructure to let the library be linked with iOS and Android.

### 2. Copy the Code over from Your App[​](#2-copy-the-code-over-from-your-app "Direct link to 2. Copy the Code over from Your App")

The rest of the guide assumes that you have a local Turbo Native Module in your app, created following the guidelines shown in the other guides in the website: platform specific Turbo Native Modules, or [cross-platform Turbo Native Modules](/docs/the-new-architecture/pure-cxx-modules). But it works also for Components and legacy architecture modules and components. You'll have to adapt the files you need to copy and update.

1. **\[Not required for legacy architecture modules and components]** Move the code you have in the `specs` folder in your app into the `src` folder created by the `create-react-native-library` folder.
2. Update the `index.ts` file to properly export the Turbo Native Module spec so that it is accessible from the library. For example:

TypeScript

```
import NativeSampleModule from './NativeSampleModule';



export default NativeSampleModule;
```

```
Development

├── App

└── Library
```

You can use the library created with `create-react-native-library` also in this case.

1. add you library to your app by navigating into the `App` folder and running `yarn add ../Library`.
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:

React TSX

```
import NativeSampleModule from '../Library/src/index';
```

If you run your app right now, Metro would not find the JS files that it needs to serve to the app. That's because metro will be running starting from the `App` folder and it would not have access to the JS files located in the `Library` folder. To fix this, let's update the `metro.config.js` file as it follows

Diff

```
const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');



/**

 * Metro configuration

 * https://reactnative.dev/docs/metro

 *

 * @type {import('metro-config').MetroConfig}

 */

+ const path = require('path');



- const config = {}

+ const config = {

+  // Make Metro able to resolve required external dependencies

+  watchFolders: [

+    path.resolve(__dirname, '../Library'),

+  ],

+  resolver: {

+    extraNodeModules: {

+      'react-native': path.resolve(__dirname, 'node_modules/react-native'),

+    },

+  },

+};



module.exports = mergeConfig(getDefaultConfig(__dirname), config);
```

```
npm view <package.name>
```

where `package.name` is the `name` you set up in the `package.json` file during the initialization of the library.

Now, you can install the library in your application by running:

```
yarn add <package.name>
```

----
url: https://reactnative.dev/docs/inputaccessoryview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

A component which enables customization of the keyboard input accessory view on iOS. The input accessory view is displayed above the keyboard whenever a `TextInput` has focus. This component can be used to create custom toolbars.

To use this component wrap your custom toolbar with the InputAccessoryView component, and set a `nativeID`. Then, pass that `nativeID` as the `inputAccessoryViewID` of whatever `TextInput` you desire. A basic example:

This component can also be used to create sticky text inputs (text inputs which are anchored to the top of the keyboard). To do this, wrap a `TextInput` with the `InputAccessoryView` component, and don't set a `nativeID`. For an example, look at [InputAccessoryViewExample.js](https://github.com/react/react-native/blob/main/packages/rn-tester/js/examples/InputAccessoryView/InputAccessoryViewExample.js).

***

# Reference

## Props[​](#props "Direct link to Props")

### `backgroundColor`[​](#backgroundcolor "Direct link to backgroundcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

An ID which is used to associate this `InputAccessoryView` to specified TextInput(s).

| Type   |
| ------ |
| string |

***

### `style`[​](#style "Direct link to style")

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

----
url: https://reactnative.dev/docs/next/communication-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/communication-android)** (0.87).

Version: Next

In [Integrating with Existing Apps guide](/docs/next/integration-with-existing-apps) and [Native UI Components guide](/docs/next/legacy/native-components-android) we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.

```
public class MainActivity extends ReactActivity {

  @Override

  protected ReactActivityDelegate createReactActivityDelegate() {

    return new ReactActivityDelegate(this, getMainComponentName()) {

      @Override

      protected Bundle getLaunchOptions() {

        Bundle initialProperties = new Bundle();

        ArrayList<String> imageList = new ArrayList<String>(Arrays.asList(

                "https://dummyimage.com/600x400/ffffff/000000.png",

                "https://dummyimage.com/600x400/000000/ffffff.png"

        ));

        initialProperties.putStringArrayList("images", imageList);

        return initialProperties;

      }

    };

  }

}
```

Kotlin

```
class MainActivity : ReactActivity() {

    override fun createReactActivityDelegate(): ReactActivityDelegate {

        return object : ReactActivityDelegate(this, mainComponentName) {

            override fun getLaunchOptions(): Bundle {

                val imageList = arrayListOf("https://dummyimage.com/600x400/ffffff/000000.png", "https://dummyimage.com/600x400/000000/ffffff.png")

                val initialProperties = Bundle().apply { putStringArrayList("images", imageList) }

                return initialProperties

            }

        }

    }

}
```

React TSX

```
import {View, Image} from 'react-native';



export default class ImageBrowserApp extends React.Component {

  renderImage(imgURI) {

    return <Image source={{uri: imgURI}} />;

  }

  render() {

    return <View>{this.props.images.map(this.renderImage)}</View>;

  }

}
```

`ReactRootView` provides a read-write property `appProperties`. After `appProperties` is set, the React Native app is re-rendered with new properties. The update is only performed when the new updated properties differ from the previous ones.

* Java
* Kotlin

Java

```
Bundle updatedProps = mReactRootView.getAppProperties();

ArrayList<String> imageList = new ArrayList<String>(Arrays.asList(

        "https://dummyimage.com/600x400/ff0000/000000.png",

        "https://dummyimage.com/600x400/ffffff/ff0000.png"

));

updatedProps.putStringArrayList("images", imageList);



mReactRootView.setAppProperties(updatedProps);
```

Kotlin

```
var updatedProps: Bundle = reactRootView.getAppProperties()

var imageList = arrayListOf("https://dummyimage.com/600x400/ff0000/000000.png", "https://dummyimage.com/600x400/ffffff/ff0000.png")
```

It is fine to update properties anytime. However, updates have to be performed on the main thread. You use the getter on any thread.

There is no way to update only a few properties at a time. We suggest that you build it into your own wrapper instead.

info

Currently, JS function `componentWillUpdateProps` of the top level RN component will not be called after a prop update. However, you can access the new props in `componentDidMount` function.

### Passing properties from React Native to native[​](#passing-properties-from-react-native-to-native "Direct link to Passing properties from React Native to native")

The problem exposing properties of native components is covered in detail in [this article](/docs/next/legacy/native-components-android#3-expose-view-property-setters-using-reactprop-or-reactpropgroup-annotation). In short, properties that are to be reflected in JavaScript needs to be exposed as setter method annotated with `@ReactProp`, then use them in React Native as if the component was an ordinary React Native component.

### Limits of properties[​](#limits-of-properties "Direct link to Limits of properties")

The main drawback of cross-language properties is that they do not support callbacks, which would allow us to handle bottom-up data bindings. Imagine you have a small RN view that you want to be removed from the native parent view as a result of a JS action. There is no way to do that with props, as the information would need to go bottom-up.

Although we have a flavor of cross-language callbacks ([described here](/docs/next/legacy/native-modules-android#callbacks)), these callbacks are not always the thing we need. The main problem is that they are not intended to be passed as properties. Rather, this mechanism allows us to trigger a native action from JS, and handle the result of that action in JS.

## Other ways of cross-language interaction (events and native modules)[​](#other-ways-of-cross-language-interaction-events-and-native-modules "Direct link to Other ways of cross-language interaction (events and native modules)")

As stated in the previous chapter, using properties comes with some limitations. Sometimes properties are not enough to drive the logic of our app and we need a solution that gives more flexibility. This chapter covers other communication techniques available in React Native. They can be used for internal communication (between JS and native layers in RN) as well as for external communication (between RN and the 'pure native' part of your app).

React Native enables you to perform cross-language function calls. You can execute custom native code from JS and vice versa. Unfortunately, depending on the side we are working on, we achieve the same goal in different ways. For native - we use events mechanism to schedule an execution of a handler function in JS, while for React Native we directly call methods exported by native modules.

### Calling React Native functions from native (events)[​](#calling-react-native-functions-from-native-events "Direct link to Calling React Native functions from native (events)")

Events are described in detail in [this article](/docs/next/legacy/native-components-android#events). Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread.

Events are powerful, because they allow us to change React Native components without needing a reference to them. However, there are some pitfalls that you can fall into while using them:

* As events can be sent from anywhere, they can introduce spaghetti-style dependencies into your project.
* Events share namespace, which means that you may encounter some name collisions. Collisions will not be detected statically, which makes them hard to debug.
* If you use several instances of the same React Native component and you want to distinguish them from the perspective of your event, you'll likely need to introduce identifiers and pass them along with events (you can use the native view's `reactTag` as an identifier).

### Calling native functions from React Native (native modules)[​](#calling-native-functions-from-react-native-native-modules "Direct link to Calling native functions from React Native (native modules)")

Native modules are Java/Kotlin classes that are available in JS. Typically one instance of each module is created per JS bridge. They can export arbitrary functions and constants to React Native. They have been covered in detail in [this article](/docs/next/legacy/native-modules-android).

----
url: https://reactnative.dev/docs/dynamiccolorios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The `DynamicColorIOS` function is a platform color type specific to iOS.

React TSX

```
DynamicColorIOS({

  light: color,

  dark: color,

  highContrastLight: color, // (optional) will fallback to "light" if not provided

  highContrastDark: color, // (optional) will fallback to "dark" if not provided

});
```

```
import {DynamicColorIOS} from 'react-native';



const customDynamicTextColor = DynamicColorIOS({

  dark: 'lightskyblue',

  light: 'midnightblue',

});



const customContrastDynamicTextColor = DynamicColorIOS({

  dark: 'darkgray',

  light: 'lightgray',

  highContrastDark: 'black',

  highContrastLight: 'white',

});
```

* [Example](#example)

----
url: https://reactnative.dev/docs/next/checkbox
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/checkbox)** (0.87).

Version: Next

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=checkbox) instead.

----
url: https://reactnative.dev/docs/next/fast-refresh
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/fast-refresh)** (0.87).

Version: Next

Fast Refresh is a React Native feature that allows you to get near-instant feedback for changes in your React components. Fast Refresh is enabled by default, and you can toggle "Enable Fast Refresh" in the [React Native Dev Menu](/docs/next/debugging#opening-the-dev-menu). With Fast Refresh enabled, most edits should be visible within a second or two.

----
url: https://reactnative.dev/docs/global-Request
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Request) for more information.

The global `Request` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/imagepickerios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=image+picker) instead.

----
url: https://reactnative.dev/docs/transforms
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Transforms are style properties that will help you modify the appearance and position of your components using 2D or 3D transformations. However, once you apply transforms, the layouts remain the same around the transformed component hence it might overlap with the nearby components. You can apply margin to the transformed component, the nearby components or padding to the container to prevent such overlaps.

## Example[​](#example "Direct link to Example")

***

# Reference

## Transform[​](#transform "Direct link to Transform")

`transform` accepts an array of transformation objects or space-separated string values. Each object specifies the property that will be transformed as the key, and the value to use in the transformation. Objects should not be combined. Use a single key/value pair per object.

The rotate transformations require a string so that the transform may be expressed in degrees (deg) or radians (rad). For example:

JavaScript

```
{

  transform: [{rotateX: '45deg'}, {rotateZ: '0.785398rad'}],

}
```

The same could also be achieved using a space-separated string:

JavaScript

```
{

  transform: 'rotateX(45deg) rotateZ(0.785398rad)',

}
```

The skew transformations require a string so that the transform may be expressed in degrees (deg). For example:

JavaScript

```
{

  transform: [{skewX: '45deg'}],

}
```

The translate transformations (`translateX` and `translateY`) accept numbers (points) or percentage strings (e.g. `'50%'`, `'100%'`). When using percentages, the offset is relative to the element's width (for `translateX`) or height (for `translateY`). Percentage translation is supported on the [New Architecture](/architecture/landing-page). For example:

JavaScript

```
{

  transform: [{translateX: '50%'}, {translateY: 100}],

}
```

### Matrix Transform[​](#matrix-transform "Direct link to Matrix Transform")

The `matrix` transform accepts a 4x4 transformation matrix as an array of 16 numbers. This allows you to apply complex transformations that combine translation, rotation, scaling, and skewing in a single operation.

The matrix is specified in column-major order:

JavaScript

```
{

  transform: [

    {

      matrix: [

        scaleX,

        skewY,

        0,

        0,

        skewX,

        scaleY,

        0,

        0,

        0,

        0,

        1,

        0,

        translateX,

        translateY,

        0,

        1,

      ],

    },

  ];

}
```

For example, to apply a combination of scale and skew:

JavaScript

```
{

  transform: [

    {

      matrix: [

        1, 0.5, 0, 0, 0.5, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,

      ],

    },

  ];

}
```

note

Matrix transforms are useful when you need to apply pre-calculated transformation matrices, such as those from animation libraries or when building UI editor applications. For basic transformations, it's recommended to use the individual transform properties (scale, rotate, translate, etc.) as they are more readable.

| Type                                                                                                                                                                                                                                                                                                                              | Required |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| array of objects: `{matrix: number[]}`, `{perspective: number}`, `{rotate: string}`, `{rotateX: string}`, `{rotateY: string}`, `{rotateZ: string}`, `{scale: number}`, `{scaleX: number}`, `{scaleY: number}`, `{translateX: number \| string}`, `{translateY: number \| string}`, `{skewX: string}`, `{skewY: string}` or string | No       |

***

### 🗑️ `decomposedMatrix`, `rotation`, `scaleX`, `scaleY`, `transformMatrix`, `translateX`, `translateY`[​](#️-decomposedmatrix-rotation-scalex-scaley-transformmatrix-translatex-translatey "Direct link to ️-decomposedmatrix-rotation-scalex-scaley-transformmatrix-translatex-translatey")

Deprecated

Use the [`transform`](/docs/transforms#transform) prop instead.

```
{

  transformOrigin: '20px',

  transformOrigin: 'bottom',

}
```

#### Two-value syntax:[​](#two-value-syntax "Direct link to Two-value syntax:")

* First value (x-offset) must be a `px`, a `percentage`, or one of the keywords `left`, `center`, and `right`.
* The second value (y-offset) must be a `px`, a `percentage`, or one of the keywords `top`, `center`, and `bottom`.

JavaScript

```
{

  transformOrigin: '10px 2px',

  transformOrigin: 'left top',

  transformOrigin: 'top right',

}
```

#### Three-value syntax:[​](#three-value-syntax "Direct link to Three-value syntax:")

* The first two values are the same as for the two-value syntax.
* The third value (z-offset) must be a `px`. It always represents the Z offset.

JavaScript

```
{

  transformOrigin: '2px 30% 10px',

  transformOrigin: 'right bottom 20px',

}
```

#### Array syntax[​](#array-syntax "Direct link to Array syntax")

`transformOrigin` also supports an array syntax. It makes it convenient to use it with Animated APIs. It also avoids string parsing, so should be more efficient.

JavaScript

```
{

  // Using numeric values

  transformOrigin: [10, 30, 40],

  // Mixing numeric and percentage values

  transformOrigin: [10, '20%', 0],

}
```

----
url: https://reactnative.dev/docs/image-style-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

| Type                          | Default     |
| ----------------------------- | ----------- |
| enum(`'visible'`, `'hidden'`) | `'visible'` |

***

### `backgroundColor`[​](#backgroundcolor "Direct link to backgroundcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderBottomLeftRadius`[​](#borderbottomleftradius "Direct link to borderbottomleftradius")

| Type   |
| ------ |
| number |

***

### `borderBottomRightRadius`[​](#borderbottomrightradius "Direct link to borderbottomrightradius")

| Type   |
| ------ |
| number |

***

### `borderColor`[​](#bordercolor "Direct link to bordercolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderRadius`[​](#borderradius "Direct link to borderradius")

| Type   |
| ------ |
| number |

***

### `borderTopLeftRadius`[​](#bordertopleftradius "Direct link to bordertopleftradius")

| Type   |
| ------ |
| number |

***

### `borderTopRightRadius`[​](#bordertoprightradius "Direct link to bordertoprightradius")

| Type   |
| ------ |
| number |

***

### `borderWidth`[​](#borderwidth "Direct link to borderwidth")

| Type   |
| ------ |
| number |

***

### `opacity`[​](#opacity "Direct link to opacity")

Set an opacity value for the image. The number should be in the range from `0.0` to `1.0`.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

### `overflow`[​](#overflow "Direct link to overflow")

| Type                          | Default     |
| ----------------------------- | ----------- |
| enum(`'visible'`, `'hidden'`) | `'visible'` |

***

### `overlayColor`Android[​](#overlaycolor-android "Direct link to overlaycolor-android")

When the image has rounded corners, specifying an overlayColor will cause the remaining space in the corners to be filled with a solid color. This is useful in cases which are not supported by the Android implementation of rounded corners:

* Certain resize modes, such as `'contain'`
* Animated GIFs

A typical way to use this prop is with images displayed on a solid background and setting the `overlayColor` to the same color as the background.

For details of how this works under the hood, see [Fresco documentation](https://frescolib.org/docs/rounded-corners-and-circles.html).

| Type   |
| ------ |
| string |

***

| Type                                                              | Default   |
| ----------------------------------------------------------------- | --------- |
| enum(`'cover'`, `'contain'`, `'stretch'`, `'repeat'`, `'center'`) | `'cover'` |

***

### `objectFit`[​](#objectfit "Direct link to objectfit")

Determines how to resize the image when the frame doesn't match the raw image dimensions.

| Type                                                   | Default   |
| ------------------------------------------------------ | --------- |
| enum(`'cover'`, `'contain'`, `'fill'`, `'scale-down'`) | `'cover'` |

***

### `tintColor`[​](#tintcolor "Direct link to tintcolor")

Changes the color of all the non-transparent pixels to the tintColor.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

    [Android](#overlaycolor-android)
  * [`resizeMode`](#resizemode)
  * [`objectFit`](#objectfit)
  * [`tintColor`](#tintcolor)

----
url: https://reactnative.dev/docs/next/global-PerformanceObserver
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-PerformanceObserver)** (0.87).

Version: Next

The global [`PerformanceObserver`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver) class, as defined in Web specifications.

## Example[​](#example "Direct link to Example")

TypeScript

```
const observer = new PerformanceObserver(

  (list, observer, options) => {

    for (const entry of list.getEntries()) {

      console.log(

        'Received entry with type',

        entry.entryType,

        'and name',

        entry.name,

        'that started at',

        entry.startTime,

        'and took',

        entry.duration,

        'ms',

      );

    }

  },

);



observer.observe({entryTypes: ['mark', 'measure']});
```

***

----
url: https://reactnative.dev/docs/next/global-PerformanceMeasure
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-PerformanceMeasure)** (0.87).

Version: Next

The global [`PerformanceMeasure`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMeasure) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-Blob
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Blob) for more information.

The global `Blob` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/navigation
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator.

This guide covers the various navigation components available in React Native. If you are getting started with navigation, you will probably want to use [React Navigation](/docs/navigation#react-navigation). React Navigation provides a straightforward navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both Android and iOS.

If you're integrating React Native into an app that already manages navigation natively, or looking for an alternative to React Navigation, the following library provides native navigation on both platforms: [react-native-navigation](https://github.com/wix/react-native-navigation).

## React Navigation[​](#react-navigation "Direct link to React Navigation")

The community solution to navigation is a standalone library that allows developers to set up the screens of an app with a few lines of code.

### Starter template[​](#starter-template "Direct link to Starter template")

If you're starting a new project, you can use the React Navigation template to quickly set up a new project with [Expo](https://expo.dev/):

```
npx create-expo-app@latest --template react-navigation/template
```

See the project's `README.md` for more information on how to get started.

### Installation and setup[​](#installation-and-setup "Direct link to Installation and setup")

First, you need to install them in your project:

```
npm install @react-navigation/native @react-navigation/native-stack
```

Next, install the required peer dependencies. You need to run different commands depending on whether your project is an Expo managed project or a bare React Native project.

* If you have an Expo managed project, install the dependencies with `expo`:

  ```
  npx expo install react-native-screens react-native-safe-area-context
  ```

* If you have a bare React Native project, install the dependencies with `npm`:

  ```
  npm install react-native-screens react-native-safe-area-context
  ```

  For iOS with bare React Native project, make sure you have [CocoaPods](https://cocoapods.org/) installed. Then install the pods to complete the installation:

  ```
  cd ios

  pod install

  cd ..
  ```

Once you've installed and configured the dependencies, you can move on to setting up your project to use React Navigation.

When using React Navigation, you configure [navigators](https://reactnavigation.org/docs/glossary-of-terms#navigator) in your app. Navigators handle the transition between screens in your app and provide UI such as header, tab bar etc.

Now you are ready to build and run your app on the device/simulator.

### Usage[​](#usage "Direct link to Usage")

Now you can create an app with a home screen and a profile screen:

App.tsx

```
import {createStaticNavigation} from '@react-navigation/native';

import {createNativeStackNavigator} from '@react-navigation/native-stack';



const RootStack = createNativeStackNavigator({

  screens: {

    Home: {

      screen: HomeScreen,

      options: {title: 'Welcome'},

    },

    Profile: {

      screen: ProfileScreen,

    },

  },

});



const Navigation = createStaticNavigation(RootStack);



export default function App() {

  return <Navigation />;

}
```

In this example, `RootStack` is a navigator with 2 screens (`Home` and `Profile`), defined in the `screens` property in `createNativeStackNavigator`. Similarly, you can define as many screens as you like.

You can specify options such as the screen title for each screen in the `options` property of each screen. Each screen definition also needs a `screen` property that is a React component or another navigator.

Inside each screen component, you can use the `useNavigation` hook to get the `navigation` object, which has various methods to link to other screens. For example, you can use `navigation.navigate` to go to the `Profile` screen:

HomeScreen.tsx

```
import {useNavigation} from '@react-navigation/native';



export default function HomeScreen() {

  const navigation = useNavigation();



  return (

    <Button

      title="Go to Jane's profile"

      onPress={() =>

        navigation.navigate('Profile', {name: 'Jane'})

      }

    />

  );

}
```

ProfileScreen.tsx

```
export default function ProfileScreen({route}) {

  return <Text>This is {route.params.name}'s profile</Text>;

}
```

----
url: https://reactnative.dev/docs/turbo-native-modules-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Now it's time to write some iOS platform code to make sure `localStorage` survives after the application is closed.

## Prepare your Xcode Project[​](#prepare-your-xcode-project "Direct link to Prepare your Xcode Project")

We need to prepare your iOS project using Xcode. After completing these **6 steps** you'll have `RCTNativeLocalStorage` that implements the generated `NativeLocalStorageSpec` interface.

1. Open the CocoaPods generated Xcode Workspace:

```
cd ios

open TurboModuleExample.xcworkspace
```

```
//  RCTNativeLocalStorage.h

//  TurboModuleExample



#import <Foundation/Foundation.h>

#import <NativeLocalStorageSpec/NativeLocalStorageSpec.h>



NS_ASSUME_NONNULL_BEGIN



@interface RCTNativeLocalStorage : NSObject

@interface RCTNativeLocalStorage : NSObject <NativeLocalStorageSpec>



@end
```

Then update our implementation to use `NSUserDefaults` with a custom [suite name](https://developer.apple.com/documentation/foundation/nsuserdefaults/1409957-initwithsuitename).

NativeLocalStorage/RCTNativeLocalStorage.mm

```
//  RCTNativeLocalStorage.m

//  TurboModuleExample



#import "RCTNativeLocalStorage.h"



static NSString *const RCTNativeLocalStorageKey = @"local-storage";



@interface RCTNativeLocalStorage()

@property (strong, nonatomic) NSUserDefaults *localStorage;

@end



@implementation RCTNativeLocalStorage



- (id) init {

  if (self = [super init]) {

    _localStorage = [[NSUserDefaults alloc] initWithSuiteName:RCTNativeLocalStorageKey];

  }

  return self;

}



- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {

  return std::make_shared<facebook::react::NativeLocalStorageSpecJSI>(params);

}



- (NSString * _Nullable)getItem:(NSString *)key {

  return [self.localStorage stringForKey:key];

}



- (void)setItem:(NSString *)value

          key:(NSString *)key {

  [self.localStorage setObject:value forKey:key];

}



- (void)removeItem:(NSString *)key {

  [self.localStorage removeObjectForKey:key];

}



- (void)clear {

  NSDictionary *keys = [self.localStorage dictionaryRepresentation];

  for (NSString *key in keys) {

    [self removeItem:key];

  }

}



+ (NSString *)moduleName

{

  return @"NativeLocalStorage";

}



@end
```

Important things to note:

* You can use Xcode to jump to the Codegen `@protocol NativeLocalStorageSpec`. You can also use Xcode to generate stubs for you.

## Register the Native Module in your app[​](#register-the-native-module-in-your-app "Direct link to Register the Native Module in your app")

The last step consist in updating the `package.json` to tell React Native about the link between the JS specs of the Native Module and the concrete implementation of those specs in native code.

Modify the `package.json` as it follows:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "NativeLocalStorageSpec",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.nativelocalstorage"

     },

     "ios": {

        "modulesProvider": {

          "NativeLocalStorage": "RCTNativeLocalStorage"

        }

     }

   },



   "dependencies": {
```

At this point, you need to re-install the pods to make sure that codegen runs again to generate the new files:

```
# from the ios folder

bundle exec pod install

open TurboModuleExample.xcworkspace
```

If you now build your application from Xcode, you should be able to build successfully.

## Build and run your code on a Simulator[​](#build-and-run-your-code-on-a-simulator "Direct link to Build and run your code on a Simulator")

* npm
* Yarn

```
npm run ios
```

```
yarn run ios
```

* [Prepare your Xcode Project](#prepare-your-xcode-project)
* [Implement localStorage with NSUserDefaults](#implement-localstorage-with-nsuserdefaults)
* [Register the Native Module in your app](#register-the-native-module-in-your-app)
* [Build and run your code on a Simulator](#build-and-run-your-code-on-a-simulator)

----
url: https://reactnative.dev/docs/next/legacy/local-library-setup
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/legacy/local-library-setup)** (0.87).

Version: Next

A local library is a library containing views or modules that's local to your app and not published to a registry. This is different from the traditional setup for view and modules in the sense that a local library is decoupled from your app's native code.

The local library is created outside of the `android/` and `ios/` folders and makes use of autolinking to integrate with your app. The structure with a local library may look like this:

Plaintext

```
MyApp

├── node_modules

├── modules <-- folder for your local libraries

│ └── awesome-module <-- your local library

├── android

├── ios

├── src

├── index.js

└── package.json
```

Since a local library's code exists outside of `android/` and `ios/` folders, it makes it easier to upgrade React Native versions in the future, copy to other projects etc.

To create local library we will use [create-react-native-library](https://callstack.github.io/react-native-builder-bob/create). This tool contains all the necessary templates.

### Getting Started[​](#getting-started "Direct link to Getting Started")

Inside your React Native application's root folder, run the following command:

```
npx create-react-native-library@latest awesome-module
```

Where `awesome-module` is the name you would like for the new module. After going through the prompts, you will have a new folder called `modules` in your project's root directory which contains the new module.

### Linking[​](#linking "Direct link to Linking")

By default, the generated library is automatically linked to the project using `link:` protocol when using Yarn and `file:` when using npm:

* npm
* Yarn

JSON

```
"dependencies": {

  "awesome-module": "file:./modules/awesome-module"

}
```

JSON

```
"dependencies": {

  "awesome-module": "link:./modules/awesome-module"

}
```

This creates a symlink to the library under `node_modules` which makes autolinking work.

### Installing dependencies[​](#installing-dependencies "Direct link to Installing dependencies")

To link the module you need to install dependencies:

* npm
* Yarn

```
npm install
```

```
yarn install
```

### Using module inside your app[​](#using-module-inside-your-app "Direct link to Using module inside your app")

To use the module inside your app, you can import it by its name:

JavaScript

```
import {multiply} from 'awesome-module';
```

* [Getting Started](#getting-started)
* [Linking](#linking)
* [Installing dependencies](#installing-dependencies)
* [Using module inside your app](#using-module-inside-your-app)

----
url: https://reactnative.dev/docs/next/react-native-gradle-plugin
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/react-native-gradle-plugin)** (0.87).

Version: Next

```
apply plugin: "com.facebook.react"



/**

 * This is the configuration block to customize your React Native Android app.

 * By default you don't need to apply any configuration, just uncomment the lines you need.

 */

react {

  // Custom configuration goes here.

}
```

Each configuration key is described below:

### `root`[​](#root "Direct link to root")

This is the root folder of your React Native project, i.e. where the `package.json` file lives. Default is `..`. You can customize it as follows:

Groovy

```
root = file("../")
```

### `reactNativeDir`[​](#reactnativedir "Direct link to reactnativedir")

This is the folder where the `react-native` package lives. Default is `../node_modules/react-native`. If you're in a monorepo or using a different package manager, you can use adjust `reactNativeDir` to your setup.

You can customize it as follows:

Groovy

```
reactNativeDir = file("../node_modules/react-native")
```

### `codegenDir`[​](#codegendir "Direct link to codegendir")

This is the folder where the `react-native-codegen` package lives. Default is `../node_modules/react-native-codegen`. If you're in a monorepo or using a different package manager, you can adjust `codegenDir` to your setup.

You can customize it as follows:

Groovy

```
codegenDir = file("../node_modules/@react-native/codegen")
```

### `cliFile`[​](#clifile "Direct link to clifile")

This is the entrypoint file for the React Native CLI. Default is `../node_modules/react-native/cli.js`. The entrypoint file is needed as the plugin needs to invoke the CLI for bundling and creating your app.

If you're in a monorepo or using a different package manager, you can adjust `cliFile` to your setup. You can customize it as follows:

Groovy

```
cliFile = file("../node_modules/react-native/cli.js")
```

### `debuggableVariants`[​](#debuggablevariants "Direct link to debuggablevariants")

This is the list of variants that are debuggable (see [using variants](#using-flavors--build-variants) for more context on variants).

By default the plugin is considering as `debuggableVariants` only `debug`, while `release` is not. If you have other variants (like `staging`, `lite`, etc.) you'll need to adjust this accordingly.

Variants that are listed as `debuggableVariants` will not come with a shipped bundle, so you'll need Metro to run them.

You can customize it as follows:

Groovy

```
debuggableVariants = ["liteDebug", "prodDebug"]
```

### `nodeExecutableAndArgs`[​](#nodeexecutableandargs "Direct link to nodeexecutableandargs")

This is the list of node command and arguments that should be invoked for all the scripts. By default is `[node]` but can be customized to add extra flags as follows:

Groovy

```
nodeExecutableAndArgs = ["node"]
```

### `bundleCommand`[​](#bundlecommand "Direct link to bundlecommand")

This is the name of the `bundle` command to be invoked when creating the bundle for your app. That's useful if you're using [RAM Bundles](https://reactnative.dev/docs/0.74/ram-bundles-inline-requires). By default is `bundle` but can be customized to add extra flags as follows:

Groovy

```
bundleCommand = "ram-bundle"
```

### `bundleConfig`[​](#bundleconfig "Direct link to bundleconfig")

This is the path to a configuration file that will be passed to `bundle --config <file>` if provided. Default is empty (no config file will be probided). More information on bundling config files can be found [on the CLI documentation](https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle). Can be customized as follow:

Groovy

```
bundleConfig = file(../rn-cli.config.js)
```

### `bundleAssetName`[​](#bundleassetname "Direct link to bundleassetname")

This is the name of the bundle file that should be generated. Default is `index.android.bundle`. Can be customized as follow:

Groovy

```
bundleAssetName = "MyApplication.android.bundle"
```

### `entryFile`[​](#entryfile "Direct link to entryfile")

The entry file used for bundle generation. The default is to search for `index.android.js` or `index.js`. Can be customized as follow:

Groovy

```
entryFile = file("../js/MyApplication.android.js")
```

### `extraPackagerArgs`[​](#extrapackagerargs "Direct link to extrapackagerargs")

A list of extra flags that will be passed to the `bundle` command. The list of available flags is in [the CLI documentation](https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle). Default is empty. Can be customized as follows:

Groovy

```
extraPackagerArgs = []
```

### `hermesCommand`[​](#hermescommand "Direct link to hermescommand")

The path to the `hermesc` command (the Hermes Compiler). React Native comes with a version of the Hermes compiler bundled with it, so you generally won't be needing to customize this. The plugin will use the correct compiler for your system by default.

### `hermesFlags`[​](#hermesflags "Direct link to hermesflags")

The list of flags to pass to `hermesc`. By default is `["-O", "-output-source-map"]`. You can customize it as follows

Groovy

```
hermesFlags = ["-O", "-output-source-map"]
```

```
apply plugin: "com.facebook.react"



react {

+ debuggableVariants = ["fullStaging", "fullDebug"]

}
```

----
url: https://reactnative.dev/docs/animatedvalue
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Standard value for driving animations. One `Animated.Value` can drive multiple properties in a synchronized fashion, but can only be driven by one mechanism at a time. Using a new mechanism (e.g. starting a new animation, or calling `setValue`) will stop any previous ones.

Typically initialized with `useAnimatedValue(0);` or `new Animated.Value(0);` in class components.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `setValue()`[​](#setvalue "Direct link to setvalue")

React TSX

```
setValue(value: number);
```

Directly set the value. This will stop any animations running on the value and update all the bound properties.

**Parameters:**

| Name  | Type   | Required | Description |
| ----- | ------ | -------- | ----------- |
| value | number | Yes      | Value       |

***

### `setOffset()`[​](#setoffset "Direct link to setoffset")

React TSX

```
setOffset(offset: number);
```

Sets an offset that is applied on top of whatever value is set, whether via `setValue`, an animation, or `Animated.event`. Useful for compensating things like the start of a pan gesture.

**Parameters:**

| Name   | Type   | Required | Description  |
| ------ | ------ | -------- | ------------ |
| offset | number | Yes      | Offset value |

***

### `flattenOffset()`[​](#flattenoffset "Direct link to flattenoffset")

React TSX

```
flattenOffset();
```

Merges the offset value into the base value and resets the offset to zero. The final output of the value is unchanged.

***

### `extractOffset()`[​](#extractoffset "Direct link to extractoffset")

React TSX

```
extractOffset();
```

Sets the offset value to the base value, and resets the base value to zero. The final output of the value is unchanged.

***

### `addListener()`[​](#addlistener "Direct link to addlistener")

React TSX

```
addListener(callback: (state: {value: number}) => void): string;
```

Adds an asynchronous listener to the value so you can observe updates from animations. This is useful because there is no way to synchronously read the value because it might be driven natively.

Returns a string that serves as an identifier for the listener.

**Parameters:**

| Name     | Type     | Required | Description                                                                                 |
| -------- | -------- | -------- | ------------------------------------------------------------------------------------------- |
| callback | function | Yes      | The callback function which will receive an object with a `value` key set to the new value. |

***

### `removeListener()`[​](#removelistener "Direct link to removelistener")

React TSX

```
removeListener(id: string);
```

Unregister a listener. The `id` param shall match the identifier previously returned by `addListener()`.

**Parameters:**

| Name | Type   | Required | Description                        |
| ---- | ------ | -------- | ---------------------------------- |
| id   | string | Yes      | Id for the listener being removed. |

***

### `removeAllListeners()`[​](#removealllisteners "Direct link to removealllisteners")

React TSX

```
removeAllListeners();
```

Remove all registered listeners.

***

### `stopAnimation()`[​](#stopanimation "Direct link to stopanimation")

React TSX

```
stopAnimation(callback?: (value: number) => void);
```

Stops any running animation or tracking. `callback` is invoked with the final value after stopping the animation, which is useful for updating state to match the animation position with layout.

**Parameters:**

| Name     | Type     | Required | Description                                   |
| -------- | -------- | -------- | --------------------------------------------- |
| callback | function | No       | A function that will receive the final value. |

***

### `resetAnimation()`[​](#resetanimation "Direct link to resetanimation")

React TSX

```
resetAnimation(callback?: (value: number) => void);
```

Stops any animation and resets the value to its original.

**Parameters:**

| Name     | Type     | Required | Description                                      |
| -------- | -------- | -------- | ------------------------------------------------ |
| callback | function | No       | A function that will receive the original value. |

***

### `interpolate()`[​](#interpolate "Direct link to interpolate")

React TSX

```
interpolate(config: InterpolationConfigType);
```

Interpolates the value before updating the property, e.g. mapping 0-1 to 0-10.

See `AnimatedInterpolation.js`

**Parameters:**

| Name   | Type   | Required | Description |
| ------ | ------ | -------- | ----------- |
| config | object | Yes      | See below.  |

***

### `animate()`[​](#animate "Direct link to animate")

React TSX

```
animate(animation, callback);
```

Typically only used internally, but could be used by a custom Animation class.

**Parameters:**

| Name      | Type      | Required | Description         |
| --------- | --------- | -------- | ------------------- |
| animation | Animation | Yes      | See `Animation.js`. |
| callback  | function  | Yes      | Callback function.  |

----
url: https://reactnative.dev/docs/reactnativeversion
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React TSX

```
import {ReactNativeVersion} from 'react-native';
```

The `ReactNativeVersion` API exposes the version of the resolved `react-native` package on JS side. Apps and libraries can use it to check compatibility or enable version-specific behavior.

note

Also, we have [`Platform.constants.reactNativeVersion`](/docs/platform#constants) in our public API already. **However**, this is the per-platform ***native-reported*** React Native version.

## Example[​](#example "Direct link to Example")

React TSX

```
import {ReactNativeVersion} from 'react-native';



const version = ReactNativeVersion.getVersionString(); // 0.87.1

const {major, minor, patch, prerelease} = ReactNativeVersion;

major; // 0

minor; // 87

patch; // 1

prerelease; // null
```

***

# Reference

## Properties[​](#properties "Direct link to Properties")

### `major`[​](#major "Direct link to major")

React TSX

```
static major: number;
```

The major version number of the resolved `react-native` package.

***

### `minor`[​](#minor "Direct link to minor")

React TSX

```
static minor: number;
```

The minor version number of the resolved `react-native` package.

***

### `patch`[​](#patch "Direct link to patch")

React TSX

```
static patch: number;
```

The patch version number of the resolved `react-native` package.

***

### `prerelease`[​](#prerelease "Direct link to prerelease")

React TSX

```
static prerelease: string | null;
```

The prerelease tag for the resolved `react-native` package, or `null` for stable releases.

## Methods[​](#methods "Direct link to Methods")

### `getVersionString()`[​](#getversionstring "Direct link to getversionstring")

React TSX

```
static getVersionString(): string;
```

----
url: https://reactnative.dev/docs/next/settings
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/settings)** (0.87).

Version: Next

`Settings` serves as a wrapper for [`NSUserDefaults`](https://developer.apple.com/documentation/foundation/nsuserdefaults), a persistent key-value store available only on iOS.

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `clearWatch()`[​](#clearwatch "Direct link to clearwatch")

React TSX

```
static clearWatch(watchId: number);
```

`watchId` is the number returned by `watchKeys()` when the subscription was originally configured.

***

### `get()`[​](#get "Direct link to get")

React TSX

```
static get(key: string): any;
```

Get the current value for a given `key` in `NSUserDefaults`.

***

### `set()`[​](#set "Direct link to set")

React TSX

```
static set(settings: Record<string, any>);
```

Set one or more values in `NSUserDefaults`.

***

### `watchKeys()`[​](#watchkeys "Direct link to watchkeys")

React TSX

```
static watchKeys(keys: string | array<string>, callback: () => void): number;
```

----
url: https://reactnative.dev/docs/next/the-new-architecture/turbo-modules-with-swift
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/turbo-modules-with-swift)** (0.87).

Version: Next

```
import Foundation



@objcMembers public class NativeLocalStorage: NSObject {

  let userDefaults = UserDefaults(suiteName: "local-storage");



  public func getItem(for key: String) -> String? {

    return userDefaults?.string(forKey: key)

  }



  public func setItem(for key: String, value: String) {

    userDefaults?.set(value, forKey: key)

  }



  public func removeItem(for key: String) {

    userDefaults?.removeObject(forKey: key)

  }



  public func clear() {

    userDefaults?.dictionaryRepresentation().keys.forEach { removeItem(for: $0) }

  }

}
```

Notice that you have to declare all the methods that you need to call from Objective-C as `public` and with the `@objc` annotation. Remember also to make your class inherit from `NSObject`, otherwise it would not be possible to use it from Objective-C.

### Update the `RCTNativeLocalStorage` file[​](#update-the-rctnativelocalstorage-file "Direct link to update-the-rctnativelocalstorage-file")

Then, you need to update the implementation of the `RCTNativeLocalStorage` to be able to create the Swift module and to call its methods.

1. Open the `RCTNativeLocalStorage.mm` file
2. Update it as it follows:

RCTNativeLocalStorage.mm

```
//  RCTNativeLocalStorage.m

//  TurboModuleExample



#import "RCTNativeLocalStorage.h"

+#import "SampleApp-Swift.h"



- static NSString *const RCTNativeLocalStorageKey = @"local-storage";



-@interface RCTNativeLocalStorage()

-@property (strong, nonatomic) NSUserDefaults *localStorage;

-@end



-@implementation RCTNativeLocalStorage

+@implementation RCTNativeLocalStorage {

+    NativeLocalStorage *storage;

+}



-RCT_EXPORT_MODULE(NativeLocalStorage)



 - (id) init {

   if (self = [super init]) {

-    _localStorage = [[NSUserDefaults alloc] initWithSuiteName:RCTNativeLocalStorageKey];

+    storage = [NativeLocalStorage new];

   }

   return self;

 }



 - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {

   return std::make_shared<facebook::react::NativeLocalStorageSpecJSI>(params);

 }



 - (NSString * _Nullable)getItem:(NSString *)key {

-   return [self.localStorage stringForKey:key];

+   return [storage getItemFor:key];

 }



 - (void)setItem:(NSString *)value key:(NSString *)key {

-   [self.localStorage setObject:value forKey:key];

+   [storage setItemFor:key value:value];

 }



 - (void)removeItem:(NSString *)key {

-   [self.localStorage removeObjectForKey:key];

+   [storage removeItemFor:key];

 }



 - (void)clear {

-   NSDictionary *keys = [self.localStorage dictionaryRepresentation];

-   for (NSString *key in keys) {

-     [self removeItem:key];

-   }

+  [storage clear];

 }



++ (NSString *)moduleName

+{

+  return @"NativeLocalStorage";

+}



@end
```

```
//

//  Use this file to import your target's public headers that you would like to expose to Swift.

//



+ #import <React-RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>
```

----
url: https://reactnative.dev/docs/next/global-queueMicrotask
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-queueMicrotask)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/queueMicrotask) for more information.

The global `queueMicrotask` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/global-global
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-global)** (0.87).

Version: Next

[`global`](https://nodejs.org/api/globals.html#global) is a legacy alias for [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), as defined in Node.js.

The use of `globalThis` is recommended over `global`.

----
url: https://reactnative.dev/docs/next/native-platform
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/native-platform)** (0.87).

Version: Next

Your application may need access to platform features that aren’t directly available from react-native or one of the hundreds of [third-party libraries](https://reactnative.directory/) maintained by the community. Maybe you want to reuse some existing Objective-C, Swift, Java, Kotlin or C++ code from the JavaScript runtime. Whatever your reason, React Native exposes a powerful set of API to connect your native code to your JavaScript application code.

This guide introduces:

* **Native Modules:** native libraries that have no User Interface (UI) for the user. Examples would be persistent storage, notifications, network events. These are accessible to your user as JavaScript functions and objects.
* **Native Component:** native platform views, widgets and controllers that are available to your application's JavaScript code through React Components.

note

You might have previously been familiar with:

* [Legacy Native Modules](/docs/next/legacy/native-modules-intro);
* [Legacy Native Components](/docs/next/legacy/native-components-android);

These are our deprecated native module and component API. You can still use many of these legacy libraries with the New Architecture thanks to our interop layers. You should consider:

* using alternative libraries,
* upgrading to newer library versions that have first-class support for the New Architecture, or
* port these libraries yourself to Turbo Native Modules or Fabric Native Components.

1. Native Modules

   * [Android & iOS](/docs/next/turbo-native-modules-introduction)
   * [Cross-Platform with C++](/docs/next/the-new-architecture/pure-cxx-modules)
   * [Advanced: Custom C++ Types](/docs/next/the-new-architecture/custom-cxx-types)

2. Fabric Native Components
   * [Android & iOS](/docs/next/fabric-native-components-introduction)

----
url: https://reactnative.dev/docs/next/stylesheet
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/stylesheet)** (0.87).

Version: Next

A StyleSheet is an abstraction similar to CSS StyleSheets.

Code quality tips:

* By moving styles away from the render function, you're making the code easier to understand.
* Naming the styles is a good way to add meaning to the low level components in the render function, and encourage reuse.
* In most IDEs, using `StyleSheet.create()` will offer static type checking and suggestions to help you write valid styles.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `compose()`[​](#compose "Direct link to compose")

React TSX

```
static compose(style1: Object, style2: Object): Object | Object[];
```

Combines two styles such that `style2` will override any styles in `style1`. If either style is falsy, the other one is returned without allocating an array, saving allocations and maintaining reference equality for PureComponent checks.

***

### `create()`[​](#create "Direct link to create")

React TSX

```
static create(styles: Object extends Record<string, ViewStyle | ImageStyle | TextStyle>): Object;
```

An identity function for creating styles. The main practical benefit of creating styles inside `StyleSheet.create()` is static type checking against native style properties.

***

### `flatten()`[​](#flatten "Direct link to flatten")

React TSX

```
static flatten(style: Array<Object extends Record<string, ViewStyle | ImageStyle | TextStyle>>): Object;
```

Flattens an array of style objects, into one aggregated style object.

***

### `setStyleAttributePreprocessor()`[​](#setstyleattributepreprocessor "Direct link to setstyleattributepreprocessor")

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.

React TSX

```
static setStyleAttributePreprocessor(

  property: string,

  process: (propValue: any) => any,

);
```

Sets a function to use to pre-process a style property value. This is used internally to process color and transform values. You should not use this unless you really know what you are doing and have exhausted other options.

## Properties[​](#properties "Direct link to Properties")

***

### `absoluteFill`[​](#absolutefill "Direct link to absolutefill")

A very common pattern is to create overlays with position absolute and zero positioning (`position: 'absolute', left: 0, right: 0, top: 0, bottom: 0`), so `absoluteFill` can be used for convenience and to reduce duplication of these repeated styles. If you want, absoluteFill can be used to create a customized entry in a StyleSheet, e.g.:

***

----
url: https://reactnative.dev/docs/the-new-architecture/direct-manipulation-new-architecture
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

You can use the [`clear`](/docs/textinput#clear) method to clear the `TextInput` which clears the current input text using the same approach.

## Avoiding conflicts with the render function[​](#avoiding-conflicts-with-the-render-function "Direct link to Avoiding conflicts with the render function")

If you update a property that is also managed by the render function, you might end up with some unpredictable and confusing bugs because anytime the component re-renders and that property changes, whatever value was previously set from `setNativeProps` will be completely ignored and overridden.

* [setNativeProps to edit TextInput value](#setnativeprops-to-edit-textinput-value)
* [Avoiding conflicts with the render function](#avoiding-conflicts-with-the-render-function)

----
url: https://reactnative.dev/docs/platform
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

## Example[​](#example "Direct link to Example")

***

# Reference

## Properties[​](#properties "Direct link to Properties")

### `constants`[​](#constants "Direct link to constants")

React TSX

```
static constants: PlatformConstants;
```

Returns an object which contains all available common and specific constants related to the platform.

**Properties:**

| Name                   | Type    | Optional | Description                                                                                                                                                                                       |
| ---------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| isDisableAnimations    | boolean | Yes      | Whether animations should be disabled. When not set, defaults to the value of `isTesting`.                                                                                                        |
| isTesting              | boolean | No       |                                                                                                                                                                                                   |
| reactNativeVersion     | object  | No       | Information about React Native version. Keys are `major`, `minor`, `patch` with optional `prerelease` and values are `number`s.                                                                   |
| VersionAndroid         | number  | No       | OS version constant specific to Android.                                                                                                                                                          |
| ReleaseAndroid         | string  | No       |                                                                                                                                                                                                   |
| SerialAndroid          | string  | No       | Hardware serial number of an Android device.                                                                                                                                                      |
| FingerprintAndroid     | string  | No       | A string that uniquely identifies the build.                                                                                                                                                      |
| ModelAndroid           | string  | No       | The end-user-visible name for the Android device.                                                                                                                                                 |
| BrandAndroid           | string  | No       | The consumer-visible brand with which the product/hardware will be associated.                                                                                                                    |
| ManufacturerAndroid    | string  | No       | The manufacturer of the Android device.                                                                                                                                                           |
| ServerHostAndroid      | string  | Yes      |                                                                                                                                                                                                   |
| uiModeAndroid          | string  | No       | Possible values are: `'car'`, `'desk'`, `'normal'`,`'tv'`, `'watch'` and `'unknown'`. Read more about [Android ModeType](https://developer.android.com/reference/android/app/UiModeManager.html). |
| forceTouchAvailableiOS | boolean | No       | Indicate the availability of 3D Touch on a device.                                                                                                                                                |
| interfaceIdiomiOS      | string  | No       | The interface type for the device. Read more about [UIUserInterfaceIdiom](https://developer.apple.com/documentation/uikit/uiuserinterfaceidiom).                                                  |
| osVersioniOS           | string  | No       | OS version constant specific to iOS.                                                                                                                                                              |
| systemNameiOS          | string  | No       | OS name constant specific to iOS.                                                                                                                                                                 |

***

### `isDisableAnimations`[​](#isdisableanimations "Direct link to isdisableanimations")

React TSX

```
static isDisableAnimations: boolean;
```

Returns `true` when animations are turned off, usually during automated tests. Falls back to [`isTesting`](#istesting) if not set. On Android, it can be set with the `IS_DISABLE_ANIMATIONS` system property.

| Type    |
| ------- |
| boolean |

***

### `isPad`iOS[​](#ispad-ios "Direct link to ispad-ios")

React TSX

```
static isPad: boolean;
```

Returns a boolean which defines if device is an iPad.

| Type    |
| ------- |
| boolean |

***

### `isTV`[​](#istv "Direct link to istv")

React TSX

```
static isTV: boolean;
```

Returns a boolean which defines if device is a TV.

| Type    |
| ------- |
| boolean |

***

### `isVision`[​](#isvision "Direct link to isvision")

React TSX

```
static isVision: boolean;
```

Returns a boolean which defines if device is an Apple Vision. *If you are using [Apple Vision Pro (Designed for iPad)](https://developer.apple.com/documentation/visionos/determining-whether-to-bring-your-app-to-visionos) `isVision` will be `false` but `isPad` will be `true`*

| Type    |
| ------- |
| boolean |

***

### `isTesting`[​](#istesting "Direct link to istesting")

React TSX

```
static isTesting: boolean;
```

Returns a boolean which defines if application is running in Developer Mode with testing flag set.

| Type    |
| ------- |
| boolean |

***

### `OS`[​](#os "Direct link to os")

React TSX

```
static OS: 'android' | 'ios';
```

Returns string value representing the current OS.

| Type                       |
| -------------------------- |
| enum(`'android'`, `'ios'`) |

***

### `Version`[​](#version "Direct link to version")

React TSX

```
static Version: 'number' | 'string';
```

Returns the version of the OS.

| Type                      |
| ------------------------- |
| numberAndroid***stringiOS |

## Methods[​](#methods "Direct link to Methods")

### `select()`[​](#select "Direct link to select")

React TSX

```
static select(config: Record<string, T>): T;
```

Returns the most fitting value for the platform you are currently running on.

#### Parameters:[​](#parameters "Direct link to Parameters:")

| Name   | Type   | Required | Description                   |
| ------ | ------ | -------- | ----------------------------- |
| config | object | Yes      | See config description below. |

```
import {Platform, StyleSheet} from 'react-native';



const styles = StyleSheet.create({

  container: {

    flex: 1,

    ...Platform.select({

      android: {

        backgroundColor: 'green',

      },

      ios: {

        backgroundColor: 'red',

      },

      default: {

        // other platforms, web for example

        backgroundColor: 'blue',

      },

    }),

  },

});
```

This will result in a container having `flex: 1` on all platforms, a green background color on Android, a red background color on iOS, and a blue background color on other platforms.

Since the value of the corresponding platform key can be of type `any`, [`select`](/docs/platform#select) method can also be used to return platform-specific components, like below:

React TSX

```
const Component = Platform.select({

  ios: () => require('ComponentIOS'),

  android: () => require('ComponentAndroid'),

})();



<Component />;
```

React TSX

```
const Component = Platform.select({

  native: () => require('ComponentForNative'),

  default: () => require('ComponentForWeb'),

})();



<Component />;
```

* [Example](#example)

* [Properties](#properties)

  * [`constants`](#constants)
  * [`isDisableAnimations`](#isdisableanimations)
  * [`isPad`](#ispad-ios)

    [iOS](#ispad-ios)

----
url: https://reactnative.dev/docs/next/global-PerformanceMark
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-PerformanceMark)** (0.87).

Version: Next

The global [`PerformanceMark`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMark) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/legacy/native-modules-intro
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/legacy/native-modules-intro)** (0.87).

Version: Next

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

Sometimes a React Native app needs to access a native platform API that is not available by default in JavaScript, for example the native APIs to access Apple or Google Pay. Maybe you want to reuse some existing Objective-C, Swift, Java or C++ libraries without having to reimplement it in JavaScript, or write some high performance, multi-threaded code for things like image processing.

The NativeModule system exposes instances of Java/Objective-C/C++ (native) classes to JavaScript (JS) as JS objects, thereby allowing you to execute arbitrary native code from within JS. While we don't expect this feature to be part of the usual development process, it is essential that it exists. If React Native doesn't export a native API that your JS app needs you should be able to export it yourself!

## Native Module Setup[​](#native-module-setup "Direct link to Native Module Setup")

There are different ways to write a native module for your React Native application:

1. Creating a local library that can be imported in your React Native application. Read [Creating local libraries](/docs/next/legacy/local-library-setup) guide to learn more.
2. Directly within your React Native application's iOS/Android projects
3. As an NPM package that can be installed as a dependency by your/other React Native applications.

This guide will first walk you through implementing a native module directly within a React Native application. However the native module you build in the following guide can be distributed as an NPM package. Check out the [Setting Up a Native Module as an NPM Package](/docs/next/legacy/native-modules-setup) guide if you are interested in doing so.

## Getting Started[​](#getting-started "Direct link to Getting Started")

In the following sections we will walk you through guides on how to build a native module directly within a React Native application. As a prerequisite, you will need a React Native application to work within. You can follow the steps [here](/docs/next/getting-started) to setup a React Native application if you do not already have one.

Imagine that you want to access the iOS/Android native calendar APIs from JavaScript within a React Native application in order to create calendar events. React Native does not expose a JavaScript API to communicate with the native calendar libraries. However, through native modules, you can write native code that communicates with native calendar APIs. Then you can invoke that native code through JavaScript in your React Native application.

In the following sections you will create such a Calendar native module for both [Android](/docs/next/legacy/native-modules-android) and [iOS](/docs/next/legacy/native-modules-ios).

* [Native Module Setup](#native-module-setup)
* [Getting Started](#getting-started)

----
url: https://reactnative.dev/docs/next/timers
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/timers)** (0.87).

Version: Next

----
url: https://reactnative.dev/docs/next/global-setInterval
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-setInterval)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval) for more information.

The global `setInterval` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/optimizing-javascript-loading
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/optimizing-javascript-loading)** (0.87).

Version: Next

Parsing and running JavaScript code requires memory and time. Because of this, as your app grows, it's often useful to delay loading code until it's needed for the first time. React Native comes with some standard optimizations that are on by default, and there are techniques you can adopt in your own code to help React load your app more efficiently. There are also some advanced automatic optimizations (with their own tradeoffs) that are suitable for very large apps.

## Recommended: Use Hermes[​](#recommended-use-hermes "Direct link to Recommended: Use Hermes")

Hermes is the default engine for new React Native apps, and is highly optimized for efficient code loading. In release builds, JavaScript code is fully compiled to bytecode ahead of time. Bytecode is loaded to memory on-demand and does not need to be parsed like plain JavaScript does.

info

Read more about using Hermes in React Native [here](/docs/next/hermes).

```
import Logger from './utils/Logger';



//  🚩 🚩 🚩 Side effect! This must be executed before React can even begin to

// render the SplashScreen component, and can unexpectedly break code elsewhere

// in your app if you later decide to lazy-load SplashScreen.

global.logger = new Logger();



export function SplashScreen() {

  // ...

}
```

## Advanced: Call `require` inline[​](#advanced-call-require-inline "Direct link to advanced-call-require-inline")

Sometimes you may want to defer loading some code until you use it for the first time, without using `lazy` or an asynchronous `import()`. You can do this by using the [`require()`](https://metrobundler.dev/docs/module-api/#require) function where you would otherwise use a static `import` at the top of the file.

VeryExpensive.tsx

```
import {Component} from 'react';

import {Text} from 'react-native';

// ... import some very expensive modules



export default function VeryExpensive() {

  // ... lots and lots of rendering logic

  return <Text>Very Expensive Component</Text>;

}
```

Optimized.tsx

```
import {useCallback, useState} from 'react';

import {TouchableOpacity, View, Text} from 'react-native';

// Usually we would write a static import:

// import VeryExpensive from './VeryExpensive';



let VeryExpensive = null;



export default function Optimize() {

  const [needsExpensive, setNeedsExpensive] = useState(false);

  const didPress = useCallback(() => {

    if (VeryExpensive == null) {

      VeryExpensive = require('./VeryExpensive').default;

    }



    setNeedsExpensive(true);

  }, []);



  return (

    <View style={{marginTop: 20}}>

      <TouchableOpacity onPress={didPress}>

        <Text>Load</Text>

      </TouchableOpacity>

      {needsExpensive ? <VeryExpensive /> : null}

    </View>

  );

}
```

## Advanced: Automatically inline `require` calls[​](#advanced-automatically-inline-require-calls "Direct link to 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.

React TSX

```
import {useCallback, useState} from 'react';

import {TouchableOpacity, View, Text} from 'react-native';



// This top-level require call will be evaluated lazily as part of the component below.

const VeryExpensive = require('./VeryExpensive').default;



export default function Optimize() {

  const [needsExpensive, setNeedsExpensive] = useState(false);

  const didPress = useCallback(() => {

    setNeedsExpensive(true);

  }, []);



  return (

    <View style={{marginTop: 20}}>

      <TouchableOpacity onPress={didPress}>

        <Text>Load</Text>

      </TouchableOpacity>

      {needsExpensive ? <VeryExpensive /> : null}

    </View>

  );

}
```

```
module.exports = {

  transformer: {

    async getTransformOptions() {

      return {

        transform: {

          inlineRequires: false,

        },

      };

    },

  },

};
```

To only **exclude certain modules from `require` inlining:**

There are two relevant transformer options: `inlineRequires.blockList` and `nonInlinedRequires`. See the code snippet for examples of how to use each one.

metro.config.js

```
module.exports = {

  transformer: {

    async getTransformOptions() {

      return {

        transform: {

          inlineRequires: {

            blockList: {

              // require() calls in `DoNotInlineHere.js` will not be inlined.

              [require.resolve('./src/DoNotInlineHere.js')]: true,



              // require() calls anywhere else will be inlined, unless they

              // match any entry nonInlinedRequires (see below).

            },

          },

          nonInlinedRequires: [

            // require('react') calls will not be inlined anywhere

            'react',

          ],

        },

      };

    },

  },

};
```

```
project.ext.react = [

  bundleCommand: "ram-bundle",

]
```

Use the following lines on Android if you want to use a single indexed file:

```
project.ext.react = [

  bundleCommand: "ram-bundle",

  extraPackagerArgs: ["--indexed-ram-bundle"]

]
```

On iOS, RAM bundles are always indexed ( = single file).

Enable the RAM format in Xcode by editing the build phase "Bundle React Native code and images". Before `../node_modules/react-native/scripts/react-native-xcode.sh` add `export BUNDLE_COMMAND="ram-bundle"`:

```
export BUNDLE_COMMAND="ram-bundle"

export NODE_BINARY=node

../node_modules/react-native/scripts/react-native-xcode.sh
```

----
url: https://reactnative.dev/docs/next/touchableopacity
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/touchableopacity)** (0.87).

Version: Next

tip

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the [Pressable](/docs/next/pressable) API.

A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, dimming it.

Opacity is controlled by wrapping the children in an `Animated.View`, which is added to the view hierarchy. Be aware that this can affect layout.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [TouchableWithoutFeedback Props](/docs/next/touchablewithoutfeedback#props)[​](#touchablewithoutfeedback-props "Direct link to touchablewithoutfeedback-props")

Inherits [TouchableWithoutFeedback Props](/docs/next/touchablewithoutfeedback#props).

***

### `style`[​](#style "Direct link to style")

| Type                                      |
| ----------------------------------------- |
| [View.style](/docs/next/view-style-props) |

***

### `activeOpacity`[​](#activeopacity "Direct link to activeopacity")

Determines what the opacity of the wrapped view should be when touch is active. Defaults to `0.2`.

| Type   |
| ------ |
| number |

***

### `hasTVPreferredFocus`iOS[​](#hastvpreferredfocus-ios "Direct link to hastvpreferredfocus-ios")

*(Apple TV only)* TV preferred focus (see documentation for the View component).

| Type |
| ---- |
| bool |

***

### `nextFocusDown`Android[​](#nextfocusdown-android "Direct link to nextfocusdown-android")

TV next focus down (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`Android[​](#nextfocusforward-android "Direct link to nextfocusforward-android")

TV next focus forward (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`Android[​](#nextfocusleft-android "Direct link to nextfocusleft-android")

TV next focus left (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`Android[​](#nextfocusright-android "Direct link to nextfocusright-android")

TV next focus right (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`Android[​](#nextfocusup-android "Direct link to nextfocusup-android")

TV next focus up (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/next/element-nodes) when mounted.

* [Example](#example)

* [Props](#props)

  * [TouchableWithoutFeedback Props](#touchablewithoutfeedback-props)
  * [`style`](#style)
  * [`activeOpacity`](#activeopacity)
  * [`hasTVPreferredFocus`](#hastvpreferredfocus-ios)

    [iOS](#hastvpreferredfocus-ios)
  * [`nextFocusDown`](#nextfocusdown-android)

    [Android](#nextfocusdown-android)
  * [`nextFocusForward`](#nextfocusforward-android)

    [Android](#nextfocusforward-android)
  * [`nextFocusLeft`](#nextfocusleft-android)

    [Android](#nextfocusleft-android)
  * [`nextFocusRight`](#nextfocusright-android)

    [Android](#nextfocusright-android)
  * [`nextFocusUp`](#nextfocusup-android)

    [Android](#nextfocusup-android)
  * [`ref`](#ref)

----
url: https://reactnative.dev/docs/view-style-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

### Example[​](#example "Direct link to Example")

# Reference

## Props[​](#props "Direct link to Props")

### `backfaceVisibility`[​](#backfacevisibility "Direct link to backfacevisibility")

| Type                          |
| ----------------------------- |
| enum(`'visible'`, `'hidden'`) |

***

### `backgroundColor`[​](#backgroundcolor "Direct link to backgroundcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `backgroundImage`[​](#backgroundimage "Direct link to backgroundimage")

`backgroundImage` provides the ability to draw a [`linear-gradient()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/gradient/linear-gradient) and [`radial-gradient()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/gradient/radial-gradient) using a web-like syntax.

React TSX

```
// Simple usage:

<View style={{ backgroundImage: 'linear-gradient(45deg, blue, red)' }} />



<View style={{ backgroundImage: 'radial-gradient(ellipse farthest-corner at 30% 40%, red, blue)' }} />



// Also with PlatformColor:

<View

style={{

  backgroundImage: [

    {

      type: 'linear-gradient',

      direction: 'to bottom',

      colorStops: [

        {

          color: Platform.select({

            ios: PlatformColor('systemTealColor'),

            android: PlatformColor('@android:color/holo_purple'),

            default: 'blue',

          }),

          positions: ['0%'],

        },

        {color: 'green', positions: ['100%']},

      ],

    },

  ],

}}

/>
```

More complex examples of usage can be found in the RNTester app (with `PlatformColor` supports):

* [LinearGradientExample.js](https://github.com/react/react-native/blob/v0.87.0/packages/rn-tester/js/examples/LinearGradient/LinearGradientExample.js)
* [RadialGradientExample.js](https://github.com/react/react-native/blob/v0.87.0/packages/rn-tester/js/examples/RadialGradient/RadialGradientExample.js)

| Type                                                                                                                                                                                               |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| string, array of objects: `{type: 'linear-gradient', direction: string, colorStops: object[] }`, `{type: 'radial-gradient', shape: string, position: object, size: string, colorStops: object[] }` |

***

### `borderBottomColor`[​](#borderbottomcolor "Direct link to borderbottomcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderBlockColor`[​](#borderblockcolor "Direct link to borderblockcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderBlockEndColor`[​](#borderblockendcolor "Direct link to borderblockendcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderBlockStartColor`[​](#borderblockstartcolor "Direct link to borderblockstartcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderBottomEndRadius`[​](#borderbottomendradius "Direct link to borderbottomendradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderBottomLeftRadius`[​](#borderbottomleftradius "Direct link to borderbottomleftradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderBottomRightRadius`[​](#borderbottomrightradius "Direct link to borderbottomrightradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderBottomStartRadius`[​](#borderbottomstartradius "Direct link to borderbottomstartradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderStartEndRadius`[​](#borderstartendradius "Direct link to borderstartendradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderStartStartRadius`[​](#borderstartstartradius "Direct link to borderstartstartradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderEndEndRadius`[​](#borderendendradius "Direct link to borderendendradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderEndStartRadius`[​](#borderendstartradius "Direct link to borderendstartradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderBottomWidth`[​](#borderbottomwidth "Direct link to borderbottomwidth")

| Type   |
| ------ |
| number |

***

### `borderColor`[​](#bordercolor "Direct link to bordercolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderCurve`iOS[​](#bordercurve-ios "Direct link to bordercurve-ios")

On iOS 13+, it is possible to change the corner curve of borders.

| Type                               |
| ---------------------------------- |
| enum(`'circular'`, `'continuous'`) |

***

### `borderEndColor`[​](#borderendcolor "Direct link to borderendcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderLeftColor`[​](#borderleftcolor "Direct link to borderleftcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderLeftWidth`[​](#borderleftwidth "Direct link to borderleftwidth")

| Type   |
| ------ |
| number |

***

### `borderRadius`[​](#borderradius "Direct link to borderradius")

If the rounded border is not visible, try applying `overflow: 'hidden'` as well.

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderRightColor`[​](#borderrightcolor "Direct link to borderrightcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderRightWidth`[​](#borderrightwidth "Direct link to borderrightwidth")

| Type   |
| ------ |
| number |

***

### `borderStartColor`[​](#borderstartcolor "Direct link to borderstartcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderStyle`[​](#borderstyle "Direct link to borderstyle")

| Type                                    |
| --------------------------------------- |
| enum(`'solid'`, `'dotted'`, `'dashed'`) |

***

### `borderTopColor`[​](#bordertopcolor "Direct link to bordertopcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `borderTopEndRadius`[​](#bordertopendradius "Direct link to bordertopendradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderTopLeftRadius`[​](#bordertopleftradius "Direct link to bordertopleftradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderTopRightRadius`[​](#bordertoprightradius "Direct link to bordertoprightradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderTopStartRadius`[​](#bordertopstartradius "Direct link to bordertopstartradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderTopWidth`[​](#bordertopwidth "Direct link to bordertopwidth")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderWidth`[​](#borderwidth "Direct link to borderwidth")

| Type   |
| ------ |
| number |

### `boxShadow`[​](#boxshadow "Direct link to boxshadow")

note

`boxShadow` is only available on the [New Architecture](/architecture/landing-page). Outset shadows are only supported on **Android 9+**. Inset shadows are only supported on **Android 10+**.

Adds a shadow effect to an element, with the ability to control the position, color, size, and blurriness of the shadow. This shadow either appears around the outside or inside of the border box of the element, depending on whether or not the shadow is *inset*. This is a spec-compliant implementation of the [web style prop of the same name](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow). Read more about all the arguments available in the [BoxShadowValue](/docs/boxshadowvalue) documentation.

These shadows can be composed together so that a single `boxShadow` can be comprised of multiple different shadows.

`boxShadow` takes either a string which mimics the [web syntax](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow#syntax) or an array of [BoxShadowValue](/docs/boxshadowvalue) objects.

| Type                                      |
| ----------------------------------------- |
| array of BoxShadowValue objects \| string |

### `cursor`iOS[​](#cursor-ios "Direct link to cursor-ios")

On iOS 17+, Setting to `pointer` allows hover effects when a pointer (such as a trackpad or stylus on iOS, or the users' gaze on visionOS) is over the view.

| Type                        |
| --------------------------- |
| enum(`'auto'`, `'pointer'`) |

***

### `elevation`Android[​](#elevation-android "Direct link to elevation-android")

Sets the elevation of a view, using Android's underlying [elevation API](https://developer.android.com/training/material/shadows-clipping.html#Elevation). This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.

| Type   |
| ------ |
| number |

***

### `experimental_backgroundPosition`[​](#experimental_backgroundposition "Direct link to experimental_backgroundposition")

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

Controls where the background gradient is placed inside the view. This is useful when `experimental_backgroundImage` is set, and you want to offset or center it instead of filling the full area.

React TSX

```
<View

  style={{

    experimental_backgroundImage:

      'radial-gradient(circle, #ff6b6b, #4ecdc4)',

    experimental_backgroundPosition: 'center',

    experimental_backgroundRepeat: 'no-repeat',

    experimental_backgroundSize: '50px 50px',

  }}

/>
```

| Type                                                                                    |
| --------------------------------------------------------------------------------------- |
| string \| array of objects `{top: string, left: string, right: string, bottom: string}` |

***

### `experimental_backgroundRepeat`[​](#experimental_backgroundrepeat "Direct link to experimental_backgroundrepeat")

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

Controls whether the background gradient is repeated, and how. This works together with `experimental_backgroundImage` to tile gradients across the view.

React TSX

```
<View

  style={{

    experimental_backgroundImage:

      'linear-gradient(45deg, #ff6b6b, #4ecdc4)',

    experimental_backgroundRepeat: 'repeat',

    experimental_backgroundSize: '20px 20px',

  }}

/>
```

| Type                                                                                               |
| -------------------------------------------------------------------------------------------------- |
| enum(`'repeat'`, `'space'`, `'round'`, `'no-repeat'`) \| array of objects `{x: string, y: string}` |

***

### `experimental_backgroundSize`[​](#experimental_backgroundsize "Direct link to experimental_backgroundsize")

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

Controls the size of the background gradient. This is most useful when `experimental_backgroundImage` is set and the gradient should not fill the entire view by default.

React TSX

```
<View

  style={{

    experimental_backgroundImage:

      'linear-gradient(90deg, #a8edea, #fed6e3)',

    experimental_backgroundRepeat: 'no-repeat',

    experimental_backgroundSize: '100px 100px',

  }}

/>
```

| Type                                                |
| --------------------------------------------------- |
| string \| array of objects `{x: number, y: number}` |

***

* `dropShadow`: Adds a shadow around the alpha mask of the `View` (only non-zero alpha pixels in the `View` will cast a shadow). Takes an optional color representing the shadow color, and 2 or 3 lengths. If 2 lengths are specified they are interpreted as `offsetX` and `offsetY` which will translate the shadow in the X and Y dimensions respectfully. If a 3rd length is given it is interpreted as the standard deviation of the Gaussian blur used on the shadow - so a larger value will blur the shadow more. Read more about the arguments in [DropShadowValue](/docs/dropshadowvalue).

| Type                                                                                                                                                                                                                                                                                                                                        |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| array of objects: `{brightness: number\|string}`, `{opacity: number\|string}`, `{blur: number\|string}`, `{contrast: number\|string}`, `{dropShadow: DropShadowValue\|string}`, `{grayscale: number\|string}`, `{hueRotate: number\|string}`, `{invert: number\|string}`, `{sepia: number\|string}`, `{saturate: number\|string}` or string |

***

### `mixBlendMode`[​](#mixblendmode "Direct link to mixblendmode")

note

`mixBlendMode` is only available on the [New Architecture](/architecture/landing-page) and **Android 10+**

Controls how the `View` blends its colors with the other elements in its **stacking context**. Check out the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode) for a full overview of each blending function.

For more granular control over what should be blending together see [isolation](/docs/layout-props#isolation).

| Type                                                                                                                                                                                                                                                   |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| enum(`'normal'`, `'multiply'`, `'screen'`, `'overlay'`, `'darken'`, `'lighten'`, `'color-dodge'`, `'color-burn'`, `'hard-light'`, `'soft-light'`, `'difference'`, `'exclusion'`, `'hue'`, `'saturation'`, `'color'`, `'luminosity'`, `'plus-lighter'`) |

***

### `opacity`[​](#opacity "Direct link to opacity")

| Type   |
| ------ |
| number |

***

### `outlineColor`[​](#outlinecolor "Direct link to outlinecolor")

note

`outlineColor` is only available on the [New Architecture](/architecture/landing-page)

Sets the color of an element's outline. See [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-color) for more details.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `outlineOffset`[​](#outlineoffset "Direct link to outlineoffset")

note

`outlineOffset` is only available on the [New Architecture](/architecture/landing-page)

Sets the amount of space between an outline and the bounds of an element. Does not affect layout. See [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-offset) for more details.

| Type   |
| ------ |
| number |

***

### `outlineStyle`[​](#outlinestyle "Direct link to outlinestyle")

note

`outlineStyle` is only available on the [New Architecture](/architecture/landing-page)

Sets the style of an element's outline. See [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-style) for more details.

| Type                                    |
| --------------------------------------- |
| enum(`'solid'`, `'dotted'`, `'dashed'`) |

***

### `outlineWidth`[​](#outlinewidth "Direct link to outlinewidth")

note

`outlineWidth` is only available on the [New Architecture](/architecture/landing-page)

The width of an outline which is drawn around an element, outside the border. Does not affect layout. See [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-width) for more details.

| Type   |
| ------ |
| number |

***

### `pointerEvents`[​](#pointerevents "Direct link to pointerevents")

Controls whether the `View` can be the target of touch events.

* `'auto'`: The View can be the target of touch events.
* `'none'`: The View is never the target of touch events.
* `'box-none'`: The View is never the target of touch events but its subviews can be.
* `'box-only'`: The view can be the target of touch events but its subviews cannot be.

| Type                                                  |
| ----------------------------------------------------- |
| enum(`'auto'`, `'box-none'`, `'box-only'`, `'none'` ) |

* [Example](#example)

* [Props](#props)

  * [`backfaceVisibility`](#backfacevisibility)
  * [`backgroundColor`](#backgroundcolor)
  * [`backgroundImage`](#backgroundimage)

    [iOS](#bordercurve-ios)

    [iOS](#cursor-ios)
  * [`elevation`](#elevation-android)

    [Android](#elevation-android)
  * [`experimental_backgroundPosition`](#experimental_backgroundposition)
  * [`experimental_backgroundRepeat`](#experimental_backgroundrepeat)
  * [`experimental_backgroundSize`](#experimental_backgroundsize)

----
url: https://reactnative.dev/docs/next/actionsheetios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/actionsheetios)** (0.87).

Version: Next

Displays native to iOS [Action Sheet](https://developer.apple.com/design/human-interface-guidelines/action-sheets) component.

## Example[​](#example "Direct link to Example")

# Reference

## Methods[​](#methods "Direct link to Methods")

### `showActionSheetWithOptions()`[​](#showactionsheetwithoptions "Direct link to showactionsheetwithoptions")

React TSX

```
static showActionSheetWithOptions: (

  options: ActionSheetIOSOptions,

  callback: (buttonIndex: number) => void,

);
```

Display an iOS action sheet. The `options` object must contain one or more of:

* `options` (array of strings) - a list of button titles (required)
* `cancelButtonIndex` (int) - index of cancel button in `options`
* `cancelButtonTintColor` (string) - the [color](/docs/next/colors) used for the change the text color of the cancel button
* `destructiveButtonIndex` (int or array of ints) - indices of destructive buttons in `options`
* `title` (string) - a title to show above the action sheet
* `message` (string) - a message to show below the title
* `anchor` (number) - the node to which the action sheet should be anchored (used for iPad)
* `tintColor` (string) - the [color](/docs/next/colors) used for non-destructive button titles
* `disabledButtonIndices` (array of numbers) - a list of button indices which should be disabled
* `userInterfaceStyle` (string) - the interface style used for the action sheet, can be set to `light` or `dark`, otherwise the default system style will be used

The 'callback' function takes one parameter, the zero-based index of the selected item.

Minimal example:

React TSX

```
ActionSheetIOS.showActionSheetWithOptions(

  {

    options: ['Cancel', 'Remove'],

    destructiveButtonIndex: 1,

    cancelButtonIndex: 0,

  },

  buttonIndex => {

    if (buttonIndex === 1) {

      /* destructive action */

    }

  },

);
```

***

### `dismissActionSheet()`[​](#dismissactionsheet "Direct link to dismissactionsheet")

React TSX

```
static dismissActionSheet();
```

Dismisses the most upper iOS action sheet presented, if no action sheet is present a warning is displayed.

***

### `showShareActionSheetWithOptions()`[​](#showshareactionsheetwithoptions "Direct link to showshareactionsheetwithoptions")

React TSX

```
static showShareActionSheetWithOptions: (

  options: ShareActionSheetIOSOptions,

  failureCallback: (error: Error) => void,

  successCallback: (success: boolean, method: string) => void,

);
```

----
url: https://reactnative.dev/docs/next/easing
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/easing)** (0.87).

Version: Next

The `Easing` module implements common easing functions. This module is used by [`Animated.timing()`](/docs/next/animated#timing) to convey physically believable motion in animations.

You can find a visualization of some common easing functions at <https://easings.net/>

### Predefined animations[​](#predefined-animations "Direct link to Predefined animations")

The `Easing` module provides several predefined animations through the following methods:

* [`back`](/docs/next/easing#back) provides a basic animation where the object goes slightly back before moving forward
* [`bounce`](/docs/next/easing#bounce) provides a bouncing animation
* [`ease`](/docs/next/easing#ease) provides a basic inertial animation
* [`elastic`](/docs/next/easing#elastic) provides a basic spring interaction

### Standard functions[​](#standard-functions "Direct link to Standard functions")

Three standard easing functions are provided:

* [`linear`](/docs/next/easing#linear)
* [`quad`](/docs/next/easing#quad)
* [`cubic`](/docs/next/easing#cubic)

The [`poly`](/docs/next/easing#poly) function can be used to implement quartic, quintic, and other higher power functions.

### Additional functions[​](#additional-functions "Direct link to Additional functions")

Additional mathematical functions are provided by the following methods:

* [`bezier`](/docs/next/easing#bezier) provides a cubic bezier curve
* [`circle`](/docs/next/easing#circle) provides a circular function
* [`sin`](/docs/next/easing#sin) provides a sinusoidal function
* [`exp`](/docs/next/easing#exp) provides an exponential function

The following helpers are used to modify other easing functions.

* [`in`](/docs/next/easing#in) runs an easing function forwards
* [`inOut`](/docs/next/easing#inout) makes any easing function symmetrical
* [`out`](/docs/next/easing#out) runs an easing function backwards

## Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `step0()`[​](#step0 "Direct link to step0")

React TSX

```
static step0(n: number);
```

A stepping function, returns 1 for any positive value of `n`.

***

### `step1()`[​](#step1 "Direct link to step1")

React TSX

```
static step1(n: number);
```

A stepping function, returns 1 if `n` is greater than or equal to 1.

***

### `linear()`[​](#linear "Direct link to linear")

React TSX

```
static linear(t: number);
```

A linear function, `f(t) = t`. Position correlates to elapsed time one to one.

<https://cubic-bezier.com/#0,0,1,1>

***

### `ease()`[​](#ease "Direct link to ease")

React TSX

```
static ease(t: number);
```

A basic inertial interaction, similar to an object slowly accelerating to speed.

<https://cubic-bezier.com/#.42,0,1,1>

***

### `quad()`[​](#quad "Direct link to quad")

React TSX

```
static quad(t: number);
```

A quadratic function, `f(t) = t * t`. Position equals the square of elapsed time.

<https://easings.net/#easeInQuad>

***

### `cubic()`[​](#cubic "Direct link to cubic")

React TSX

```
static cubic(t: number);
```

A cubic function, `f(t) = t * t * t`. Position equals the cube of elapsed time.

<https://easings.net/#easeInCubic>

***

### `poly()`[​](#poly "Direct link to poly")

React TSX

```
static poly(n: number);
```

A power function. Position is equal to the Nth power of elapsed time.

n = 4: <https://easings.net/#easeInQuart> n = 5: <https://easings.net/#easeInQuint>

***

### `sin()`[​](#sin "Direct link to sin")

React TSX

```
static sin(t: number);
```

A sinusoidal function.

<https://easings.net/#easeInSine>

***

### `circle()`[​](#circle "Direct link to circle")

React TSX

```
static circle(t: number);
```

A circular function.

<https://easings.net/#easeInCirc>

***

### `exp()`[​](#exp "Direct link to exp")

React TSX

```
static exp(t: number);
```

An exponential function.

<https://easings.net/#easeInExpo>

***

### `elastic()`[​](#elastic "Direct link to elastic")

React TSX

```
static elastic(bounciness: number);
```

A basic elastic interaction, similar to a spring oscillating back and forth.

Default bounciness is 1, which overshoots a little bit once. 0 bounciness doesn't overshoot at all, and bounciness of N > 1 will overshoot about N times.

<https://easings.net/#easeInElastic>

***

### `back()`[​](#back "Direct link to back")

React TSX

```
static back(s)
```

Use with `Animated.parallel()` to create a basic effect where the object animates back slightly as the animation starts.

***

### `bounce()`[​](#bounce "Direct link to bounce")

React TSX

```
static bounce(t: number);
```

Provides a basic bouncing effect.

<https://easings.net/#easeInBounce>

***

### `bezier()`[​](#bezier "Direct link to bezier")

React TSX

```
static bezier(x1: number, y1: number, x2: number, y2: number);
```

Provides a cubic bezier curve, equivalent to CSS Transitions' `transition-timing-function`.

A useful tool to visualize cubic bezier curves can be found at <https://cubic-bezier.com/>

***

### `in()`[​](#in "Direct link to in")

React TSX

```
static in(easing: number);
```

Runs an easing function forwards.

***

### `out()`[​](#out "Direct link to out")

React TSX

```
static out(easing: number);
```

Runs an easing function backwards.

***

### `inOut()`[​](#inout "Direct link to inout")

React TSX

```
static inOut(easing: number);
```

----
url: https://reactnative.dev/docs/next/rect
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/rect)** (0.87).

Version: Next

`Rect` accepts numeric pixel values to describe how far to extend a rectangular area. These values are added to the original area's size to expand it.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

    bottom: 20,

    left: null,

    right: undefined,

    top: 50

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `bottom`[​](#bottom "Direct link to bottom")

| Type                        | Required |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

### `left`[​](#left "Direct link to left")

| Type                        | Required |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

### `right`[​](#right "Direct link to right")

| Type                        | Required |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

### `top`[​](#top "Direct link to top")

| Type                        | Required |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

## Used by[​](#used-by "Direct link to Used by")

* [`Image`](/docs/next/image)
* [`Pressable`](/docs/next/pressable)
* [`Text`](/docs/next/text)
* [`TouchableWithoutFeedback`](/docs/next/touchablewithoutfeedback)

----
url: https://reactnative.dev/docs/next/shadow-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/shadow-props)** (0.87).

Version: Next

* TypeScript
* JavaScript

***

# Reference

There are 3 sets of shadow APIs in React Native:

* `boxShadow`: A View style prop and a spec-compliant implementation of the [web style prop of the same name](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow).
* `dropShadow`: A specific filter function available as part of the [`filter`](/docs/next/view-style-props#filter) View style prop.

See [View Style Props](/docs/next/view-style-props#boxshadow) for documentation.

### `dropShadow`Android[​](#dropshadow-android "Direct link to dropshadow-android")

See [View Style Props](/docs/next/view-style-props#filter) for documentation.

### `shadowColor`[​](#shadowcolor "Direct link to shadowcolor")

Sets the drop shadow color.

This property will only work on Android API 28 and above. For similar functionality on lower Android APIs, use the [`elevation` property](/docs/next/view-style-props#elevation-android).

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `shadowOffset`iOS[​](#shadowoffset-ios "Direct link to shadowoffset-ios")

Sets the drop shadow offset.

| Type                                     |
| ---------------------------------------- |
| object: `{width: number,height: number}` |

***

### `shadowOpacity`iOS[​](#shadowopacity-ios "Direct link to shadowopacity-ios")

Sets the drop shadow opacity (multiplied by the color's alpha component).

| Type   |
| ------ |
| number |

***

### `shadowRadius`iOS[​](#shadowradius-ios "Direct link to shadowradius-ios")

Sets the drop shadow blur radius.

| Type   |
| ------ |
| number |

* [Props](#props)

  * [`boxShadow`](#boxshadow)
  * [`dropShadow`](#dropshadow-android)

    [Android](#dropshadow-android)
  * [`shadowColor`](#shadowcolor)
  * [`shadowOffset`](#shadowoffset-ios)

    [iOS](#shadowoffset-ios)
  * [`shadowOpacity`](#shadowopacity-ios)

    [iOS](#shadowopacity-ios)
  * [`shadowRadius`](#shadowradius-ios)

    [iOS](#shadowradius-ios)

----
url: https://reactnative.dev/docs/next/the-new-architecture/codegen-cli
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/codegen-cli)** (0.87).

Version: Next

Calling Gradle or manually calling a script might be hard to remember and it requires a lot of ceremony.

To simplify it, we created a CLI tool that can help you running those tasks: the **Codegen** cli. This command runs [@react-native/codegen](https://www.npmjs.com/package/@react-native/codegen) for your project. The following options are available:

```
npx @react-native-community/cli codegen --help

Usage: rnc-cli codegen [options]



Options:

  --verbose            Increase logging verbosity

  --path <path>        Path to the React Native project root. (default: "/Users/MyUsername/projects/my-app")

  --platform <string>  Target platform. Supported values: "android", "ios", "all". (default: "all")

  --outputPath <path>  Path where generated artifacts will be output to.

  -h, --help           display help for command
```

## Examples[​](#examples "Direct link to Examples")

* Read `package.json` from the current working directory, generate code based on its codegenConfig.

```
npx @react-native-community/cli codegen
```

* Read `package.json` from the current working directory, generate iOS code in the location defined in the codegenConfig.

```
npx @react-native-community/cli codegen --platform ios
```

* Read `package.json` from `third-party/some-library`, generate Android code in `third-party/some-library/android/generated`.

```
npx @react-native-community/cli codegen \

    --path third-party/some-library \

    --platform android \

    --outputPath third-party/some-library/android/generated
```

----
url: https://reactnative.dev/docs/network
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may need to fetch a chunk of static content from another server.

## Using Fetch[​](#using-fetch "Direct link to Using Fetch")

React Native provides the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for your networking needs. Fetch will seem familiar if you have used `XMLHttpRequest` or other networking APIs before. You may refer to MDN's guide on [Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) for additional information.

### Making requests[​](#making-requests "Direct link to Making requests")

In order to fetch content from an arbitrary URL, you can pass the URL to fetch:

TypeScript

```
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:

TypeScript

```
fetch('https://mywebsite.com/endpoint/', {

  method: 'POST',

  headers: {

    Accept: 'application/json',

    'Content-Type': 'application/json',

  },

  body: JSON.stringify({

    firstParam: 'yourValue',

    secondParam: 'yourOtherValue',

  }),

});
```

Take a look at the [Fetch Request docs](https://developer.mozilla.org/en-US/docs/Web/API/Request) for a full list of properties.

### Handling the response[​](#handling-the-response "Direct link to Handling the response")

The above examples show how you can make a request. In many cases, you will want to do something with the response.

Networking is an inherently asynchronous operation. Fetch method will return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that makes it straightforward to write code that works in an asynchronous manner:

TypeScript

```
const getMoviesFromApi = () => {

  return fetch('https://reactnative.dev/movies.json')

    .then(response => response.json())

    .then(json => {

      return json.movies;

    })

    .catch(error => {

      console.error(error);

    });

};
```

You can also use the `async` / `await` syntax in a React Native app:

TypeScript

```
const getMoviesFromApiAsync = async () => {

  try {

    const response = await fetch(

      'https://reactnative.dev/movies.json',

    );

    const json = await response.json();

    return json.movies;

  } catch (error) {

    console.error(error);

  }

};
```

```
const request = new XMLHttpRequest();

request.onreadystatechange = e => {

  if (request.readyState !== 4) {

    return;

  }



  if (request.status === 200) {

    console.log('success', request.responseText);

  } else {

    console.warn('error');

  }

};



request.open('GET', 'https://mywebsite.com/endpoint/');

request.send();
```

Caution

The security model for XMLHttpRequest is different than on web as there is no concept of [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) in native apps.

## WebSocket Support[​](#websocket-support "Direct link to WebSocket Support")

React Native also supports [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), a protocol which provides full-duplex communication channels over a single TCP connection.

TypeScript

```
const ws = new WebSocket('ws://host.com/path');



ws.onopen = () => {

  // connection opened

  ws.send('something'); // send a message

};



ws.onmessage = e => {

  // a message was received

  console.log(e.data);

};



ws.onerror = e => {

  // an error occurred

  console.log(e.message);

};



ws.onclose = e => {

  // connection closed

  console.log(e.code, e.reason);

};
```

```
#import <React/RCTHTTPRequestHandler.h>
```

`RCTSetCustomNSURLSessionConfigurationProvider` should be called early in the application life cycle such that it is readily available when needed by React, for instance:

Objective-C

```
-(void)application:(__unused UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {



  // set RCTSetCustomNSURLSessionConfigurationProvider

  RCTSetCustomNSURLSessionConfigurationProvider(^NSURLSessionConfiguration *{

     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

     // configure the session

     return configuration;

  });



  // set up React

  _bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];

}
```

----
url: https://reactnative.dev/docs/hermes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
const isHermes = () => !!global.HermesInternal;
```

```
npm run android -- --mode="release"
```

```
yarn android --mode release
```

* npm
* Yarn

```
npm run ios -- --mode="Release"
```

```
yarn ios --mode Release
```

This will compile JavaScript to Hermes Bytecode during build time which will improve your app's startup speed on device.

## Switching back to JavaScriptCore[​](#switching-back-to-javascriptcore "Direct link to Switching back to JavaScriptCore")

React Native also supports using JavaScriptCore as the [JavaScript engine](/docs/javascript-environment). Follow the instructions [from the community repository](https://github.com/react-native-community/javascriptcore) to opt-out of Hermes.

* [Bundled Hermes](#bundled-hermes)
* [Confirming Hermes is in use](#confirming-hermes-is-in-use)
* [Switching back to JavaScriptCore](#switching-back-to-javascriptcore)

----
url: https://reactnative.dev/docs/next/global-AbortSignal
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-AbortSignal)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) for more information.

The global `AbortSignal` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/more-resources
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/more-resources)** (0.87).

Version: Next

There’s always more to learn: developer workflows, shipping to app stores, internationalization, security and more.

## Where to go from here[​](#where-to-go-from-here "Direct link to Where to go from here")

* [Set up your environment](/docs/next/environment-setup)
* [Set up your development workflow](/docs/next/running-on-device)
* [Design and layout your app](/docs/next/flexbox)
* [Debug your app](/docs/next/debugging)
* [Make your app cross platform](/docs/next/platform-specific-code)

Interested in making your own Native Component or Module? Making modules for your own use case and sharing them with others on NPM and GitHub helps grow the React Native ecosystem and community! Read the guides to making your own Native Modules ([Android](/docs/next/legacy/native-modules-android), [iOS](/docs/next/legacy/native-modules-ios)) and Native Components ([Android](/docs/next/legacy/native-components-android), [iOS](/docs/next/legacy/native-components-ios)).

* [Where to go from here](#where-to-go-from-here)
* [Dive deep](#dive-deep)
* [IDEs](#ides)
* [Platforms to try](#platforms-to-try)
* [Example Apps](#example-apps)
* [Find, make, and share your own Native Components and TurboModules](#find-make-and-share-your-own-native-components-and-turbomodules)

----
url: https://reactnative.dev/docs/app-extensions
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

----
url: https://reactnative.dev/docs/fabric-native-components-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Now it's time to write some iOS platform code to be able to render the web view. The steps you need to follow are:

* Run Codegen.
* Write the code for the `RCTWebView`
* Register the `RCTWebView` in the application

### 1. Run Codegen[​](#1-run-codegen "Direct link to 1. Run Codegen")

You can [manually run](/docs/the-new-architecture/codegen-cli) the Codegen, however it's simpler to use the application you're going to demo the component in to do this for you.

```
cd ios

bundle install

bundle exec pod install
```

Importantly you will see logging output from Codegen, which we're going to use in Xcode to build our WebView native component.

warning

You should be careful about committing generated code to your repository. Generated code is specific to each version of React Native. Use npm [peerDependencies](https://nodejs.org/en/blog/npm/peer-dependencies) to restrict compatibility with version of React Native.

### 3. Write the `RCTWebView`[​](#3-write-the-rctwebview "Direct link to 3-write-the-rctwebview")

We need to prepare your iOS project using Xcode by completing these **5 steps**:

1. Open the CocoaPods generated Xcode Workspace:

```
cd ios

open Demo.xcworkspace
```

2. Right click on app and select `New Group`, call the new group `WebView`.

3) In the `WebView` group, create `New`→`File from Template`.

4. Use the `Objective-C File` template, and name it `RCTWebView`.

5) Repeat step 4 and create a header file named `RCTWebView.h`.

6) Rename `RCTWebView.m` → `RCTWebView.mm` making it an Objective-C++ file.

Demo/ios

```
Podfile

...

Demo

├── AppDelegate.swift

...

├── RCTWebView.h

└── RCTWebView.mm
```

After creating the header file and the implementation file, you can start implementing them.

This is the code for the `RCTWebView.h` file, which declares the component interface.

Demo/RCTWebView/RCTWebView\.h

```
#import <React/RCTViewComponentView.h>

#import <UIKit/UIKit.h>



NS_ASSUME_NONNULL_BEGIN



@interface RCTWebView : RCTViewComponentView



// You would declare native methods you'd want to access from the view here



@end



NS_ASSUME_NONNULL_END
```

This class defines an `RCTWebView` which extends the `RCTViewComponentView` class. This is the base class for all the native components and it is provided by React Native.

The code for the implementation file (`RCTWebView.mm`) is the following:

Demo/RCTWebView/RCTWebView\.mm

```
#import "RCTWebView.h"



#import <react/renderer/components/AppSpec/ComponentDescriptors.h>

#import <react/renderer/components/AppSpec/EventEmitters.h>

#import <react/renderer/components/AppSpec/Props.h>

#import <react/renderer/components/AppSpec/RCTComponentViewHelpers.h>

#import <WebKit/WebKit.h>



using namespace facebook::react;



@interface RCTWebView () <RCTCustomWebViewViewProtocol, WKNavigationDelegate>

@end



@implementation RCTWebView {

  NSURL * _sourceURL;

  WKWebView * _webView;

}



-(instancetype)init

{

  if(self = [super init]) {

    _webView = [WKWebView new];

    _webView.navigationDelegate = self;

    [self addSubview:_webView];

  }

  return self;

}



- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps

{

  const auto &oldViewProps = *std::static_pointer_cast<CustomWebViewProps const>(_props);

  const auto &newViewProps = *std::static_pointer_cast<CustomWebViewProps const>(props);



  // Handle your props here

  if (oldViewProps.sourceURL != newViewProps.sourceURL) {

    NSString *urlString = [NSString stringWithCString:newViewProps.sourceURL.c_str() encoding:NSUTF8StringEncoding];

    _sourceURL = [NSURL URLWithString:urlString];

    if ([self urlIsValid:newViewProps.sourceURL]) {

      [_webView loadRequest:[NSURLRequest requestWithURL:_sourceURL]];

    }

  }



  [super updateProps:props oldProps:oldProps];

}



-(void)layoutSubviews

{

  [super layoutSubviews];

  _webView.frame = self.bounds;



}



#pragma mark - WKNavigationDelegate



-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{

  CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Success};

  self.eventEmitter.onScriptLoaded(result);

}



- (BOOL)urlIsValid:(std::string)propString

{

  if (propString.length() > 0 && !_sourceURL) {

    CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Error};



    self.eventEmitter.onScriptLoaded(result);

    return NO;

  }

  return YES;

}



// Event emitter convenience method

- (const CustomWebViewEventEmitter &)eventEmitter

{

  return static_cast<const CustomWebViewEventEmitter &>(*_eventEmitter);

}



+ (ComponentDescriptorProvider)componentDescriptorProvider

{

  return concreteComponentDescriptorProvider<CustomWebViewComponentDescriptor>();

}



@end
```

----
url: https://reactnative.dev/docs/global-PerformanceResourceTiming
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

----
url: https://reactnative.dev/docs/metro
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
const {

  getDefaultConfig,

  mergeConfig,

} = require('@react-native/metro-config');



/**

 * Metro configuration

 * https://metrobundler.dev/docs/configuration

 *

 * @type {import('metro-config').MetroConfig}

 */

const config = {};



module.exports = mergeConfig(getDefaultConfig(__dirname), config);
```

Metro options you wish to customize can be done so within the `config` object.

### Advanced: Using a config function[​](#advanced-using-a-config-function "Direct link to Advanced: Using a config function")

Exporting a config function is an opt-in to managing the final config yourself — **Metro will not apply any internal defaults**. This pattern can be useful when needing to read the base default config object from Metro or to set options dynamically.

info

**From `@react-native/metro-config` 0.72.1**, it is no longer necessary to use a config function to access the complete default config. See the **Tip** section below.

JavaScript

```
const {

  getDefaultConfig,

  mergeConfig,

} = require('@react-native/metro-config');



module.exports = function (baseConfig) {

  const defaultConfig = mergeConfig(

    baseConfig,

    getDefaultConfig(__dirname),

  );

  const {

    resolver: {assetExts, sourceExts},

  } = defaultConfig;



  return mergeConfig(defaultConfig, {

    resolver: {

      assetExts: assetExts.filter(ext => ext !== 'svg'),

      sourceExts: [...sourceExts, 'svg'],

    },

  });

};
```

tip

Using a config function is for advanced use cases. A simpler method than the above, e.g. for customising `sourceExts`, would be to read these defaults from `@react-native/metro-config`.

**Alternative**

JavaScript

```
const defaultConfig = getDefaultConfig(__dirname);



const config = {

  resolver: {

    sourceExts: [...defaultConfig.resolver.sourceExts, 'svg'],

  },

};



module.exports = mergeConfig(defaultConfig, config);
```

**However!**, we recommend copying and editing when overriding these config values — placing the source of truth in your config file.

✅ **Recommended**

JavaScript

```
const config = {

  resolver: {

    sourceExts: ['js', 'ts', 'tsx', 'svg'],

  },

};
```

## Learn more about Metro[​](#learn-more-about-metro "Direct link to Learn more about Metro")

* [Metro website](https://metrobundler.dev/)
* [Video: "Metro & React Native DevX" talk at App.js 2023](https://www.youtube.com/watch?v=c9D4pg0y9cI)

- [Configuring Metro](#configuring-metro)
  * [Advanced: Using a config function](#advanced-using-a-config-function)
- [Learn more about Metro](#learn-more-about-metro)

----
url: https://reactnative.dev/docs/the-new-architecture/advanced-topics-modules
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This document contains a set of advanced topics to implement more complex functionalities of Native Modules. It is recommended to first read the [Codegen](/docs/the-new-architecture/what-is-codegen) section and the guides on [Native Modules](/docs/turbo-native-modules-introduction).

This guide will cover the following topics:

* [Add custom C++ types to your C++ modules](/docs/the-new-architecture/custom-cxx-types)
* [Use Swift in your Module](/docs/next/the-new-architecture/turbo-modules-with-swift)
* [Emit custom events from your Native Modules](/docs/next/the-new-architecture/native-modules-custom-events)
* [Native Modules Lifecycle](/docs/next/the-new-architecture/native-modules-lifecycle)

----
url: https://reactnative.dev/docs/next/alertios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/alertios)** (0.87).

Version: Next

Removed from React Native

Use [`Alert`](/docs/next/alert) instead.

----
url: https://reactnative.dev/docs/next/global-FormData
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-FormData)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/FormData) for more information.

The global `FormData` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/global-PerformanceEntry
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-PerformanceEntry)** (0.87).

Version: Next

The global [`PerformanceEntry`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/fabric-native-components-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/fabric-native-components-android)** (0.87).

Version: Next

```
cd android

./gradlew generateCodegenArtifactsFromSchema
```

```
package com.webview;



import android.content.Context;

import android.util.AttributeSet;

import android.webkit.WebView;

import android.webkit.WebViewClient;



import com.facebook.react.bridge.Arguments;

import com.facebook.react.bridge.WritableMap;

import com.facebook.react.bridge.ReactContext;

import com.facebook.react.uimanager.UIManagerHelper;

import com.facebook.react.uimanager.events.Event;



public class ReactWebView extends WebView {

  public ReactWebView(Context context) {

    super(context);

    configureComponent();

  }



  public ReactWebView(Context context, AttributeSet attrs) {

    super(context, attrs);

    configureComponent();

  }



  public ReactWebView(Context context, AttributeSet attrs, int defStyleAttr) {

    super(context, attrs, defStyleAttr);

    configureComponent();

  }



  private void configureComponent() {

    this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    this.setWebViewClient(new WebViewClient() {

      @Override

      public void onPageFinished(WebView view, String url) {

        emitOnScriptLoaded(OnScriptLoadedEventResult.success);

      }

    });

  }



  public void emitOnScriptLoaded(OnScriptLoadedEventResult result) {

    ReactContext reactContext = (ReactContext) context;

    int surfaceId = UIManagerHelper.getSurfaceId(reactContext);

    EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());

    WritableMap payload = Arguments.createMap();

    payload.putString("result", result.name());



    OnScriptLoadedEvent event = new OnScriptLoadedEvent(surfaceId, getId(), payload);

    if (eventDispatcher != null) {

      eventDispatcher.dispatchEvent(event);

    }

  }



  public enum OnScriptLoadedEventResult {

    success,

    error

  }



  private class OnScriptLoadedEvent extends Event<OnScriptLoadedEvent> {

    private final WritableMap payload;



    OnScriptLoadedEvent(int surfaceId, int viewId, WritableMap payload) {

      super(surfaceId, viewId);

      this.payload = payload;

    }



    @Override

    public String getEventName() {

      return "onScriptLoaded";

    }



    @Override

    public WritableMap getEventData() {

      return payload;

    }

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebView\.kt

```
package com.webview



import android.content.Context

import android.util.AttributeSet

import android.webkit.WebView

import android.webkit.WebViewClient

import com.facebook.react.bridge.Arguments

import com.facebook.react.bridge.WritableMap

import com.facebook.react.bridge.ReactContext

import com.facebook.react.uimanager.UIManagerHelper

import com.facebook.react.uimanager.events.Event



class ReactWebView: WebView {

  constructor(context: Context) : super(context) {

    configureComponent()

  }



  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {

    configureComponent()

  }



  constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {

    configureComponent()

  }



  private fun configureComponent() {

    this.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)

    this.webViewClient = object : WebViewClient() {

      override fun onPageFinished(view: WebView, url: String) {

        emitOnScriptLoaded(OnScriptLoadedEventResult.success)

      }

    }

  }



  fun emitOnScriptLoaded(result: OnScriptLoadedEventResult) {

    val reactContext = context as ReactContext

    val surfaceId = UIManagerHelper.getSurfaceId(reactContext)

    val eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id)

    val payload =

        Arguments.createMap().apply {

          putString("result", result.name)

        }

    val event = OnScriptLoadedEvent(surfaceId, id, payload)



    eventDispatcher?.dispatchEvent(event)

  }



  enum class OnScriptLoadedEventResult {

    success,

    error;

  }



  inner class OnScriptLoadedEvent(

      surfaceId: Int,

      viewId: Int,

      private val payload: WritableMap

  ) : Event<OnScriptLoadedEvent>(surfaceId, viewId) {

    override fun getEventName() = "onScriptLoaded"



    override fun getEventData() = payload

  }

}
```

```
package com.webview;



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.annotations.ReactModule;

import com.facebook.react.uimanager.SimpleViewManager;

import com.facebook.react.uimanager.ThemedReactContext;

import com.facebook.react.uimanager.ViewManagerDelegate;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;

import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;



import java.util.HashMap;

import java.util.Map;



@ReactModule(name = ReactWebViewManager.REACT_CLASS)

class ReactWebViewManager extends SimpleViewManager<ReactWebView> implements CustomWebViewManagerInterface<ReactWebView> {

  private final CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> delegate =

          new CustomWebViewManagerDelegate<>(this);



  @Override

  public ViewManagerDelegate<ReactWebView> getDelegate() {

    return delegate;

  }



  @Override

  public String getName() {

    return REACT_CLASS;

  }



  @Override

  public ReactWebView createViewInstance(ThemedReactContext context) {

    return new ReactWebView(context);

  }



  @ReactProp(name = "sourceUrl")

  @Override

  public void setSourceURL(ReactWebView view, String sourceURL) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error);

      return;

    }

    view.loadUrl(sourceURL, new HashMap<>());

  }



  public static final String REACT_CLASS = "CustomWebView";



  @Override

  public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {

    Map<String, Object> map = new HashMap<>();

    Map<String, Object> bubblingMap = new HashMap<>();

    bubblingMap.put("phasedRegistrationNames", new HashMap<String, String>() {{

      put("bubbled", "onScriptLoaded");

      put("captured", "onScriptLoadedCapture");

    }});

    map.put("onScriptLoaded", bubblingMap);

    return map;

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebViewManager.kt

```
package com.webview



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.annotations.ReactModule;

import com.facebook.react.uimanager.SimpleViewManager;

import com.facebook.react.uimanager.ThemedReactContext;

import com.facebook.react.uimanager.ViewManagerDelegate;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;

import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;



@ReactModule(name = ReactWebViewManager.REACT_CLASS)

class ReactWebViewManager(context: ReactApplicationContext) : SimpleViewManager<ReactWebView>(), CustomWebViewManagerInterface<ReactWebView> {

  private val delegate: CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> =

    CustomWebViewManagerDelegate(this)



  override fun getDelegate(): ViewManagerDelegate<ReactWebView> = delegate



  override fun getName(): String = REACT_CLASS



  override fun createViewInstance(context: ThemedReactContext): ReactWebView = ReactWebView(context)



  @ReactProp(name = "sourceUrl")

  override fun setSourceURL(view: ReactWebView, sourceURL: String?) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error)

      return;

    }

    view.loadUrl(sourceURL, emptyMap())

  }



  companion object {

    const val REACT_CLASS = "CustomWebView"

  }



  override fun getExportedCustomBubblingEventTypeConstants(): Map<String, Any> =

      mapOf(

          "onScriptLoaded" to

              mapOf(

                  "phasedRegistrationNames" to

                      mapOf(

                          "bubbled" to "onScriptLoaded",

                          "captured" to "onScriptLoadedCapture"

                      )))

}
```

```
package com.webview;



import com.facebook.react.BaseReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.model.ReactModuleInfo;

import com.facebook.react.module.model.ReactModuleInfoProvider;

import com.facebook.react.uimanager.ViewManager;



import java.util.Collections;

import java.util.HashMap;

import java.util.List;

import java.util.Map;



public class ReactWebViewPackage extends BaseReactPackage {

  @Override

  public List<ViewManager<?, ?>> createViewManagers(ReactApplicationContext reactContext) {

    return Collections.singletonList(new ReactWebViewManager(reactContext));

  }



  @Override

  public NativeModule getModule(String s, ReactApplicationContext reactApplicationContext) {

    if (ReactWebViewManager.REACT_CLASS.equals(s)) {

      return new ReactWebViewManager(reactApplicationContext);

    }

    return null;

  }



  @Override

  public ReactModuleInfoProvider getReactModuleInfoProvider() {

    return new ReactModuleInfoProvider() {

      @Override

      public Map<String, ReactModuleInfo> getReactModuleInfos() {

        Map<String, ReactModuleInfo> map = new HashMap<>();

        map.put(ReactWebViewManager.REACT_CLASS, new ReactModuleInfo(

                ReactWebViewManager.REACT_CLASS, // name

                ReactWebViewManager.REACT_CLASS, // className

                false,                           // canOverrideExistingModule

                false,                           // needsEagerInit

                false,                           // isCxxModule

                true                             // isTurboModule

        ));

        return map;

      }

    };

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebViewPackage.kt

```
package com.webview



import com.facebook.react.BaseReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.module.model.ReactModuleInfo

import com.facebook.react.module.model.ReactModuleInfoProvider

import com.facebook.react.uimanager.ViewManager



class ReactWebViewPackage : BaseReactPackage() {

  override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {

    return listOf(ReactWebViewManager(reactContext))

  }



  override fun getModule(s: String, reactApplicationContext: ReactApplicationContext): NativeModule? {

    when (s) {

      ReactWebViewManager.REACT_CLASS -> ReactWebViewManager(reactApplicationContext)

    }

    return null

  }



  override fun getReactModuleInfoProvider(): ReactModuleInfoProvider = ReactModuleInfoProvider {

    mapOf(ReactWebViewManager.REACT_CLASS to ReactModuleInfo(

      name = ReactWebViewManager.REACT_CLASS,

      className = ReactWebViewManager.REACT_CLASS,

      canOverrideExistingModule = false,

      needsEagerInit = false,

      isCxxModule = false,

      isTurboModule = true,

    )

    )

  }

}
```

```
package com.demo



import android.app.Application

import com.facebook.react.PackageList

import com.facebook.react.ReactApplication

import com.facebook.react.ReactHost

import com.facebook.react.ReactNativeHost

import com.facebook.react.ReactPackage

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

import com.facebook.react.defaults.DefaultReactNativeHost

import com.facebook.react.soloader.OpenSourceMergedSoMapping

import com.facebook.soloader.SoLoader

import com.webview.ReactWebViewPackage



class MainApplication : Application(), ReactApplication {



  override val reactNativeHost: ReactNativeHost =

      object : DefaultReactNativeHost(this) {

        override fun getPackages(): List<ReactPackage> =

            PackageList(this).packages.apply {

              add(ReactWebViewPackage())

            }



        override fun getJSMainModuleName(): String = "index"



        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG



        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

      }



  override val reactHost: ReactHost

    get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

    SoLoader.init(this, OpenSourceMergedSoMapping)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      load()

    }

  }

}
```

* [1. Run Codegen through Gradle](#1-run-codegen-through-gradle)
* [2. Write the `ReactWebView`](#2-write-the-reactwebview)
* [3. Write the `WebViewManager`](#3-write-the-webviewmanager)
* [4. Write the `ReactWebViewPackage`](#4-write-the-reactwebviewpackage)
* [5. Register the `ReactWebViewPackage` in the application](#5-register-the-reactwebviewpackage-in-the-application)

----
url: https://reactnative.dev/docs/next/transforms
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/transforms)** (0.87).

Version: Next

Transforms are style properties that will help you modify the appearance and position of your components using 2D or 3D transformations. However, once you apply transforms, the layouts remain the same around the transformed component hence it might overlap with the nearby components. You can apply margin to the transformed component, the nearby components or padding to the container to prevent such overlaps.

## Example[​](#example "Direct link to Example")

***

# Reference

## Transform[​](#transform "Direct link to Transform")

`transform` accepts an array of transformation objects or space-separated string values. Each object specifies the property that will be transformed as the key, and the value to use in the transformation. Objects should not be combined. Use a single key/value pair per object.

The rotate transformations require a string so that the transform may be expressed in degrees (deg) or radians (rad). For example:

JavaScript

```
{

  transform: [{rotateX: '45deg'}, {rotateZ: '0.785398rad'}],

}
```

The same could also be achieved using a space-separated string:

JavaScript

```
{

  transform: 'rotateX(45deg) rotateZ(0.785398rad)',

}
```

The skew transformations require a string so that the transform may be expressed in degrees (deg). For example:

JavaScript

```
{

  transform: [{skewX: '45deg'}],

}
```

The translate transformations (`translateX` and `translateY`) accept numbers (points) or percentage strings (e.g. `'50%'`, `'100%'`). When using percentages, the offset is relative to the element's width (for `translateX`) or height (for `translateY`). Percentage translation is supported on the [New Architecture](/architecture/landing-page). For example:

JavaScript

```
{

  transform: [{translateX: '50%'}, {translateY: 100}],

}
```

### Matrix Transform[​](#matrix-transform "Direct link to Matrix Transform")

The `matrix` transform accepts a 4x4 transformation matrix as an array of 16 numbers. This allows you to apply complex transformations that combine translation, rotation, scaling, and skewing in a single operation.

The matrix is specified in column-major order:

JavaScript

```
{

  transform: [

    {

      matrix: [

        scaleX,

        skewY,

        0,

        0,

        skewX,

        scaleY,

        0,

        0,

        0,

        0,

        1,

        0,

        translateX,

        translateY,

        0,

        1,

      ],

    },

  ];

}
```

For example, to apply a combination of scale and skew:

JavaScript

```
{

  transform: [

    {

      matrix: [

        1, 0.5, 0, 0, 0.5, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,

      ],

    },

  ];

}
```

note

Matrix transforms are useful when you need to apply pre-calculated transformation matrices, such as those from animation libraries or when building UI editor applications. For basic transformations, it's recommended to use the individual transform properties (scale, rotate, translate, etc.) as they are more readable.

| Type                                                                                                                                                                                                                                                                                                                              | Required |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| array of objects: `{matrix: number[]}`, `{perspective: number}`, `{rotate: string}`, `{rotateX: string}`, `{rotateY: string}`, `{rotateZ: string}`, `{scale: number}`, `{scaleX: number}`, `{scaleY: number}`, `{translateX: number \| string}`, `{translateY: number \| string}`, `{skewX: string}`, `{skewY: string}` or string | No       |

***

### 🗑️ `decomposedMatrix`, `rotation`, `scaleX`, `scaleY`, `transformMatrix`, `translateX`, `translateY`[​](#️-decomposedmatrix-rotation-scalex-scaley-transformmatrix-translatex-translatey "Direct link to ️-decomposedmatrix-rotation-scalex-scaley-transformmatrix-translatex-translatey")

Deprecated

Use the [`transform`](/docs/next/transforms#transform) prop instead.

```
{

  transformOrigin: '20px',

  transformOrigin: 'bottom',

}
```

#### Two-value syntax:[​](#two-value-syntax "Direct link to Two-value syntax:")

* First value (x-offset) must be a `px`, a `percentage`, or one of the keywords `left`, `center`, and `right`.
* The second value (y-offset) must be a `px`, a `percentage`, or one of the keywords `top`, `center`, and `bottom`.

JavaScript

```
{

  transformOrigin: '10px 2px',

  transformOrigin: 'left top',

  transformOrigin: 'top right',

}
```

#### Three-value syntax:[​](#three-value-syntax "Direct link to Three-value syntax:")

* The first two values are the same as for the two-value syntax.
* The third value (z-offset) must be a `px`. It always represents the Z offset.

JavaScript

```
{

  transformOrigin: '2px 30% 10px',

  transformOrigin: 'right bottom 20px',

}
```

#### Array syntax[​](#array-syntax "Direct link to Array syntax")

`transformOrigin` also supports an array syntax. It makes it convenient to use it with Animated APIs. It also avoids string parsing, so should be more efficient.

JavaScript

```
{

  // Using numeric values

  transformOrigin: [10, 30, 40],

  // Mixing numeric and percentage values

  transformOrigin: [10, '20%', 0],

}
```

----
url: https://reactnative.dev/docs/out-of-tree-platforms
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
{

  "rnpm": {

    "haste": {

      "providesModuleNodeModules": ["react-native-example"],

      "platforms": ["example"]

    }

  }

}
```

`"providesModuleNodeModules"` is an array of modules that will get added to the Haste module search path, and `"platforms"` is an array of platform suffixes that will be added as valid platforms.

* [Creating your own React Native platform](#creating-your-own-react-native-platform)
  * [Bundling](#bundling)

----
url: https://reactnative.dev/docs/legacy/local-library-setup
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

A local library is a library containing views or modules that's local to your app and not published to a registry. This is different from the traditional setup for view and modules in the sense that a local library is decoupled from your app's native code.

The local library is created outside of the `android/` and `ios/` folders and makes use of autolinking to integrate with your app. The structure with a local library may look like this:

Plaintext

```
MyApp

├── node_modules

├── modules <-- folder for your local libraries

│ └── awesome-module <-- your local library

├── android

├── ios

├── src

├── index.js

└── package.json
```

Since a local library's code exists outside of `android/` and `ios/` folders, it makes it easier to upgrade React Native versions in the future, copy to other projects etc.

To create local library we will use [create-react-native-library](https://callstack.github.io/react-native-builder-bob/create). This tool contains all the necessary templates.

### Getting Started[​](#getting-started "Direct link to Getting Started")

Inside your React Native application's root folder, run the following command:

```
npx create-react-native-library@latest awesome-module
```

Where `awesome-module` is the name you would like for the new module. After going through the prompts, you will have a new folder called `modules` in your project's root directory which contains the new module.

### Linking[​](#linking "Direct link to Linking")

By default, the generated library is automatically linked to the project using `link:` protocol when using Yarn and `file:` when using npm:

* npm
* Yarn

JSON

```
"dependencies": {

  "awesome-module": "file:./modules/awesome-module"

}
```

JSON

```
"dependencies": {

  "awesome-module": "link:./modules/awesome-module"

}
```

This creates a symlink to the library under `node_modules` which makes autolinking work.

### Installing dependencies[​](#installing-dependencies "Direct link to Installing dependencies")

To link the module you need to install dependencies:

* npm
* Yarn

```
npm install
```

```
yarn install
```

### Using module inside your app[​](#using-module-inside-your-app "Direct link to Using module inside your app")

To use the module inside your app, you can import it by its name:

JavaScript

```
import {multiply} from 'awesome-module';
```

* [Getting Started](#getting-started)
* [Linking](#linking)
* [Installing dependencies](#installing-dependencies)
* [Using module inside your app](#using-module-inside-your-app)

----
url: https://reactnative.dev/docs/toastandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `show()`[​](#show "Direct link to show")

React TSX

```
static show(message: string, duration: number);
```

***

### `showWithGravity()`[​](#showwithgravity "Direct link to showwithgravity")

This property will only work on Android API 29 and below. For similar functionality on higher Android APIs, consider using snackbar or notification.

React TSX

```
static showWithGravity(message: string, duration: number, gravity: number);
```

***

### `showWithGravityAndOffset()`[​](#showwithgravityandoffset "Direct link to showwithgravityandoffset")

This property will only work on Android API 29 and below. For similar functionality on higher Android APIs, consider using snackbar or notification.

React TSX

```
static showWithGravityAndOffset(

  message: string,

  duration: number,

  gravity: number,

  xOffset: number,

  yOffset: number,

);
```

## Properties[​](#properties "Direct link to Properties")

### `SHORT`[​](#short "Direct link to short")

Indicates the duration on the screen.

React TSX

```
static SHORT: number;
```

***

### `LONG`[​](#long "Direct link to long")

Indicates the duration on the screen.

React TSX

```
static LONG: number;
```

***

### `TOP`[​](#top "Direct link to top")

Indicates the position on the screen.

React TSX

```
static TOP: number;
```

***

### `BOTTOM`[​](#bottom "Direct link to bottom")

Indicates the position on the screen.

React TSX

```
static BOTTOM: number;
```

***

### `CENTER`[​](#center "Direct link to center")

Indicates the position on the screen.

React TSX

```
static CENTER: number;
```

----
url: https://reactnative.dev/docs/next/global-WebSocket
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-WebSocket)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) for more information.

The global `WebSocket` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/animations
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/animations)** (0.87).

Version: Next

Animations are very important to create a great user experience. Stationary objects must overcome inertia as they start moving. Objects in motion have momentum and rarely come to a stop immediately. Animations allow you to convey physically believable motion in your interface.

React Native provides two complementary animation systems: [`Animated`](/docs/next/animations#animated-api) for granular and interactive control of specific values, and [`LayoutAnimation`](/docs/next/animations#layoutanimation-api) for animated global layout transactions.

## `Animated` API[​](#animated-api "Direct link to animated-api")

The [`Animated`](/docs/next/animated) API is designed to concisely express a wide variety of interesting animation and interaction patterns in a very performant way. `Animated` focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and `start`/`stop` methods to control time-based animation execution.

`Animated` provides several animation types, the most commonly used one being [`Animated.timing()`](/docs/next/animated#timing). It supports animating a value over time using one of various predefined easing functions, or you can use your own. Easing functions are typically used in animation to convey gradual acceleration and deceleration of objects.

By default, `timing` will use an easeInOut curve that conveys gradual acceleration to full speed and concludes by gradually decelerating to a stop. You can specify a different easing function by passing an `easing` parameter. Custom `duration` or even a `delay` before the animation starts is also supported.

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:

React TSX

```
Animated.timing(this.state.xPosition, {

  toValue: 100,

  easing: Easing.back(),

  duration: 2000,

  useNativeDriver: true,

}).start();
```

Take a look at the [Configuring animations](/docs/next/animated#configuring-animations) section of the `Animated` API reference to learn more about all the config parameters supported by the built-in animations.

### Composing animations[​](#composing-animations "Direct link to Composing animations")

Animations can be combined and played in sequence or in parallel. Sequential animations can play immediately after the previous animation has finished, or they can start after a specified delay. The `Animated` API provides several methods, such as `sequence()` and `delay()`, each of which take an array of animations to execute and automatically calls `start()`/`stop()` as needed.

For example, the following animation coasts to a stop, then it springs back while twirling in parallel:

React TSX

```
Animated.sequence([

  // decay, then spring to start and twirl

  Animated.decay(position, {

    // coast to a stop

    velocity: {x: gestureState.vx, y: gestureState.vy}, // velocity from gesture release

    deceleration: 0.997,

    useNativeDriver: true,

  }),

  Animated.parallel([

    // after decay, in parallel:

    Animated.spring(position, {

      toValue: {x: 0, y: 0}, // return to start

      useNativeDriver: true,

    }),

    Animated.timing(twirl, {

      // and twirl

      toValue: 360,

      useNativeDriver: true,

    }),

  ]),

]).start(); // start the sequence group
```

If one animation is stopped or interrupted, then all other animations in the group are also stopped. `Animated.parallel` has a `stopTogether` option that can be set to `false` to disable this.

You can find a full list of composition methods in the [Composing animations](/docs/next/animated#composing-animations) section of the `Animated` API reference.

### Combining animated values[​](#combining-animated-values "Direct link to Combining animated values")

You can [combine two animated values](/docs/next/animated#combining-animated-values) via addition, multiplication, division, or modulo to make a new animated value.

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):

React TSX

```
const a = new Animated.Value(1);

const b = Animated.divide(1, a);



Animated.spring(a, {

  toValue: 2,

  useNativeDriver: true,

}).start();
```

### Interpolation[​](#interpolation "Direct link to Interpolation")

Each property can be run through an interpolation first. An interpolation maps input ranges to output ranges, typically using a linear interpolation but also supports easing functions. By default, it will extrapolate the curve beyond the ranges given, but you can also have it clamp the output value.

A basic mapping to convert a 0-1 range to a 0-100 range would be:

React TSX

```
value.interpolate({

  inputRange: [0, 1],

  outputRange: [0, 100],

});
```

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:

React TSX

```
  style={{

    opacity: this.state.fadeAnim, // Binds directly

    transform: [{

      translateY: this.state.fadeAnim.interpolate({

        inputRange: [0, 1],

        outputRange: [150, 0]  // 0 : 150, 0.5 : 75, 1 : 0

      }),

    }],

  }}
```

[`interpolate()`](/docs/next/animatedvalue#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:

React TSX

```
value.interpolate({

  inputRange: [-300, -100, 0, 100, 101],

  outputRange: [300, 0, 1, 0, 0],

});
```

Which would map like so:

```
Input | Output

------|-------

  -400|    450

  -300|    300

  -200|    150

  -100|      0

   -50|    0.5

     0|      1

    50|    0.5

   100|      0

   101|      0

   200|      0
```

`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:

React TSX

```
value.interpolate({

  inputRange: [0, 360],

  outputRange: ['0deg', '360deg'],

});
```

`interpolate()` also supports arbitrary easing functions, many of which are already implemented in the [`Easing`](/docs/next/easing) module. `interpolate()` also has configurable behavior for extrapolating the `outputRange`. You can set the extrapolation by setting the `extrapolate`, `extrapolateLeft`, or `extrapolateRight` options. The default value is `extend` but you can use `clamp` to prevent the output value from exceeding `outputRange`.

### Tracking dynamic values[​](#tracking-dynamic-values "Direct link to Tracking dynamic values")

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:

React TSX

```
Animated.spring(follower, {toValue: leader}).start();

Animated.timing(opacity, {

  toValue: pan.x.interpolate({

    inputRange: [0, 300],

    outputRange: [1, 0],

  }),

  useNativeDriver: true,

}).start();
```

The `leader` and `follower` animated values would be implemented using `Animated.ValueXY()`. `ValueXY` is a handy way to deal with 2D interactions, such as panning or dragging. It is a basic wrapper that contains two `Animated.Value` instances and some helper functions that call through to them, making `ValueXY` a drop-in replacement for `Value` in many cases. It allows us to track both x and y values in the example above.

### Tracking gestures[​](#tracking-gestures "Direct link to Tracking gestures")

Gestures, like panning or scrolling, and other events can map directly to animated values using [`Animated.event`](/docs/next/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`):

React TSX

```
onScroll={Animated.event(

  // scrollX = e.nativeEvent.contentOffset.x

  [{

    nativeEvent: {

      contentOffset: { x: scrollX }

    }

  }],

  {useNativeDriver: true}

)}
```

The following example implements a horizontal scrolling carousel where the scroll position indicators are animated using the `Animated.event` used in the `ScrollView`

#### ScrollView with Animated Event Example[​](#scrollview-with-animated-event-example "Direct link to ScrollView with Animated Event Example")

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`.

React TSX

```
onPanResponderMove={Animated.event(

  [null, // ignore the native event

  // extract dx and dy from gestureState

  // like 'pan.x = gestureState.dx, pan.y = gestureState.dy'

  {dx: pan.x, dy: pan.y}

])}
```

```
Animated.timing(this.state.animatedValue, {

  toValue: 1,

  duration: 500,

  useNativeDriver: true, // <-- Set this to true

}).start();
```

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.

React TSX

```
<Animated.ScrollView // <-- Use the Animated ScrollView wrapper

  onScroll={Animated.event(

    [

      {

        nativeEvent: {

          contentOffset: {y: this.state.animatedValue},

        },

      },

    ],

    {useNativeDriver: true}, // <-- Set this to true

  )}>

  {content}

</Animated.ScrollView>
```

```
<Animated.View

  style={{

    transform: [

      {scale: this.state.scale},

      {rotateY: this.state.rotateY},

      {perspective: 1000}, // without this line this Animation will not render on Android while working fine on iOS

    ],

  }}

/>
```

```
UIManager.setLayoutAnimationEnabledExperimental(true);
```

This example uses a preset value, you can customize the animations as you need, see [LayoutAnimation.js](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/LayoutAnimation/LayoutAnimation.js) for more information.

## Additional notes[​](#additional-notes "Direct link to Additional notes")

### `requestAnimationFrame`[​](#requestanimationframe "Direct link to requestanimationframe")

`requestAnimationFrame` is a polyfill from the browser that you might be familiar with. It accepts a function as its only argument and calls that function before the next repaint. It is an essential building block for animations that underlies all of the JavaScript-based animation APIs. In general, you shouldn't need to call this yourself - the animation APIs will manage frame updates for you.

### `setNativeProps`[​](#setnativeprops "Direct link to setnativeprops")

As mentioned [in the Direct Manipulation section](/docs/next/legacy/direct-manipulation), `setNativeProps` allows us to modify properties of native-backed components (components that are actually backed by native views, unlike composite components) directly, without having to `setState` and re-render the component hierarchy.

----
url: https://reactnative.dev/docs/flexbox
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

A component can specify the layout of its children using the Flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.

You will normally use a combination of `flexDirection`, `alignItems`, and `justifyContent` to achieve the right layout.

caution

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with `flexDirection` defaulting to `column` instead of `row`, `alignContent` defaulting to `flex-start` instead of `stretch`, `flexShrink` defaulting to `0` instead of `1`, the `flex` parameter only supporting a single number.

## Flex[​](#flex "Direct link to Flex")

[`flex`](/docs/layout-props#flex) will define how your items are going to **“fill”** over the available space along your main axis. Space will be divided according to each element's flex property.

In the following example, the red, orange, and green views are all children in the container view that has `flex: 1` set. The red view uses `flex: 1` , the orange view uses `flex: 2`, and the green view uses `flex: 3` . **1+2+3 = 6**, which means that the red view will get `1/6` of the space, the orange `2/6` of the space, and the green `3/6` of the space.

## Flex Direction[​](#flex-direction "Direct link to Flex Direction")

[`flexDirection`](/docs/layout-props#flexdirection) controls the direction in which the children of a node are laid out. This is also referred to as the main axis. The cross axis is the axis perpendicular to the main axis, or the axis which the wrapping lines are laid out in.

Layout [`direction`](/docs/layout-props#direction) specifies the direction in which children and text in a hierarchy should be laid out. Layout direction also affects what edge `start` and `end` refer to. By default, React Native lays out with LTR layout direction. In this mode `start` refers to left and `end` refers to right.

* `LTR` (**default value**) Text and children are laid out from left to right. Margin and padding applied to the start of an element are applied on the left side.

* `RTL` Text and children are laid out from right to left. Margin and padding applied to the start of an element are applied on the right side.

- TypeScript
- JavaScript

## Justify Content[​](#justify-content "Direct link to Justify Content")

[`justifyContent`](/docs/layout-props#justifycontent) describes how to align children within the main axis of their container. For example, you can use this property to center a child horizontally within a container with `flexDirection` set to `row` or vertically within a container with `flexDirection` set to `column`.

[`alignItems`](/docs/layout-props#alignitems) describes how to align children along the cross axis of their container. It is very similar to `justifyContent` but instead of applying to the main axis, `alignItems` applies to the cross axis.

[`alignSelf`](/docs/layout-props#alignself) has the same options and effect as `alignItems` but instead of affecting the children within a container, you can apply this property to a single child to change its alignment within its parent. `alignSelf` overrides any option set by the parent with `alignItems`.

* TypeScript
* JavaScript

## Align Content[​](#align-content "Direct link to Align Content")

[alignContent](/docs/layout-props#aligncontent) defines the distribution of lines along the cross-axis. This only has effect when items are wrapped to multiple lines using `flexWrap`.

The [`flexWrap`](/docs/layout-props#flexwrap) property is set on containers and it controls what happens when children overflow the size of the container along the main axis. By default, children are forced into a single line (which can shrink elements). If wrapping is allowed, items are wrapped into multiple lines along the main axis if needed.

When wrapping lines, `alignContent` can be used to specify how the lines are placed in the container. Learn more [here](https://www.yogalayout.dev/docs/styling/flex-wrap).

* TypeScript
* JavaScript

## Flex Basis, Grow, and Shrink[​](#flex-basis-grow-and-shrink "Direct link to Flex Basis, Grow, and Shrink")

* [`flexBasis`](/docs/layout-props#flexbasis) is an axis-independent way of providing the default size of an item along the main axis. Setting the `flexBasis` of a child is similar to setting the `width` of that child if its parent is a container with `flexDirection: row` or setting the `height` of a child if its parent is a container with `flexDirection: column`. The `flexBasis` of an item is the default size of that item, the size of the item before any `flexGrow` and `flexShrink` calculations are performed.

* [`flexGrow`](/docs/layout-props#flexgrow) describes how much space within a container should be distributed among its children along the main axis. After laying out its children, a container will distribute any remaining space according to the flex grow values specified by its children.

  `flexGrow` accepts any floating point value >= 0, with 0 being the default value. A container will distribute any remaining space among its children weighted by the children’s `flexGrow` values.

* [`flexShrink`](/docs/layout-props#flexshrink) describes how to shrink children along the main axis in the case in which the total size of the children overflows the size of the container on the main axis. `flexShrink` is very similar to `flexGrow` and can be thought of in the same way if any overflowing size is considered to be negative remaining space. These two properties also work well together by allowing children to grow and shrink as needed.

  `flexShrink` accepts any floating point value >= 0, with 0 being the default value (on the web, the default is 1). A container will shrink its children weighted by the children’s `flexShrink` values.

You can learn more [here](https://www.yogalayout.dev/docs/styling/flex-basis-grow-shrink).

* TypeScript
* JavaScript

## Row Gap, Column Gap and Gap[​](#row-gap-column-gap-and-gap "Direct link to Row Gap, Column Gap and Gap")

* [`rowGap`](/docs/layout-props#rowgap) sets the size of the gap (gutter) between an element's rows.

* [`columnGap`](/docs/layout-props#columngap) sets the size of the gap (gutter) between an element's columns.

* [`gap`](/docs/layout-props#gap) sets the size of the gap (gutter) between rows and columns. It is a shorthand for `rowGap` and `columnGap`.

The `position` type of an element defines how it is positioned relative to either itself, its parent, or its [containing block](/docs/flexbox#the-containing-block).

We've covered the basics, but there are many other styles you may need for layouts. The full list of props that control layout is documented [here](/docs/layout-props).

----
url: https://reactnative.dev/docs/next/global-File
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-File)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/File) for more information.

The global `File` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/modal
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/modal)** (0.87).

Version: Next

The Modal component is a basic way to present content above an enclosing view.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### `animationType`[​](#animationtype "Direct link to animationtype")

The `animationType` prop controls how the modal animates.

Possible values:

* `slide` slides in from the bottom
* `fade` fades into view
* `none` appears without an animation

| Type                                | Default |
| ----------------------------------- | ------- |
| enum(`'none'`, `'slide'`, `'fade'`) | `none`  |

***

### `backdropColor`[​](#backdropcolor "Direct link to backdropcolor")

The `backdropColor` of the modal (or background color of the modal's container.) Defaults to `white` if not provided and transparent is `false`. Ignored if `transparent` is `true`.

| Type                       | Default |
| -------------------------- | ------- |
| [color](/docs/next/colors) | white   |

***

### `hardwareAccelerated`Android[​](#hardwareaccelerated-android "Direct link to hardwareaccelerated-android")

The `hardwareAccelerated` prop controls whether to force hardware acceleration for the underlying window.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `navigationBarTranslucent`Android[​](#navigationbartranslucent-android "Direct link to navigationbartranslucent-android")

The `navigationBarTranslucent` prop determines whether your modal should go under the system navigation bar. However, `statusBarTranslucent` also needs to be set to `true` to make navigation bar translucent.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `onDismiss`iOS[​](#ondismiss-ios "Direct link to ondismiss-ios")

The `onDismiss` prop allows passing a function that will be called once the modal has been dismissed.

| Type     |
| -------- |
| function |

***

### `onOrientationChange`iOS[​](#onorientationchange-ios "Direct link to onorientationchange-ios")

The `onOrientationChange` callback is called when the orientation changes while the modal is being displayed. The orientation provided is only 'portrait' or 'landscape'. This callback is also called on initial render, regardless of the current orientation.

| Type     |
| -------- |
| function |

***

### `allowSwipeDismissal`iOS[​](#allowswipedismissal-ios "Direct link to allowswipedismissal-ios")

Controls whether the modal can be dismissed by swiping down on iOS. This requires you to implement the `onRequestClose` prop to handle the dismissal.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/next/element-nodes) when mounted.

***

### `onRequestClose`[​](#onrequestclose "Direct link to onrequestclose")

The `onRequestClose` callback is called when the user taps the hardware back button on Android or the menu button on Apple TV. Because of this required prop, be aware that `BackHandler` events will not be emitted as long as the modal is open. On iOS, this callback is called when a Modal is being dismissed using a drag gesture when `presentationStyle` is `pageSheet` or `formSheet`. When `allowSwipeDismissal` is enabled this callback will be called after dismissing the modal.

| Type                                    |
| --------------------------------------- |
| functionRequiredAndroidTV***functioniOS |

***

### `onShow`[​](#onshow "Direct link to onshow")

The `onShow` prop allows passing a function that will be called once the modal has been shown.

| Type     |
| -------- |
| function |

***

| Type                                                                   | Default                                                                          |
| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| enum(`'fullScreen'`, `'pageSheet'`, `'formSheet'`, `'overFullScreen'`) | `fullScreen` if `transparent={false}`***`overFullScreen` if `transparent={true}` |

***

### `statusBarTranslucent`Android[​](#statusbartranslucent-android "Direct link to statusbartranslucent-android")

The `statusBarTranslucent` prop determines whether your modal should go under the system statusbar.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `supportedOrientations`iOS[​](#supportedorientations-ios "Direct link to supportedorientations-ios")

The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations. On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field.

note

When using `presentationStyle` of `pageSheet` or `formSheet`, this property will be ignored on iOS.

| Type                                                                                                           | Default        |
| -------------------------------------------------------------------------------------------------------------- | -------------- |
| array of enums(`'portrait'`, `'portrait-upside-down'`, `'landscape'`, `'landscape-left'`, `'landscape-right'`) | `['portrait']` |

***

### `transparent`[​](#transparent "Direct link to transparent")

The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `visible`[​](#visible "Direct link to visible")

The `visible` prop determines whether your modal is visible.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

* [Example](#example)

* [Props](#props)

  * [View Props](#view-props)
  * [`animationType`](#animationtype)
  * [`backdropColor`](#backdropcolor)
  * [`hardwareAccelerated`](#hardwareaccelerated-android)

    [Android](#hardwareaccelerated-android)
  * [`navigationBarTranslucent`](#navigationbartranslucent-android)

    [Android](#navigationbartranslucent-android)
  * [`onDismiss`](#ondismiss-ios)

    [iOS](#ondismiss-ios)
  * [`onOrientationChange`](#onorientationchange-ios)

    [iOS](#onorientationchange-ios)
  * [`allowSwipeDismissal`](#allowswipedismissal-ios)

    [iOS](#allowswipedismissal-ios)
  * [`ref`](#ref)
  * [`onRequestClose`](#onrequestclose)
  * [`onShow`](#onshow)
  * [`presentationStyle`](#presentationstyle-ios)

    [iOS](#presentationstyle-ios)
  * [`statusBarTranslucent`](#statusbartranslucent-android)

    [Android](#statusbartranslucent-android)
  * [`supportedOrientations`](#supportedorientations-ios)

    [iOS](#supportedorientations-ios)
  * [`transparent`](#transparent)
  * [`visible`](#visible)

----
url: https://reactnative.dev/docs/next/activityindicator
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/activityindicator)** (0.87).

Version: Next

Displays a circular loading indicator.

## Example[​](#example "Direct link to Example")

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### `animating`[​](#animating "Direct link to animating")

Whether to show the indicator (`true`) or hide it (`false`).

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `color`[​](#color "Direct link to color")

The foreground color of the spinner.

| Type                       | Default                                                      |
| -------------------------- | ------------------------------------------------------------ |
| [color](/docs/next/colors) | `null` (system accent default color)Android***`'#999999'`iOS |

***

### `hidesWhenStopped`iOS[​](#hideswhenstopped-ios "Direct link to hideswhenstopped-ios")

Whether the indicator should hide when not animating.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/next/element-nodes) when mounted.

***

### `size`[​](#size "Direct link to size")

Size of the indicator.

| Type                                       | Default   |
| ------------------------------------------ | --------- |
| enum(`'small'`, `'large'`)***numberAndroid | `'small'` |

* [Example](#example)

* [Props](#props)

  * [View Props](#view-props)
  * [`animating`](#animating)
  * [`color`](#color)
  * [`hidesWhenStopped`](#hideswhenstopped-ios)

    [iOS](#hideswhenstopped-ios)
  * [`ref`](#ref)
  * [`size`](#size)

----
url: https://reactnative.dev/docs/native-platform
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Your application may need access to platform features that aren’t directly available from react-native or one of the hundreds of [third-party libraries](https://reactnative.directory/) maintained by the community. Maybe you want to reuse some existing Objective-C, Swift, Java, Kotlin or C++ code from the JavaScript runtime. Whatever your reason, React Native exposes a powerful set of API to connect your native code to your JavaScript application code.

This guide introduces:

* **Native Modules:** native libraries that have no User Interface (UI) for the user. Examples would be persistent storage, notifications, network events. These are accessible to your user as JavaScript functions and objects.
* **Native Component:** native platform views, widgets and controllers that are available to your application's JavaScript code through React Components.

note

You might have previously been familiar with:

* [Legacy Native Modules](/docs/legacy/native-modules-intro);
* [Legacy Native Components](/docs/legacy/native-components-android);

These are our deprecated native module and component API. You can still use many of these legacy libraries with the New Architecture thanks to our interop layers. You should consider:

* using alternative libraries,
* upgrading to newer library versions that have first-class support for the New Architecture, or
* port these libraries yourself to Turbo Native Modules or Fabric Native Components.

1. Native Modules

   * [Android & iOS](/docs/turbo-native-modules-introduction)
   * [Cross-Platform with C++](/docs/the-new-architecture/pure-cxx-modules)
   * [Advanced: Custom C++ Types](/docs/the-new-architecture/custom-cxx-types)

2. Fabric Native Components
   * [Android & iOS](/docs/fabric-native-components-introduction)

----
url: https://reactnative.dev/docs/next/switch
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/switch)** (0.87).

Version: Next

Renders a boolean input.

This is a controlled component that requires an `onValueChange` callback that updates the `value` prop in order for the component to reflect user actions. If the `value` prop is not updated, the component will continue to render the supplied `value` prop instead of the expected result of any user actions.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### `disabled`[​](#disabled "Direct link to disabled")

If true the user won't be able to toggle the switch.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `ios_backgroundColor`iOS[​](#ios_backgroundcolor-ios "Direct link to ios_backgroundcolor-ios")

On iOS, custom color for the background. This background color can be seen either when the switch value is `false` or when the switch is disabled (and the switch is translucent).

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `onChange`[​](#onchange "Direct link to onchange")

Invoked when the user tries to change the value of the switch. Receives the change event as an argument. If you want to only receive the new value, use `onValueChange` instead.

| Type     |
| -------- |
| function |

***

### `onValueChange`[​](#onvaluechange "Direct link to onvaluechange")

Invoked when the user tries to change the value of the switch. Receives the new value as an argument. If you want to instead receive an event, use `onChange`.

| Type     |
| -------- |
| function |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/next/element-nodes) when mounted.

***

### `thumbColor`[​](#thumbcolor "Direct link to thumbcolor")

Color of the foreground switch grip. If this is set on iOS, the switch grip will lose its drop shadow.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `trackColor`[​](#trackcolor "Direct link to trackcolor")

Custom colors for the switch track.

*iOS*: When the switch value is `false`, the track shrinks into the border. If you want to change the color of the background exposed by the shrunken track, use [`ios_backgroundColor`](/docs/next/switch#ios_backgroundcolor-ios).

| Type                                  |
| ------------------------------------- |
| `object: {false: color, true: color}` |

***

### `value`[​](#value "Direct link to value")

The value of the switch. If true the switch will be turned on. Default value is false.

| Type |
| ---- |
| bool |

* [Example](#example)

* [Props](#props)

  * [View Props](#view-props)
  * [`disabled`](#disabled)
  * [`ios_backgroundColor`](#ios_backgroundcolor-ios)

    [iOS](#ios_backgroundcolor-ios)
  * [`onChange`](#onchange)
  * [`onValueChange`](#onvaluechange)
  * [`ref`](#ref)
  * [`thumbColor`](#thumbcolor)
  * [`trackColor`](#trackcolor)
  * [`value`](#value)

----
url: https://reactnative.dev/docs/sectionlist
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

If you don't need section support and want a simpler interface, use [`<FlatList>`](/docs/flatlist).

## Example[​](#example "Direct link to Example")

This is a convenience wrapper around [`<VirtualizedList>`](/docs/virtualizedlist), and thus inherits its props (as well as those of [`<ScrollView>`](/docs/scrollview)) that aren't explicitly listed here, along with the following caveats:

* Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
* This is a `PureComponent` which means that it will not re-render if `props` remain shallow-equal. Make sure that everything your `renderItem` function depends on is passed as a prop (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on changes. This includes the `data` prop and parent component state.
* In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
* By default, the list looks for a `key` prop on each item and uses that for the React key. Alternatively, you can provide a custom `keyExtractor` prop.

***

# Reference

## Props[​](#props "Direct link to Props")

### [VirtualizedList Props](/docs/virtualizedlist#props)[​](#virtualizedlist-props "Direct link to virtualizedlist-props")

Inherits [VirtualizedList Props](/docs/virtualizedlist#props).

***

### Require&#x64;**`renderItem`**[​](#requiredrenderitem "Direct link to requiredrenderitem")

Default renderer for every item in every section. Can be over-ridden on a per-section basis. Should return a React element.

| Type     |
| -------- |
| function |

    * 'select' (enum) - possible values are 'leading', 'trailing'
    * 'newProps' (object)

***

### Require&#x64;**`sections`**[​](#requiredsections "Direct link to requiredsections")

The actual data to render, akin to the `data` prop in [`FlatList`](/docs/flatlist).

| Type                                           |
| ---------------------------------------------- |
| array of [Section](/docs/sectionlist#section)s |

***

### `extraData`[​](#extradata "Direct link to extradata")

A marker property for telling the list to re-render (since it implements `PureComponent`). If any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the `data` prop, stick it here and treat it immutably.

| Type |
| ---- |
| any  |

***

### `initialNumToRender`[​](#initialnumtorender "Direct link to initialnumtorender")

How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.

| Type   | Default |
| ------ | ------- |
| number | `10`    |

***

### `inverted`[​](#inverted "Direct link to inverted")

Reverses the direction of scroll. Uses scale transforms of -1.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `ItemSeparatorComponent`[​](#itemseparatorcomponent "Direct link to itemseparatorcomponent")

Rendered in between each item, but not at the top or bottom. By default, `highlighted`, `section`, and `[leading/trailing][Item/Section]` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` which will update the `highlighted` prop, but you can also add custom props with `separators.updateProps`. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type                         |
| ---------------------------- |
| component, function, element |

***

### `keyExtractor`[​](#keyextractor "Direct link to keyextractor")

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the React key to track item re-ordering. The default extractor checks `item.key`, then `item.id`, and then falls back to using the index, like React does. Note that this sets keys for each item, but each overall section still needs its own key.

| Type                                    |
| --------------------------------------- |
| (item: object, index: number) => string |

***

### `ListEmptyComponent`[​](#listemptycomponent "Direct link to listemptycomponent")

Rendered when the list is empty. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListFooterComponent`[​](#listfootercomponent "Direct link to listfootercomponent")

Rendered at the very end of the list. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListHeaderComponent`[​](#listheadercomponent "Direct link to listheadercomponent")

Rendered at the very beginning of the list. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `onRefresh`[​](#onrefresh "Direct link to onrefresh")

If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the `refreshing` prop correctly. To offset the RefreshControl from the top (e.g. by 100 pts), use `progressViewOffset={100}`.

| Type     |
| -------- |
| function |

***

### `onViewableItemsChanged`[​](#onviewableitemschanged "Direct link to onviewableitemschanged")

Called when the viewability of rows changes, as defined by the `viewabilityConfig` prop.

| Type                                                                     |
| ------------------------------------------------------------------------ |
| `(callback: {changed: ViewToken[], viewableItems: ViewToken[]}) => void` |

***

### `refreshing`[​](#refreshing "Direct link to refreshing")

Set this true while waiting for new data from a refresh.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

warning

Using this property may lead to bugs (missing content) in some circumstances - use at your own risk.

When `true`, offscreen child views are removed from their native backing superview when offscreen. This may improve scroll performance for large lists. On Android the default value is `true`.

| Type    |
| ------- |
| boolean |

***

### `renderSectionFooter`[​](#rendersectionfooter "Direct link to rendersectionfooter")

Rendered at the bottom of each section.

| Type                                           |
| ---------------------------------------------- |
| `(info: {section: Section}) => element ｜ null` |

***

### `renderSectionHeader`[​](#rendersectionheader "Direct link to rendersectionheader")

Rendered at the top of each section. These stick to the top of the `ScrollView` by default on iOS. See `stickySectionHeadersEnabled`.

| Type                                           |
| ---------------------------------------------- |
| `(info: {section: Section}) => element ｜ null` |

***

### `SectionSeparatorComponent`[​](#sectionseparatorcomponent "Direct link to sectionseparatorcomponent")

Rendered at the top and bottom of each section (note this is different from `ItemSeparatorComponent` which is only rendered between items). These are intended to separate sections from the headers above and below and typically have the same highlight response as `ItemSeparatorComponent`. Also receives `highlighted`, `[leading/trailing][Item/Section]`, and any custom props from `separators.updateProps`.

| Type               |
| ------------------ |
| component, element |

***

### `stickySectionHeadersEnabled`[​](#stickysectionheadersenabled "Direct link to stickysectionheadersenabled")

Makes section headers stick to the top of the screen until the next one pushes it off. Only enabled by default on iOS because that is the platform standard there.

| Type    | Default                    |
| ------- | -------------------------- |
| boolean | `false`Android***`true`iOS |

## Methods[​](#methods "Direct link to Methods")

### `flashScrollIndicators()`iOS[​](#flashscrollindicators-ios "Direct link to flashscrollindicators-ios")

React TSX

```
flashScrollIndicators();
```

Displays the scroll indicators momentarily.

***

### `recordInteraction()`[​](#recordinteraction "Direct link to recordinteraction")

React TSX

```
recordInteraction();
```

Tells the list an interaction has occurred, which should trigger viewability calculations, e.g. if `waitForInteractions` is true and the user has not scrolled. This is typically called by taps on items or by navigation actions.

***

### `scrollToLocation()`[​](#scrolltolocation "Direct link to scrolltolocation")

React TSX

```
scrollToLocation(params: SectionListScrollParams);
```

Scrolls to the item at the specified `sectionIndex` and `itemIndex` (within the section) positioned in the viewable area such that `viewPosition` set to `0` places it at the top (and may be covered by a sticky header), `1` at the bottom, and `0.5` centered in the middle.

note

You cannot scroll to locations outside the render window without specifying the `getItemLayout` or `onScrollToIndexFailed` prop.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| paramsRequired | object |

| Type |
| ---- |
| any  |

**Properties:**

| Name                   | Type               | Description                                                                                                                                                               |
| ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| dataRequired           | array              | The data for rendering items in this section. Array of objects, much like [`FlatList`'s data prop](/docs/flatlist#required-data).                                         |
| key                    | string             | Optional key to keep track of section re-ordering. If you don't plan on re-ordering sections, the array index will be used by default.                                    |
| renderItem             | function           | Optionally define an arbitrary item renderer for this section, overriding the default [`renderItem`](/docs/sectionlist#requiredrenderitem) for the list.                  |
| ItemSeparatorComponent | component, element | Optionally define an arbitrary item separator for this section, overriding the default [`ItemSeparatorComponent`](/docs/sectionlist#itemseparatorcomponent) for the list. |
| keyExtractor           | function           | Optionally define an arbitrary key extractor for this section, overriding the default [`keyExtractor`](/docs/sectionlist#keyextractor).                                   |

* [Example](#example)

* [Props](#props)

  * [VirtualizedList Props](#virtualizedlist-props)
  * [Required](#requiredrenderitem)

    [**`renderItem`**](#requiredrenderitem)
  * [Required](#requiredsections)

    [**`sections`**](#requiredsections)

    [iOS](#flashscrollindicators-ios)
  * [`recordInteraction()`](#recordinteraction)
  * [`scrollToLocation()`](#scrolltolocation)

* [Type Definitions](#type-definitions)
  * [Section](#section)

----
url: https://reactnative.dev/docs/usewindowdimensions
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React 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:

React TSX

```
const {height, width} = useWindowDimensions();
```

## Example[​](#example "Direct link to Example")

## Properties[​](#properties "Direct link to Properties")

### `fontScale`[​](#fontscale "Direct link to fontscale")

React TSX

```
useWindowDimensions().fontScale;
```

The scale of the font currently used. Some operating systems allow users to scale their font sizes larger or smaller for reading comfort. This property will let you know what is in effect.

***

### `height`[​](#height "Direct link to height")

React TSX

```
useWindowDimensions().height;
```

The height in pixels of the window or screen your app occupies.

***

### `scale`[​](#scale "Direct link to scale")

React TSX

```
useWindowDimensions().scale;
```

The pixel ratio of the device your app is running on. The values can be:

* `1` which indicates that one point equals one pixel (usually PPI/DPI of 96, 76 on some platforms).
* `2` or `3` which indicates a Retina or high DPI display.

***

### `width`[​](#width "Direct link to width")

React TSX

```
useWindowDimensions().width;
```

----
url: https://reactnative.dev/docs/global-XMLHttpRequest
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) for more information.

The global `XMLHttpRequest` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/textinput
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

A foundational component for inputting text into the app via a keyboard. Props provide configurability for several features, such as auto-correction, auto-capitalization, placeholder text, and different keyboard types, such as a numeric keypad.

The most basic use case is to plop down a `TextInput` and subscribe to the `onChangeText` events to read the user input. There are also other events, such as `onSubmitEditing` and `onFocus` that can be subscribed to. A minimal example:

Two methods exposed via the native element are `.focus()` and `.blur()` that will focus or blur the TextInput programmatically.

Note that some props are only available with `multiline={true/false}`:

`TextInput` has a border at the bottom of its view by default. This border has its padding set by the background image provided by the system, and it cannot be changed. Solutions to avoid this are to either not set height explicitly, in which case the system will take care of displaying the border in the correct position, or to not display the border by setting `underlineColorAndroid` to transparent.

Note that on Android performing text selection in an input can change the app's activity `windowSoftInputMode` param to `adjustResize`. This may cause issues with components that have position: 'absolute' while the keyboard is active. To avoid this behavior either specify `windowSoftInputMode` in AndroidManifest.xml ( <https://developer.android.com/guide/topics/manifest/activity-element.html> ) or control this param programmatically with native code.

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### `allowFontScaling`[​](#allowfontscaling "Direct link to allowfontscaling")

Specifies whether fonts should scale to respect Text Size accessibility settings. The default is `true`.

| Type |
| ---- |
| bool |

***

### `autoCapitalize`[​](#autocapitalize "Direct link to autocapitalize")

Tells `TextInput` to automatically capitalize certain characters. This property is not supported by some keyboard types such as `name-phone-pad`.

* `characters`: all characters.
* `words`: first letter of each word.
* `sentences`: first letter of each sentence (*default*).
* `none`: don't auto capitalize anything.

| Type                                             |
| ------------------------------------------------ |
| enum('none', 'sentences', 'words', 'characters') |

***

| Type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| enum('additional-name', 'address-line1', 'address-line2', 'birthdate-day', 'birthdate-full', 'birthdate-month', 'birthdate-year', 'cc-csc', 'cc-exp', 'cc-exp-day', 'cc-exp-month', 'cc-exp-year', 'cc-number', 'country', 'current-password', 'email', 'family-name', 'given-name', 'honorific-prefix', 'honorific-suffix', 'name', 'new-password', 'off', 'one-time-code', 'postal-code', 'street-address', 'tel', 'username', 'cc-family-name', 'cc-given-name', 'cc-middle-name', 'cc-name', 'cc-type', 'nickname', 'organization', 'organization-title', 'url', 'gender', 'name-family', 'name-given', 'name-middle', 'name-middle-initial', 'name-prefix', 'name-suffix', 'password', 'password-new', 'postal-address', 'postal-address-country', 'postal-address-extended', 'postal-address-extended-postal-code', 'postal-address-locality', 'postal-address-region', 'sms-otp', 'tel-country-code', 'tel-device', 'tel-national', 'username-new') |

***

### `autoCorrect`[​](#autocorrect "Direct link to autocorrect")

If `false`, disables auto-correct. The default value is `true`.

| Type |
| ---- |
| bool |

***

### `autoFocus`[​](#autofocus "Direct link to autofocus")

If `true`, focuses the input. The default value is `false`.

| Type |
| ---- |
| bool |

***

### 🗑️ `blurOnSubmit`[​](#️-bluronsubmit "Direct link to ️-bluronsubmit")

Deprecated

Note that `submitBehavior` now takes the place of `blurOnSubmit` and will override any behavior defined by `blurOnSubmit`. See [submitBehavior](/docs/textinput#submitbehavior).

If `true`, the text field will blur when submitted. The default value is true for single-line fields and false for multiline fields. Note that for multiline fields, setting `blurOnSubmit` to `true` means that pressing return will blur the field and trigger the `onSubmitEditing` event instead of inserting a newline into the field.

| Type |
| ---- |
| bool |

***

### `caretHidden`[​](#carethidden "Direct link to carethidden")

If `true`, caret is hidden. The default value is `false`.

| Type |
| ---- |
| bool |

***

### `clearButtonMode`iOS[​](#clearbuttonmode-ios "Direct link to clearbuttonmode-ios")

When the clear button should appear on the right side of the text view. This property is supported only for single-line TextInput component. The default value is `never`.

| Type                                                       |
| ---------------------------------------------------------- |
| enum('never', 'while-editing', 'unless-editing', 'always') |

***

### `clearTextOnFocus`iOS[​](#cleartextonfocus-ios "Direct link to cleartextonfocus-ios")

If `true`, clears the text field automatically when editing begins.

| Type |
| ---- |
| bool |

***

### `contextMenuHidden`[​](#contextmenuhidden "Direct link to contextmenuhidden")

If `true`, context menu is hidden. The default value is `false`.

| Type |
| ---- |
| bool |

***

| Type                                                                                                                                                     |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all'), ,array of enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all') |

***

### `defaultValue`[​](#defaultvalue "Direct link to defaultvalue")

Provides an initial value that will change when the user starts typing. Useful for use-cases where you do not want to deal with listening to events and updating the value prop to keep the controlled state in sync.

| Type   |
| ------ |
| string |

***

### `disableKeyboardShortcuts`iOS[​](#disablekeyboardshortcuts-ios "Direct link to disablekeyboardshortcuts-ios")

If `true`, the keyboard shortcuts (undo/redo and copy buttons) are disabled.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `cursorColor`Android[​](#cursorcolor-android "Direct link to cursorcolor-android")

When provided it will set the color of the cursor (or "caret") in the component. Unlike the behavior of `selectionColor` the cursor color will be set independently from the color of the text selection box.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `disableFullscreenUI`Android[​](#disablefullscreenui-android "Direct link to disablefullscreenui-android")

When `false`, if there is a small amount of space available around a text input (e.g. landscape orientation on a phone), the OS may choose to have the user edit the text inside of a full screen text input mode. When `true`, this feature is disabled and users will always edit the text directly inside of the text input. Defaults to `false`.

| Type |
| ---- |
| bool |

***

### `editable`[​](#editable "Direct link to editable")

If `false`, text is not editable. The default value is `true`.

| Type |
| ---- |
| bool |

***

### `enablesReturnKeyAutomatically`iOS[​](#enablesreturnkeyautomatically-ios "Direct link to enablesreturnkeyautomatically-ios")

If `true`, the keyboard disables the return key when there is no text and automatically enables it when there is text. The default value is `false`.

| Type |
| ---- |
| bool |

***

| Type                                                              |
| ----------------------------------------------------------------- |
| enum('enter', 'done', 'next', 'previous', 'search', 'send', 'go') |

***

| Type                                                                       |
| -------------------------------------------------------------------------- |
| enum('auto', 'no', 'noExcludeDescendants', 'yes', 'yesExcludeDescendants') |

***

### `inlineImageLeft`Android[​](#inlineimageleft-android "Direct link to inlineimageleft-android")

If defined, the provided image resource will be rendered on the left. The image resource must be inside `/android/app/src/main/res/drawable` and referenced like

```
<TextInput

 inlineImageLeft='search_icon'

/>
```

| Type   |
| ------ |
| string |

***

### `inlineImagePadding`Android[​](#inlineimagepadding-android "Direct link to inlineimagepadding-android")

Padding between the inline image, if any, and the text input itself.

| Type   |
| ------ |
| number |

***

### `inputAccessoryViewID`iOS[​](#inputaccessoryviewid-ios "Direct link to inputaccessoryviewid-ios")

An optional identifier which links a custom [InputAccessoryView](/docs/inputaccessoryview) to this text input. The InputAccessoryView is rendered above the keyboard when this text input is focused.

| Type   |
| ------ |
| string |

***

### `inputAccessoryViewButtonLabel`iOS[​](#inputaccessoryviewbuttonlabel-ios "Direct link to inputaccessoryviewbuttonlabel-ios")

An optional label that overrides the default [InputAccessoryView](/docs/inputaccessoryview) button label.

By default, the default button label is not localized. Use this property to provide a localized version.

| Type   |
| ------ |
| string |

***

| Type                                                                        |
| --------------------------------------------------------------------------- |
| enum('decimal', 'email', 'none', 'numeric', 'search', 'tel', 'text', 'url') |

***

### `keyboardAppearance`iOS[​](#keyboardappearance-ios "Direct link to keyboardappearance-ios")

Determines the color of the keyboard.

| Type                             |
| -------------------------------- |
| enum('default', 'light', 'dark') |

***

| Type                                                                                                                                                                                                    |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| enum('default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', 'visible-password') |

***

### `lineBreakStrategyIOS`iOS[​](#linebreakstrategyios-ios "Direct link to linebreakstrategyios-ios")

Set line break strategy on iOS 14+. Possible values are `none`, `standard`, `hangul-word` and `push-out`.

| Type                                                        | Default  |
| ----------------------------------------------------------- | -------- |
| enum(`'none'`, `'standard'`, `'hangul-word'`, `'push-out'`) | `'none'` |

***

### `lineBreakModeIOS`iOS[​](#linebreakmodeios-ios "Direct link to linebreakmodeios-ios")

Set line break mode on iOS. Possible values are `wordWrapping`, `char`, `clip`, `head`, `middle` and `tail`.

| Type                                                                       | Default          |
| -------------------------------------------------------------------------- | ---------------- |
| enum(`'wordWrapping'`, `'char'`, `'clip'`, `'head'`, `'middle'`, `'tail'`) | `'wordWrapping'` |

***

### `maxFontSizeMultiplier`[​](#maxfontsizemultiplier "Direct link to maxfontsizemultiplier")

Specifies largest possible scale a font can reach when `allowFontScaling` is enabled. Possible values:

* `null/undefined` (default): inherit from the parent node or the global default (0)
* `0`: no max, ignore parent/global default
* `>= 1`: sets the `maxFontSizeMultiplier` of this node to this value

| Type   |
| ------ |
| number |

***

### `maxLength`[​](#maxlength "Direct link to maxlength")

Limits the maximum number of characters that can be entered. Use this instead of implementing the logic in JS to avoid flicker.

| Type   |
| ------ |
| number |

***

### `multiline`[​](#multiline "Direct link to multiline")

If `true`, the text input can be multiple lines. The default value is `false`.

note

It is important to note that this aligns the text to the top on iOS, and centers it on Android. Use with `textAlignVertical` set to `top` for the same behavior in both platforms.

| Type |
| ---- |
| bool |

***

### `numberOfLines`[​](#numberoflines "Direct link to numberoflines")

note

`numberOfLines` on iOS is only available on the [New Architecture](/architecture/landing-page)

Sets the maximum number of lines for a `TextInput`. Use it with multiline set to `true` to be able to fill the lines.

| Type   |
| ------ |
| number |

***

### `onBlur`[​](#onblur "Direct link to onblur")

Callback that is called when the text input is blurred.

note

If you are attempting to access the `text` value from `nativeEvent` keep in mind that the resulting value you get can be `undefined` which can cause unintended errors. If you are trying to find the last value of TextInput, you can use the [`onEndEditing`](/docs/textinput#onendediting) event, which is fired upon completion of editing.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: TargetEvent}) => void` |

***

### `onChange`[​](#onchange "Direct link to onchange")

Callback that is called when the text input's text changes.

| Type                                                  |
| ----------------------------------------------------- |
| (`{nativeEvent: {eventCount, target, text}}`) => void |

***

### `onChangeText`[​](#onchangetext "Direct link to onchangetext")

Callback that is called when the text input's text changes. Changed text is passed as a single string argument to the callback handler.

| Type     |
| -------- |
| function |

***

### `onContentSizeChange`[​](#oncontentsizechange "Direct link to oncontentsizechange")

Callback that is called when the text input's content size changes.

Only called for multiline text inputs.

| Type                                                       |
| ---------------------------------------------------------- |
| (`{nativeEvent: {contentSize: {width, height} }}`) => void |

***

### `onEndEditing`[​](#onendediting "Direct link to onendediting")

Callback that is called when text input ends.

| Type     |
| -------- |
| function |

***

### `onPressIn`[​](#onpressin "Direct link to onpressin")

Callback that is called when a touch is engaged.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onPressOut`[​](#onpressout "Direct link to onpressout")

Callback that is called when a touch is released.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onFocus`[​](#onfocus "Direct link to onfocus")

Callback that is called when the text input is focused.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: TargetEvent}) => void` |

***

### `onKeyPress`[​](#onkeypress "Direct link to onkeypress")

Callback that is called when a key is pressed. This will be called with object where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and the typed-in character otherwise including `' '` for space. Fires before `onChange` callbacks. Note: on Android only the inputs from soft keyboard are handled, not the hardware keyboard inputs.

| Type                                        |
| ------------------------------------------- |
| (`{nativeEvent: {key: keyValue} }`) => void |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: LayoutEvent}) => void` |

***

### `onScroll`[​](#onscroll "Direct link to onscroll")

Invoked on content scroll. May also contain other properties from `ScrollEvent` but on Android `contentSize` is not provided for performance reasons.

| Type                                                |
| --------------------------------------------------- |
| (`{nativeEvent: {contentOffset: {x, y} }}`) => void |

***

### `onSelectionChange`[​](#onselectionchange "Direct link to onselectionchange")

Callback that is called when the text input selection is changed.

| Type                                                  |
| ----------------------------------------------------- |
| (`{nativeEvent: {selection: {start, end} }}`) => void |

***

### `onSubmitEditing`[​](#onsubmitediting "Direct link to onsubmitediting")

Callback that is called when the text input's submit button is pressed.

| Type                                                  |
| ----------------------------------------------------- |
| (`{nativeEvent: {text, eventCount, target}}`) => void |

Note that on iOS this method isn't called when using `keyboardType="phone-pad"`.

***

### `placeholder`[​](#placeholder "Direct link to placeholder")

The string that will be rendered before text input has been entered.

| Type   |
| ------ |
| string |

***

### `placeholderTextColor`[​](#placeholdertextcolor "Direct link to placeholdertextcolor")

The text color of the placeholder string.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `readOnly`[​](#readonly "Direct link to readonly")

If `true`, text is not editable. The default value is `false`.

| Type |
| ---- |
| bool |

***

### `returnKeyLabel`Android[​](#returnkeylabel-android "Direct link to returnkeylabel-android")

Sets the return key to the label. Use it instead of `returnKeyType`.

| Type   |
| ------ |
| string |

***

| Type                                                                                                                              |
| --------------------------------------------------------------------------------------------------------------------------------- |
| enum('done', 'go', 'next', 'search', 'send', 'none', 'previous', 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo') |

### `rejectResponderTermination`iOS[​](#rejectrespondertermination-ios "Direct link to rejectrespondertermination-ios")

If `true`, allows TextInput to pass touch events to the parent component. This allows components such as SwipeableListView to be swipeable from the TextInput on iOS, as is the case on Android by default. If `false`, TextInput always asks to handle the input (except when disabled). The default value is `true`.

| Type |
| ---- |
| bool |

***

### `rows`Android[​](#rows-android "Direct link to rows-android")

Sets the number of lines for a `TextInput`. Use it with multiline set to `true` to be able to fill the lines.

| Type   |
| ------ |
| number |

***

### `scrollEnabled`iOS[​](#scrollenabled-ios "Direct link to scrollenabled-ios")

If `false`, scrolling of the text view will be disabled. The default value is `true`. Only works with `multiline={true}`.

| Type |
| ---- |
| bool |

***

### `secureTextEntry`[​](#securetextentry "Direct link to securetextentry")

If `true`, the text input obscures the text entered so that sensitive text like passwords stay secure. The default value is `false`. Does not work with `multiline={true}`.

| Type |
| ---- |
| bool |

***

### `selection`[​](#selection "Direct link to selection")

The start and end of the text input's selection. Set start and end to the same value to position the cursor.

| Type                                  |
| ------------------------------------- |
| object: `{start: number,end: number}` |

***

### `selectionColor`[​](#selectioncolor "Direct link to selectioncolor")

The highlight, selection handle and cursor color of the text input.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `selectionHandleColor`Android[​](#selectionhandlecolor-android "Direct link to selectionhandlecolor-android")

Sets the color of the selection handle. Unlike `selectionColor`, it allows the selection handle color to be customized independently of the selection's color.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `selectTextOnFocus`[​](#selecttextonfocus "Direct link to selecttextonfocus")

If `true`, all text will automatically be selected on focus.

| Type |
| ---- |
| bool |

***

### `showSoftInputOnFocus`[​](#showsoftinputonfocus "Direct link to showsoftinputonfocus")

When `false`, it will prevent the soft keyboard from showing when the field is focused. The default value is `true`.

| Type |
| ---- |
| bool |

***

### `smartInsertDelete`iOS[​](#smartinsertdelete-ios "Direct link to smartinsertdelete-ios")

If `false`, the iOS system will not insert an extra space after a paste operation neither delete one or two spaces after a cut or delete operation.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `spellCheck`iOS[​](#spellcheck-ios "Direct link to spellcheck-ios")

If `false`, disables spell-check style (i.e. red underlines). The default value is inherited from `autoCorrect`.

| Type |
| ---- |
| bool |

***

| Type                                       |
| ------------------------------------------ |
| enum('submit', 'blurAndSubmit', 'newline') |

***

### `textAlign`[​](#textalign "Direct link to textalign")

Align the input text to the left, center, or right sides of the input field.

Possible values for `textAlign` are:

* `left`
* `center`
* `right`

| Type                            |
| ------------------------------- |
| enum('left', 'center', 'right') |

***

| Type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| enum('none', 'addressCity', 'addressCityAndState', 'addressState', 'birthdate', 'birthdateDay', 'birthdateMonth', 'birthdateYear', 'countryName', 'creditCardExpiration', 'creditCardExpirationMonth', 'creditCardExpirationYear', 'creditCardFamilyName', 'creditCardGivenName', 'creditCardMiddleName', 'creditCardName', 'creditCardNumber', 'creditCardSecurityCode', 'creditCardType', 'emailAddress', 'familyName', 'fullStreetAddress', 'givenName', 'jobTitle', 'location', 'middleName', 'name', 'namePrefix', 'nameSuffix', 'newPassword', 'nickname', 'oneTimeCode', 'organizationName', 'password', 'postalCode', 'streetAddressLine1', 'streetAddressLine2', 'sublocality', 'telephoneNumber', 'URL', 'username') |

***

### `passwordRules`iOS[​](#passwordrules-ios "Direct link to passwordrules-ios")

When using `textContentType` as `newPassword` on iOS we can let the OS know the minimum requirements of the password so that it can generate one that will satisfy them. In order to create a valid string for `PasswordRules` take a look to the [Apple Docs](https://developer.apple.com/password-rules/).

tip

If passwords generation dialog doesn't appear please make sure that:

* AutoFill is enabled: **Settings** → **Passwords & Accounts** → toggle "On" the **AutoFill Passwords**,
* iCloud Keychain is used: **Settings** → **Apple ID** → **iCloud** → **Keychain** → toggle "On" the **iCloud Keychain**.

| Type   |
| ------ |
| string |

***

[Styles](/docs/style)

| Type                     |
| ------------------------ |
| [Text](/docs/text#style) |

***

### `textBreakStrategy`Android[​](#textbreakstrategy-android "Direct link to textbreakstrategy-android")

Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` The default value is `highQuality`.

| Type                                      |
| ----------------------------------------- |
| enum('simple', 'highQuality', 'balanced') |

***

### `underlineColorAndroid`Android[​](#underlinecolorandroid-android "Direct link to underlinecolorandroid-android")

The color of the `TextInput` underline.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `value`[​](#value "Direct link to value")

The value to show for the text input. `TextInput` is a controlled component, which means the native value will be forced to match this value prop if provided. For most uses, this works great, but in some cases this may cause flickering - one common cause is preventing edits by keeping value the same. In addition to setting the same value, either set `editable={false}`, or set/update `maxLength` to prevent unwanted edits without flicker.

| Type   |
| ------ |
| string |

## Methods[​](#methods "Direct link to Methods")

### `.focus()`[​](#focus "Direct link to focus")

React TSX

```
focus();
```

Makes the native input request focus.

### `.blur()`[​](#blur "Direct link to blur")

React TSX

```
blur();
```

Makes the native input lose focus.

### `clear()`[​](#clear "Direct link to clear")

React TSX

```
clear();
```

Removes all text from the `TextInput`.

***

### `isFocused()`[​](#isfocused "Direct link to isfocused")

React TSX

```
isFocused(): boolean;
```

    [iOS](#clearbuttonmode-ios)
  * [`clearTextOnFocus`](#cleartextonfocus-ios)

    [iOS](#cleartextonfocus-ios)
  * [`contextMenuHidden`](#contextmenuhidden)
  * [`dataDetectorTypes`](#datadetectortypes-ios)

    [iOS](#datadetectortypes-ios)
  * [`defaultValue`](#defaultvalue)
  * [`disableKeyboardShortcuts`](#disablekeyboardshortcuts-ios)

    [iOS](#disablekeyboardshortcuts-ios)
  * [`cursorColor`](#cursorcolor-android)

    [Android](#cursorcolor-android)
  * [`disableFullscreenUI`](#disablefullscreenui-android)

    [Android](#disablefullscreenui-android)
  * [`editable`](#editable)
  * [`enablesReturnKeyAutomatically`](#enablesreturnkeyautomatically-ios)

    [iOS](#enablesreturnkeyautomatically-ios)
  * [`enterKeyHint`](#enterkeyhint)
  * [`importantForAutofill`](#importantforautofill-android)

    [Android](#importantforautofill-android)
  * [`inlineImageLeft`](#inlineimageleft-android)

    [Android](#inlineimageleft-android)
  * [`inlineImagePadding`](#inlineimagepadding-android)

    [Android](#inlineimagepadding-android)
  * [`inputAccessoryViewID`](#inputaccessoryviewid-ios)

    [iOS](#inputaccessoryviewid-ios)
  * [`inputAccessoryViewButtonLabel`](#inputaccessoryviewbuttonlabel-ios)

    [iOS](#inputaccessoryviewbuttonlabel-ios)
  * [`inputMode`](#inputmode)
  * [`keyboardAppearance`](#keyboardappearance-ios)

    [iOS](#keyboardappearance-ios)
  * [`keyboardType`](#keyboardtype)
  * [`lineBreakStrategyIOS`](#linebreakstrategyios-ios)

    [iOS](#linebreakstrategyios-ios)
  * [`lineBreakModeIOS`](#linebreakmodeios-ios)

    [iOS](#linebreakmodeios-ios)

    [Android](#returnkeylabel-android)
  * [`returnKeyType`](#returnkeytype)
  * [`rejectResponderTermination`](#rejectrespondertermination-ios)

    [iOS](#rejectrespondertermination-ios)
  * [`rows`](#rows-android)

    [Android](#rows-android)
  * [`scrollEnabled`](#scrollenabled-ios)

    [iOS](#scrollenabled-ios)
  * [`secureTextEntry`](#securetextentry)
  * [`selection`](#selection)
  * [`selectionColor`](#selectioncolor)
  * [`selectionHandleColor`](#selectionhandlecolor-android)

    [Android](#selectionhandlecolor-android)
  * [`selectTextOnFocus`](#selecttextonfocus)
  * [`showSoftInputOnFocus`](#showsoftinputonfocus)
  * [`smartInsertDelete`](#smartinsertdelete-ios)

    [iOS](#smartinsertdelete-ios)
  * [`spellCheck`](#spellcheck-ios)

    [iOS](#spellcheck-ios)
  * [`submitBehavior`](#submitbehavior)
  * [`textAlign`](#textalign)
  * [`textContentType`](#textcontenttype-ios)

    [iOS](#textcontenttype-ios)
  * [`passwordRules`](#passwordrules-ios)

    [iOS](#passwordrules-ios)
  * [`style`](#style)
  * [`textBreakStrategy`](#textbreakstrategy-android)

    [Android](#textbreakstrategy-android)
  * [`underlineColorAndroid`](#underlinecolorandroid-android)

    [Android](#underlinecolorandroid-android)
  * [`value`](#value)

- [Methods](#methods)

  * [`.focus()`](#focus)
  * [`.blur()`](#blur)
  * [`clear()`](#clear)
  * [`isFocused()`](#isfocused)

----
url: https://reactnative.dev/docs/next/legacy/native-components-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/legacy/native-components-android)** (0.87).

Version: Next

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like `ScrollView` and `TextInput`, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, we can wrap up these existing components for seamless integration with your React Native application.

Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with Android SDK programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing `ImageView` component available in the core React Native library.

info

You can also setup local library containing native component with one command. Read the guide to [Local libraries setup](/docs/next/legacy/local-library-setup) for more details.

```
class ReactImageManager(

    private val callerContext: ReactApplicationContext

) : SimpleViewManager<ReactImageView>() {



  override fun getName() = REACT_CLASS



  companion object {

    const val REACT_CLASS = "RCTImageView"

  }

}
```

Java

```
public class ReactImageManager extends SimpleViewManager<ReactImageView> {



  public static final String REACT_CLASS = "RCTImageView";

  ReactApplicationContext mCallerContext;



  public ReactImageManager(ReactApplicationContext reactContext) {

    mCallerContext = reactContext;

  }



  @Override

  public String getName() {

    return REACT_CLASS;

  }

}
```

### 2. Implement method `createViewInstance`[​](#2-implement-method-createviewinstance "Direct link to 2-implement-method-createviewinstance")

Views are created in the `createViewInstance` method, the view should initialize itself in its default state, any properties will be set via a follow up call to `updateView.`

* Java
* Kotlin

Kotlin

```
  override fun createViewInstance(context: ThemedReactContext) =

      ReactImageView(context, Fresco.newDraweeControllerBuilder(), null, callerContext)
```

Java

```
  @Override

  public ReactImageView createViewInstance(ThemedReactContext context) {

    return new ReactImageView(context, Fresco.newDraweeControllerBuilder(), null, mCallerContext);

  }
```

```
  @ReactProp(name = "src")

  fun setSrc(view: ReactImageView, sources: ReadableArray?) {

    view.setSource(sources)

  }



  @ReactProp(name = "borderRadius", defaultFloat = 0f)

  override fun setBorderRadius(view: ReactImageView, borderRadius: Float) {

    view.setBorderRadius(borderRadius)

  }



  @ReactProp(name = ViewProps.RESIZE_MODE)

  fun setResizeMode(view: ReactImageView, resizeMode: String?) {

    view.setScaleType(ImageResizeMode.toScaleType(resizeMode))

  }
```

Java

```
  @ReactProp(name = "src")

  public void setSrc(ReactImageView view, @Nullable ReadableArray sources) {

    view.setSource(sources);

  }



  @ReactProp(name = "borderRadius", defaultFloat = 0f)

  public void setBorderRadius(ReactImageView view, float borderRadius) {

    view.setBorderRadius(borderRadius);

  }



  @ReactProp(name = ViewProps.RESIZE_MODE)

  public void setResizeMode(ReactImageView view, @Nullable String resizeMode) {

    view.setScaleType(ImageResizeMode.toScaleType(resizeMode));

  }
```

### 4. Register the `ViewManager`[​](#4-register-the-viewmanager "Direct link to 4-register-the-viewmanager")

The final step is to register the ViewManager to the application, this happens in a similar way to [Native Modules](/docs/next/legacy/native-modules-android), via the applications package member function `createViewManagers`.

* Java
* Kotlin

Kotlin

```
  override fun createViewManagers(

      reactContext: ReactApplicationContext

  ) = listOf(ReactImageManager(reactContext))
```

Java

```
  @Override

  public List<ViewManager> createViewManagers(

                            ReactApplicationContext reactContext) {

    return Arrays.<ViewManager>asList(

      new ReactImageManager(reactContext)

    );

  }
```

### 5. Implement the JavaScript module[​](#5-implement-the-javascript-module "Direct link to 5. Implement the JavaScript module")

The very final step is to create the JavaScript module that defines the interface layer between Java/Kotlin and JavaScript for the users of your new view. It is recommended for you to document the component interface in this module (e.g. using TypeScript, Flow, or plain old comments).

ImageView\.tsx

```
import {requireNativeComponent} from 'react-native';



/**

 * Composes `View`.

 *

 * - src: Array<{url: string}>

 * - borderRadius: number

 * - resizeMode: 'cover' | 'contain' | 'stretch'

 */

export default requireNativeComponent('RCTImageView');
```

The `requireNativeComponent` function takes the name of the native view. Note that if your component needs to do anything more sophisticated (e.g. custom event handling), you should wrap the native component in another React component. This is illustrated in the `MyCustomView` example below.

## Events[​](#events "Direct link to Events")

So now we know how to expose native view components that we can control freely from JS, but how do we deal with events from the user, like pinch-zooms or panning? When a native event occurs the native code should issue an event to the JavaScript representation of the View, and the two views are linked with the value returned from the `getId()` method.

* Java
* Kotlin

Kotlin

```
class MyCustomView(context: Context) : View(context) {

  ...

  fun onReceiveNativeEvent() {

    val event = Arguments.createMap().apply {

      putString("message", "MyMessage")

    }

    val reactContext = context as ReactContext

    reactContext

        .getJSModule(RCTEventEmitter::class.java)

        .receiveEvent(id, "topChange", event)

  }

}
```

Java

```
class MyCustomView extends View {

   ...

   public void onReceiveNativeEvent() {

      WritableMap event = Arguments.createMap();

      event.putString("message", "MyMessage");

      ReactContext reactContext = (ReactContext)getContext();

      reactContext

          .getJSModule(RCTEventEmitter.class)

          .receiveEvent(getId(), "topChange", event);

    }

}
```

To map the `topChange` event name to the `onChange` callback prop in JavaScript, register it by overriding the `getExportedCustomBubblingEventTypeConstants` method in your `ViewManager`:

* Java
* Kotlin

Kotlin

```
class ReactImageManager : SimpleViewManager<MyCustomView>() {

  ...

  override fun getExportedCustomBubblingEventTypeConstants(): Map<String, Any> {

    return mapOf(

      "topChange" to mapOf(

        "phasedRegistrationNames" to mapOf(

          "bubbled" to "onChange"

        )

      )

    )

  }

}
```

Java

```
public class ReactImageManager extends SimpleViewManager<MyCustomView> {

    ...

    public Map getExportedCustomBubblingEventTypeConstants() {

        return MapBuilder.builder().put(

            "topChange",

            MapBuilder.of(

                "phasedRegistrationNames",

                MapBuilder.of("bubbled", "onChange")

            )

        ).build();

    }

}
```

This callback is invoked with the raw event, which we typically process in the wrapper component to make a simpler API:

MyCustomView\.tsx

```
import {useCallback} from 'react';

import {requireNativeComponent} from 'react-native';



const RCTMyCustomView = requireNativeComponent('RCTMyCustomView');



export default function MyCustomView(props: {

  // ...

  /**

   * Callback that is called continuously when the user is dragging the map.

   */

  onChangeMessage: (message: string) => unknown;

}) {

  const onChange = useCallback(

    event => {

      props.onChangeMessage?.(event.nativeEvent.message);

    },

    [props.onChangeMessage],

  );



  return <RCTMyCustomView {...props} onChange={onChange} />;

}
```

```
// replace with your package

package com.mypackage



import android.content.Context

import android.graphics.Color

import android.widget.FrameLayout

import android.widget.TextView



class CustomView(context: Context) : FrameLayout(context) {

  init {

    // set padding and background color

    setPadding(16,16,16,16)

    setBackgroundColor(Color.parseColor("#5FD3F3"))



    // add default text view

    addView(TextView(context).apply {

      text = "Welcome to Android Fragments with React Native."

    })

  }

}
```

CustomView\.java

```
// replace with your package

package com.mypackage;



import android.content.Context;

import android.graphics.Color;

import android.widget.FrameLayout;

import android.widget.ImageView;

import android.widget.TextView;



import androidx.annotation.NonNull;



public class CustomView extends FrameLayout {

  public CustomView(@NonNull Context context) {

    super(context);

    // set padding and background color

    this.setPadding(16,16,16,16);

    this.setBackgroundColor(Color.parseColor("#5FD3F3"));



    // add default text view

    TextView text = new TextView(context);

    text.setText("Welcome to Android Fragments with React Native.");

    this.addView(text);

  }

}
```

### 2. Create a `Fragment`[​](#2-create-a-fragment "Direct link to 2-create-a-fragment")

* Java
* Kotlin

MyFragment.kt

```
// replace with your package

package com.mypackage



import android.os.Bundle

import android.view.LayoutInflater

import android.view.View

import android.view.ViewGroup

import androidx.fragment.app.Fragment



// replace with your view's import

import com.mypackage.CustomView



class MyFragment : Fragment() {

  private lateinit var customView: CustomView



  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {

    super.onCreateView(inflater, container, savedInstanceState)

    customView = CustomView(requireNotNull(context))

    return customView // this CustomView could be any view that you want to render

  }



  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    super.onViewCreated(view, savedInstanceState)

    // do any logic that should happen in an `onCreate` method, e.g:

    // customView.onCreate(savedInstanceState);

  }



  override fun onPause() {

    super.onPause()

    // do any logic that should happen in an `onPause` method

    // e.g.: customView.onPause();

  }



  override fun onResume() {

    super.onResume()

    // do any logic that should happen in an `onResume` method

    // e.g.: customView.onResume();

  }



  override fun onDestroy() {

    super.onDestroy()

    // do any logic that should happen in an `onDestroy` method

    // e.g.: customView.onDestroy();

  }

}
```

MyFragment.java

```
// replace with your package

package com.mypackage;



import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import androidx.fragment.app.Fragment;



// replace with your view's import

import com.mypackage.CustomView;



public class MyFragment extends Fragment {

    CustomView customView;



    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {

        super.onCreateView(inflater, parent, savedInstanceState);

        customView = new CustomView(this.getContext());

        return customView; // this CustomView could be any view that you want to render

    }



    @Override

    public void onViewCreated(View view, Bundle savedInstanceState) {

        super.onViewCreated(view, savedInstanceState);

        // do any logic that should happen in an `onCreate` method, e.g:

        // customView.onCreate(savedInstanceState);

    }



    @Override

    public void onPause() {

        super.onPause();

        // do any logic that should happen in an `onPause` method

        // e.g.: customView.onPause();

    }



    @Override

    public void onResume() {

        super.onResume();

       // do any logic that should happen in an `onResume` method

       // e.g.: customView.onResume();

    }



    @Override

    public void onDestroy() {

        super.onDestroy();

        // do any logic that should happen in an `onDestroy` method

        // e.g.: customView.onDestroy();

    }

}
```

### 3. Create the `ViewManager` subclass[​](#3-create-the-viewmanager-subclass "Direct link to 3-create-the-viewmanager-subclass")

* Java
* Kotlin

MyViewManager.kt

```
// replace with your package

package com.mypackage



import android.view.Choreographer

import android.view.View

import android.view.ViewGroup

import android.widget.FrameLayout

import androidx.fragment.app.FragmentActivity

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.bridge.ReadableArray

import com.facebook.react.uimanager.ThemedReactContext

import com.facebook.react.uimanager.ViewGroupManager

import com.facebook.react.uimanager.annotations.ReactPropGroup



class MyViewManager(

    private val reactContext: ReactApplicationContext

) : ViewGroupManager<FrameLayout>() {

  private var propWidth: Int? = null

  private var propHeight: Int? = null



  override fun getName() = REACT_CLASS



  /**

   * Return a FrameLayout which will later hold the Fragment

   */

  override fun createViewInstance(reactContext: ThemedReactContext) =

      FrameLayout(reactContext)



  /**

   * Map the "create" command to an integer

   */

  override fun getCommandsMap() = mapOf("create" to COMMAND_CREATE)



  /**

   * Handle "create" command (called from JS) and call createFragment method

   */

  override fun receiveCommand(

      root: FrameLayout,

      commandId: String,

      args: ReadableArray?

  ) {

    super.receiveCommand(root, commandId, args)

    val reactNativeViewId = requireNotNull(args).getInt(0)



    when (commandId.toInt()) {

      COMMAND_CREATE -> createFragment(root, reactNativeViewId)

    }

  }



  @ReactPropGroup(names = ["width", "height"], customType = "Style")

  fun setStyle(view: FrameLayout, index: Int, value: Int) {

    if (index == 0) propWidth = value

    if (index == 1) propHeight = value

  }



  /**

   * Replace your React Native view with a custom fragment

   */

  fun createFragment(root: FrameLayout, reactNativeViewId: Int) {

    val parentView = root.findViewById<ViewGroup>(reactNativeViewId)

    setupLayout(parentView)



    val myFragment = MyFragment()

    val activity = reactContext.currentActivity as FragmentActivity

    activity.supportFragmentManager

        .beginTransaction()

        .replace(reactNativeViewId, myFragment, reactNativeViewId.toString())

        .commit()

  }



  fun setupLayout(view: View) {

    Choreographer.getInstance().postFrameCallback(object: Choreographer.FrameCallback {

      override fun doFrame(frameTimeNanos: Long) {

        manuallyLayoutChildren(view)

        view.viewTreeObserver.dispatchOnGlobalLayout()

        Choreographer.getInstance().postFrameCallback(this)

      }

    })

  }



  /**

   * Layout all children properly

   */

  private fun manuallyLayoutChildren(view: View) {

    // propWidth and propHeight coming from react-native props

    val width = requireNotNull(propWidth)

    val height = requireNotNull(propHeight)



    view.measure(

        View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),

        View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY))



    view.layout(0, 0, width, height)

  }



  companion object {

    private const val REACT_CLASS = "MyViewManager"

    private const val COMMAND_CREATE = 1

  }

}
```

MyViewManager.java

```
// replace with your package

package com.mypackage;



import android.view.Choreographer;

import android.view.View;

import android.view.ViewGroup;

import android.widget.FrameLayout;



import androidx.annotation.NonNull;

import androidx.annotation.Nullable;

import androidx.fragment.app.FragmentActivity;



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.bridge.ReadableArray;

import com.facebook.react.common.MapBuilder;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.uimanager.annotations.ReactPropGroup;

import com.facebook.react.uimanager.ViewGroupManager;

import com.facebook.react.uimanager.ThemedReactContext;



import java.util.Map;



public class MyViewManager extends ViewGroupManager<FrameLayout> {



  public static final String REACT_CLASS = "MyViewManager";

  public final int COMMAND_CREATE = 1;

  private int propWidth;

  private int propHeight;



  ReactApplicationContext reactContext;



  public MyViewManager(ReactApplicationContext reactContext) {

    this.reactContext = reactContext;

  }



  @Override

  public String getName() {

    return REACT_CLASS;

  }



  /**

   * Return a FrameLayout which will later hold the Fragment

   */

  @Override

  public FrameLayout createViewInstance(ThemedReactContext reactContext) {

    return new FrameLayout(reactContext);

  }



  /**

   * Map the "create" command to an integer

   */

  @Nullable

  @Override

  public Map<String, Integer> getCommandsMap() {

    return MapBuilder.of("create", COMMAND_CREATE);

  }



  /**

   * Handle "create" command (called from JS) and call createFragment method

   */

  @Override

  public void receiveCommand(

    @NonNull FrameLayout root,

    String commandId,

    @Nullable ReadableArray args

  ) {

    super.receiveCommand(root, commandId, args);

    int reactNativeViewId = args.getInt(0);

    int commandIdInt = Integer.parseInt(commandId);



    switch (commandIdInt) {

      case COMMAND_CREATE:

        createFragment(root, reactNativeViewId);

        break;

      default: {}

    }

  }



  @ReactPropGroup(names = {"width", "height"}, customType = "Style")

  public void setStyle(FrameLayout view, int index, Integer value) {

    if (index == 0) {

      propWidth = value;

    }



    if (index == 1) {

      propHeight = value;

    }

  }



  /**

   * Replace your React Native view with a custom fragment

   */

  public void createFragment(FrameLayout root, int reactNativeViewId) {

    ViewGroup parentView = (ViewGroup) root.findViewById(reactNativeViewId);

    setupLayout(parentView);



    final MyFragment myFragment = new MyFragment();

    FragmentActivity activity = (FragmentActivity) reactContext.getCurrentActivity();

    activity.getSupportFragmentManager()

            .beginTransaction()

            .replace(reactNativeViewId, myFragment, String.valueOf(reactNativeViewId))

            .commit();

  }



  public void setupLayout(View view) {

    Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {

      @Override

      public void doFrame(long frameTimeNanos) {

        manuallyLayoutChildren(view);

        view.getViewTreeObserver().dispatchOnGlobalLayout();

        Choreographer.getInstance().postFrameCallback(this);

      }

    });

  }



  /**

   * Layout all children properly

   */

  public void manuallyLayoutChildren(View view) {

      // propWidth and propHeight coming from react-native props

      int width = propWidth;

      int height = propHeight;



      view.measure(

              View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),

              View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));



      view.layout(0, 0, width, height);

  }

}
```

### 4. Register the `ViewManager`[​](#4-register-the-viewmanager-1 "Direct link to 4-register-the-viewmanager-1")

* Java
* Kotlin

MyPackage.kt

```
// replace with your package

package com.mypackage



import com.facebook.react.ReactPackage

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.uimanager.ViewManager



class MyPackage : ReactPackage {

  ...

  override fun createViewManagers(

      reactContext: ReactApplicationContext

  ) = listOf(MyViewManager(reactContext))

}
```

MyPackage.java

```
// replace with your package

package com.mypackage;



import com.facebook.react.ReactPackage;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.uimanager.ViewManager;



import java.util.Arrays;

import java.util.List;



public class MyPackage implements ReactPackage {



   @Override

   public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {

       return Arrays.<ViewManager>asList(

            new MyViewManager(reactContext)

       );

   }



}
```

### 5. Register the `Package`[​](#5-register-the-package "Direct link to 5-register-the-package")

* Java
* Kotlin

MainApplication.kt

```
override fun getPackages(): List<ReactPackage> =

    PackageList(this).packages.apply {

        // Packages that cannot be autolinked yet can be added manually here, for example:

        // add(MyReactNativePackage())

        add(MyAppPackage())

    }
```

MainApplication.java

```
@Override

protected List<ReactPackage> getPackages() {

    List<ReactPackage> packages = new PackageList(this).getPackages();

    // Packages that cannot be autolinked yet can be added manually here, for example:

    // packages.add(new MyReactNativePackage());

    packages.add(new MyAppPackage());

    return packages;

}
```

### 6. Implement the JavaScript module[​](#6-implement-the-javascript-module "Direct link to 6. Implement the JavaScript module")

I. Start with custom View manager:

MyViewManager.tsx

```
import {requireNativeComponent} from 'react-native';



export const MyViewManager =

  requireNativeComponent('MyViewManager');
```

II. Then implement custom View calling the `create` method:

MyView\.tsx

```
import {useEffect, useRef} from 'react';

import {

  PixelRatio,

  UIManager,

  findNodeHandle,

} from 'react-native';



import {MyViewManager} from './my-view-manager';



const createFragment = viewId =>

  UIManager.dispatchViewManagerCommand(

    viewId,

    // we are calling the 'create' command

    UIManager.MyViewManager.Commands.create.toString(),

    [viewId],

  );



export const MyView = () => {

  const ref = useRef(null);



  useEffect(() => {

    const viewId = findNodeHandle(ref.current);

    createFragment(viewId);

  }, []);



  return (

    <MyViewManager

      style={{

        // converts dpi to px, provide desired height

        height: PixelRatio.getPixelSizeForLayoutSize(200),

        // converts dpi to px, provide desired width

        width: PixelRatio.getPixelSizeForLayoutSize(200),

      }}

      ref={ref}

    />

  );

};
```

----
url: https://reactnative.dev/docs/testing-overview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React Native comes with two such tools configured out of the box: [ESLint](https://eslint.org/) for linting and [TypeScript](/docs/typescript) for type checking.

```
it('given a date in the past, colorForDueDate() returns red', () => {

  expect(colorForDueDate('2000-10-20')).toBe('red');

});
```

```
function GroceryShoppingList() {

  const [groceryItem, setGroceryItem] = useState('');

  const [items, setItems] = useState<string[]>([]);



  const addNewItemToShoppingList = useCallback(() => {

    setItems([groceryItem, ...items]);

    setGroceryItem('');

  }, [groceryItem, items]);



  return (

    <>

      <TextInput

        value={groceryItem}

        placeholder="Enter grocery item"

        onChangeText={text => setGroceryItem(text)}

      />

      <Button

        title="Add the item to list"

        onPress={addNewItemToShoppingList}

      />

      {items.map(item => (

        <Text key={item}>{item}</Text>

      ))}

    </>

  );

}
```

```
test('given empty GroceryShoppingList, user can add an item to it', () => {

  const {getByPlaceholderText, getByText, getAllByText} = render(

    <GroceryShoppingList />,

  );



  fireEvent.changeText(

    getByPlaceholderText('Enter grocery item'),

    'banana',

  );

  fireEvent.press(getByText('Add the item to list'));



  const bananaElements = getAllByText('banana');

  expect(bananaElements).toHaveLength(1); // expect 'banana' to be on the list

});
```

This example is not testing how some state changes when you call a function. It tests what happens when a user changes text in the `TextInput` and presses the `Button`!

### Testing Rendered Output[​](#testing-rendered-output "Direct link to Testing Rendered Output")

[Snapshot testing](https://jestjs.io/docs/en/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:

React TSX

```
<Text

  style={

    Object {

      "fontSize": 20,

      "textAlign": "center",

    }

  }>

  Welcome to React Native!

</Text>
```

***

----
url: https://reactnative.dev/docs/next/the-new-architecture/advanced-topics-modules
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/advanced-topics-modules)** (0.87).

Version: Next

This document contains a set of advanced topics to implement more complex functionalities of Native Modules. It is recommended to first read the [Codegen](/docs/the-new-architecture/what-is-codegen) section and the guides on [Native Modules](/docs/turbo-native-modules-introduction).

This guide will cover the following topics:

* [Add custom C++ types to your C++ modules](/docs/the-new-architecture/custom-cxx-types)
* [Use Swift in your Module](/docs/next/the-new-architecture/turbo-modules-with-swift)
* [Emit custom events from your Native Modules](/docs/next/the-new-architecture/native-modules-custom-events)
* [Native Modules Lifecycle](/docs/next/the-new-architecture/native-modules-lifecycle)

----
url: https://reactnative.dev/docs/next/statusbar
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/statusbar)** (0.87).

Version: Next

***

# Reference

## Constants[​](#constants "Direct link to Constants")

### `currentHeight`Android[​](#currentheight-android "Direct link to currentheight-android")

The height of the status bar, which includes the notch height, if present.

***

## Props[​](#props "Direct link to Props")

### `animated`[​](#animated "Direct link to animated")

If the transition between status bar property changes should be animated. Supported for `barStyle` and `hidden` properties.

| Type    | Required | Default |
| ------- | -------- | ------- |
| boolean | No       | `false` |

***

### `barStyle`[​](#barstyle "Direct link to barstyle")

Sets the color of the status bar text.

On Android, this will only have an impact on API versions 23 and above.

| Type                                                  | Required | Default     |
| ----------------------------------------------------- | -------- | ----------- |
| [StatusBarStyle](/docs/next/statusbar#statusbarstyle) | No       | `'default'` |

***

### `hidden`[​](#hidden "Direct link to hidden")

If the status bar is hidden.

| Type    | Required | Default |
| ------- | -------- | ------- |
| boolean | No       | `false` |

***

### `showHideTransition`iOS[​](#showhidetransition-ios "Direct link to showhidetransition-ios")

The transition effect when showing and hiding the status bar using the `hidden` prop.

| Type                                                          | Default  |
| ------------------------------------------------------------- | -------- |
| [StatusBarAnimation](/docs/next/statusbar#statusbaranimation) | `'fade'` |

## Methods[​](#methods "Direct link to Methods")

### `popStackEntry()`[​](#popstackentry "Direct link to popstackentry")

React TSX

```
static popStackEntry(entry: StatusBarProps);
```

Get and remove the last StatusBar entry from the stack.

**Parameters:**

| Name          | Type | Description                           |
| ------------- | ---- | ------------------------------------- |
| entryRequired | any  | Entry returned from `pushStackEntry`. |

***

### `pushStackEntry()`[​](#pushstackentry "Direct link to pushstackentry")

React TSX

```
static pushStackEntry(props: StatusBarProps): StatusBarProps;
```

Push a StatusBar entry onto the stack. The return value should be passed to `popStackEntry` when complete.

**Parameters:**

| Name          | Type | Description                                                      |
| ------------- | ---- | ---------------------------------------------------------------- |
| propsRequired | any  | Object containing the StatusBar props to use in the stack entry. |

***

### `replaceStackEntry()`[​](#replacestackentry "Direct link to replacestackentry")

React TSX

```
static replaceStackEntry(

  entry: StatusBarProps,

  props: StatusBarProps

): StatusBarProps;
```

Replace an existing StatusBar stack entry with new props.

**Parameters:**

| Name          | Type | Description                                                                  |
| ------------- | ---- | ---------------------------------------------------------------------------- |
| entryRequired | any  | Entry returned from `pushStackEntry` to replace.                             |
| propsRequired | any  | Object containing the StatusBar props to use in the replacement stack entry. |

***

### `setBarStyle()`[​](#setbarstyle "Direct link to setbarstyle")

React TSX

```
static setBarStyle(style: StatusBarStyle, animated?: boolean);
```

Set the status bar style.

**Parameters:**

| Name          | Type                                                  | Description               |
| ------------- | ----------------------------------------------------- | ------------------------- |
| styleRequired | [StatusBarStyle](/docs/next/statusbar#statusbarstyle) | Status bar style to set.  |
| animated      | boolean                                               | Animate the style change. |

***

### `setHidden()`[​](#sethidden "Direct link to sethidden")

React TSX

```
static setHidden(hidden: boolean, animation?: StatusBarAnimation);
```

Show or hide the status bar.

**Parameters:**

| Name           | Type                                                          | Description                                             |
| -------------- | ------------------------------------------------------------- | ------------------------------------------------------- |
| hiddenRequired | boolean                                                       | Hide the status bar.                                    |
| animationiOS   | [StatusBarAnimation](/docs/next/statusbar#statusbaranimation) | Animation when changing the status bar hidden property. |

***

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### StatusBarAnimation[​](#statusbaranimation "Direct link to StatusBarAnimation")

Status bar animation type for transitions on the iOS.

| Type |
| ---- |
| enum |

**Constants:**

| Value     | Type   | Description     |
| --------- | ------ | --------------- |
| `'fade'`  | string | Fade animation  |
| `'slide'` | string | Slide animation |
| `'none'`  | string | No animation    |

***

### StatusBarStyle[​](#statusbarstyle "Direct link to StatusBarStyle")

Status bar style type.

| Type |
| ---- |
| enum |

**Constants:**

| Value             | Type   | Description                                                                                                                         |
| ----------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `'default'`       | string | Default status bar style (light for Android, dark for iOS)                                                                          |
| `'auto'`          | string | Automatically picks `light-content` or `dark-content` based on the current color scheme. Updates whenever the color scheme changes. |
| `'light-content'` | string | White texts and icons                                                                                                               |
| `'dark-content'`  | string | Dark texts and icons (requires API>=23 on Android)                                                                                  |

* [Usage with Navigator](#usage-with-navigator)

* [Imperative API](#imperative-api)

* [Constants](#constants)
  * [`currentHeight`](#currentheight-android)

    [Android](#currentheight-android)

* [Props](#props)

  * [`animated`](#animated)
  * [`barStyle`](#barstyle)
  * [`hidden`](#hidden)
  * [`showHideTransition`](#showhidetransition-ios)

    [iOS](#showhidetransition-ios)

----
url: https://reactnative.dev/docs/next/the-new-architecture/pure-cxx-modules
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/pure-cxx-modules)** (0.87).

Version: Next

```
npx @react-native-community/cli@latest init SampleApp --version "latest"
```

```
// @flow

import type {TurboModule} from 'react-native'

import { TurboModuleRegistry } from "react-native";



export interface Spec extends TurboModule {

  +reverseString: (input: string) => string;

}



export default (TurboModuleRegistry.getEnforcing<Spec>(

  "NativeSampleModule"

): Spec);
```

specs/NativeSampleModule.ts

```
import {TurboModule, TurboModuleRegistry} from 'react-native';



export interface Spec extends TurboModule {

  readonly reverseString: (input: string) => string;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeSampleModule',

);
```

## 2. Configure Codegen[​](#2-configure-codegen "Direct link to 2. Configure Codegen")

The next step is to configure [Codegen](/docs/next/the-new-architecture/what-is-codegen) in your `package.json`. Update the file to include:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "AppSpecs",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.sampleapp.specs"

     }

   },

   "dependencies": {
```

This configuration tells Codegen to look for spec files in the `specs` folder. It also instructs Codegen to only generate code for `modules` and to namespace the generated code as `AppSpecs`.

## 3. Write the Native Code[​](#3-write-the-native-code "Direct link to 3. Write the Native Code")

Writing a C++ Turbo Native Module allows you to share the code between Android and iOS. Therefore we will be writing the code once, and we will look into what changes we need to apply to the platforms so that the C++ code can be picked up.

1. Create a folder named `shared` at the same level as the `android` and `ios` folders.

2. Inside the `shared` folder, create a new file called `NativeSampleModule.h`.

   shared/NativeSampleModule.h

   ```
   #pragma once



   #include <AppSpecsJSI.h>



   #include <memory>

   #include <string>



   namespace facebook::react {



   class NativeSampleModule : public NativeSampleModuleCxxSpec<NativeSampleModule> {

   public:

     NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker);



     std::string reverseString(jsi::Runtime& rt, std::string input);

   };



   } // namespace facebook::react
   ```

3. Inside the `shared` folder, create a new file called `NativeSampleModule.cpp`.

   shared/NativeSampleModule.cpp

   ```
   #include "NativeSampleModule.h"



   namespace facebook::react {



   NativeSampleModule::NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker)

       : NativeSampleModuleCxxSpec(std::move(jsInvoker)) {}



   std::string NativeSampleModule::reverseString(jsi::Runtime& rt, std::string input) {

     return std::string(input.rbegin(), input.rend());

   }



   } // namespace facebook::react
   ```

```
cmake_minimum_required(VERSION 3.13)



# Define the library name here.

project(appmodules)



# This file includes all the necessary to let you build your React Native application

include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake)



# Define where the additional source code lives. We need to crawl back the jni, main, src, app, android folders

target_sources(${CMAKE_PROJECT_NAME} PRIVATE ../../../../../shared/NativeSampleModule.cpp)



# Define where CMake can find the additional header files. We need to crawl back the jni, main, src, app, android folders

target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC ../../../../../shared)
```

```
    buildTypes {

        debug {

            signingConfig signingConfigs.debug

        }

        release {

            // Caution! In production, you need to generate your own keystore file.

            // see https://reactnative.dev/docs/signed-apk-android.

            signingConfig signingConfigs.debug

            minifyEnabled enableProguardInReleaseBuilds

            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"

        }

    }



+   externalNativeBuild {

+       cmake {

+           path "src/main/jni/CMakeLists.txt"

+       }

+   }

}
```

This block tells the Gradle file where to look for the CMake file. The path is relative to the folder where the `build.gradle` file lives, so we need to add the path to the `CMakeLists.txt` files in the `jni` folder.

#### 3. Register the new Turbo Native Module[​](#3-register-the-new-turbo-native-module "Direct link to 3. Register the new Turbo Native Module")

The final step is to register the new C++ Turbo Native Module in the runtime, so that when JS requires the C++ Turbo Native Module, the app knows where to find it and can return it.

1. From the folder `SampleApp/android/app/src/main/jni`, run the following command:

shell

```
curl -O https://raw.githubusercontent.com/react/react-native/main/packages/react-native/ReactAndroid/cmake-utils/default-app-setup/OnLoad.cpp
```

2. Then, modify this file as follows:

android/app/src/main/jni/OnLoad.cpp

```
#include <DefaultComponentsRegistry.h>

#include <DefaultTurboModuleManagerDelegate.h>

#include <autolinking.h>

#include <fbjni/fbjni.h>

#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>

#include <rncore.h>



+ // Include the NativeSampleModule header

+ #include <NativeSampleModule.h>



//...



std::shared_ptr<TurboModule> cxxModuleProvider(

    const std::string& name,

    const std::shared_ptr<CallInvoker>& jsInvoker) {

  // Here you can provide your CXX Turbo Modules coming from

  // either your application or from external libraries. The approach to follow

  // is similar to the following (for a module called `NativeCxxModuleExample`):

  //

  // if (name == NativeCxxModuleExample::kModuleName) {

  //   return std::make_shared<NativeCxxModuleExample>(jsInvoker);

  // }



+  // This code registers the module so that when the JS side asks for it, the app can return it

+  if (name == NativeSampleModule::kModuleName) {

+    return std::make_shared<NativeSampleModule>(jsInvoker);

+  }



  // And we fallback to the CXX module providers autolinked

  return autolinking_cxxModuleProvider(name, jsInvoker);

}



// leave the rest of the file
```

```
cd ios

bundle install

bundle exec pod install
```

#### 2. Add the shared folder to the iOS project[​](#2-add-the-shared-folder-to-the-ios-project "Direct link to 2. Add the shared folder to the iOS project")

This step adds the `shared` folder to the project to make it visible to Xcode.

1. Open the CocoaPods generated Xcode Workspace.

```
cd ios

open SampleApp.xcworkspace
```

```


#import <Foundation/Foundation.h>

#import <ReactCommon/RCTTurboModule.h>



NS_ASSUME_NONNULL_BEGIN



@interface NativeSampleModuleProvider : NSObject <RCTModuleProvider>



@end



NS_ASSUME_NONNULL_END
```

This declares a `NativeSampleModuleProvider` object that conforms to the `RCTModuleProvider` protocol.

7. Implement the content of the `NativeSampleModuleProvider.mm` with the following:

NativeSampleModuleProvider.mm

```


#import "NativeSampleModuleProvider.h"

#import <ReactCommon/CallInvoker.h>

#import <ReactCommon/TurboModule.h>

#import "NativeSampleModule.h"



@implementation NativeSampleModuleProvider



- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:

    (const facebook::react::ObjCTurboModule::InitParams &)params

{

  return std::make_shared<facebook::react::NativeSampleModule>(params.jsInvoker);

}



@end
```

This code implements the `RCTModuleProvider` protocol by creating the pure C++ `NativeSampleModule` when the `getTurboModule:` method is called.

##### 3.2 Update the package.json[​](#32-update-the-packagejson "Direct link to 3.2 Update the package.json")

The last step consists in updating the `package.json` to tell React Native about the link between the JS specs of the Native Module and the concrete implementation of those spec in native code.

Modify the `package.json` as it follows:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "AppSpecs",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.sampleapp.specs"

     },

     "ios": {

        "modulesProvider": {

          "NativeSampleModule":  "NativeSampleModuleProvider"

        }

     }

   },



   "dependencies": {
```

At this point, you need to re-install the pods to make sure that codegen runs again to generate the new files:

```
# from the ios folder

bundle exec pod install

open SampleApp.xcworkspace
```

If you now build your application from Xcode, you should be able to build successfully.

## 5. Testing your Code[​](#5-testing-your-code "Direct link to 5. Testing your Code")

It's now time to access our C++ Turbo Native Module from JS. To do so, we have to modify the `App.tsx` file to import the Turbo Native Module and to call it in our code.

1. Open the `App.tsx` file.
2. Replace the content of the template with the following code:

App.tsx

```
import {type JSX, useState} from 'react';

import {

  Button,

  SafeAreaView,

  StyleSheet,

  Text,

  TextInput,

  View,

} from 'react-native';

import SampleTurboModule from './specs/NativeSampleModule';



function App(): JSX.Element {

  const [value, setValue] = useState('');

  const [reversedValue, setReversedValue] = useState('');



  const onPress = () => {

    const revString = SampleTurboModule.reverseString(value);

    setReversedValue(revString);

  };



  return (

    <SafeAreaView style={styles.container}>

      <View>

        <Text style={styles.title}>

          Welcome to C++ Turbo Native Module Example

        </Text>

        <Text>Write down here the text you want to reverse</Text>

        <TextInput

          style={styles.textInput}

          placeholder="Write your text here"

          onChangeText={setValue}

          value={value}

        />

        <Button title="Reverse" onPress={onPress} />

        <Text>Reversed text: {reversedValue}</Text>

      </View>

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

  },

  title: {

    fontSize: 18,

    marginBottom: 20,

  },

  textInput: {

    borderColor: 'black',

    borderWidth: 1,

    borderRadius: 5,

    padding: 10,

    marginTop: 10,

  },

});



export default App;
```

The interesting lines in this app are:

* `import SampleTurboModule from './specs/NativeSampleModule';`: this line imports the Turbo Native Module in the app,
* `const revString = SampleTurboModule.reverseString(value);` in the `onPress` callback: this is how you can use the Turbo Native Module in your app.

warning

For the sake of this example and to keep it as short as possible, we directly imported the spec file in our app. The best practice in this case is to create a separate file to wrap the specs and use that file into your application. This allows you to prepare the input for the specs and gives you more control over them in JS.

Congratulations, you wrote your first C++ Turbo Native Module!

| Android | iOS |
| ------- | --- |
|         |     |

----
url: https://reactnative.dev/docs/next/the-new-architecture/fabric-component-native-commands
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/fabric-component-native-commands)** (0.87).

Version: Next

```
import type {HostComponent, ViewProps} from 'react-native';

import type {BubblingEventHandler} from 'react-native/Libraries/Types/CodegenTypes';

import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

+import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands';



type WebViewScriptLoadedEvent = {

  result: 'success' | 'error';

};



export interface NativeProps extends ViewProps {

  sourceURL?: string;

  onScriptLoaded?: BubblingEventHandler<WebViewScriptLoadedEvent> | null;

}



+interface NativeCommands {

+    reload: (viewRef: React.ElementRef<HostComponent<NativeProps>>) => void;

+}



+export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({

+    supportedCommands: ['reload'],

+});



export default codegenNativeComponent<NativeProps>(

  'CustomWebView',

) as HostComponent<NativeProps>;
```

Update the `WebViewNativeComponent.js` as it follows:

Demo/specs/WebViewNativeComponent.js

```
// @flow strict-local



import type {HostComponent, ViewProps} from 'react-native';

import type {BubblingEventHandler} from 'react-native/Libraries/Types/CodegenTypes';

import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

+import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands';



type WebViewScriptLoadedEvent = $ReadOnly<{|

  result: "success" | "error",

|}>;



type NativeProps = $ReadOnly<{|

  ...ViewProps,

  sourceURL?: string;

  onScriptLoaded?: BubblingEventHandler<WebViewScriptLoadedEvent>?;

|}>;



+interface NativeCommands {

+    reload: (viewRef: React.ElementRef<HostComponent<NativeProps>>) => void;

+}



+export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({

+    supportedCommands: ['reload'],

+});



export default (codegenNativeComponent<NativeProps>(

  'CustomWebView',

): HostComponent<NativeProps>);
```

```
-import {Alert, StyleSheet, View} from 'react-native';

-import WebView from '../specs/WebViewNativeComponent';

+import {Alert, StyleSheet, Pressable, Text, View} from 'react-native';

+import WebView, {Commands} from '../specs/WebViewNativeComponent';



function App(): React.JSX.Element {

+    const webViewRef = React.useRef<React.ElementRef<typeof View> | null>(null);

+

+    const refresh = () => {

+        if (webViewRef.current) {

+            Commands.reload(webViewRef.current);

+        }

+    };



  return (

    <View style={styles.container}>

      <WebView

+       ref={webViewRef}

        sourceURL="https://react.dev/"

        style={styles.webview}

        onScriptLoaded={() => {

          Alert.alert('Page Loaded');

        }}

      />

+      <View style={styles.tabbar}>

+        <Pressable onPress={refresh} style={styles.button}>

+            {({pressed}) => (

+                !pressed ? <Text style={styles.buttonText}>Refresh</Text> : <Text style={styles.buttonTextPressed}>Refresh</Text>) }

+        </Pressable>

+      </View>

    </View>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    alignItems: 'center',

    alignContent: 'center',

  },

  webview: {

    width: '100%',

-    height: '100%',

+    height: '90%',

  },

+  tabbar: {

+    flex: 1,

+    backgroundColor: 'gray',

+    width: '100%',

+    alignItems: 'center',

+    alignContent: 'center',

+  },

+  button: {

+    margin: 10,

+  },

+  buttonText: {

+    fontSize: 20,

+    fontWeight: 'bold',

+    color: '#00D6FF',

+    width: '100%',

+  },

+  buttonTextPressed: {

+    fontSize: 20,

+    fontWeight: 'bold',

+    color: '#00D6FF77',

+    width: '100%',

+  },

});



export default App;
```

Open the `App.tsx` file and modify it as it follows:

App.jsx

```
-import {Alert, StyleSheet, View} from 'react-native';

-import WebView from '../specs/WebViewNativeComponent';

+import {Alert, StyleSheet, Pressable, Text, View} from 'react-native';

+import WebView, {Commands} from '../specs/WebViewNativeComponent';



function App(): React.JSX.Element {

+    const webViewRef = React.useRef<React.ElementRef<typeof View> | null>(null);

+

+    const refresh = () => {

+        if (webViewRef.current) {

+            Commands.reload(webViewRef.current);

+        }

+    };



  return (

    <View style={styles.container}>

      <WebView

+       ref={webViewRef}

        sourceURL="https://react.dev/"

        style={styles.webview}

        onScriptLoaded={() => {

          Alert.alert('Page Loaded');

        }}

      />

+      <View style={styles.tabbar}>

+        <Pressable onPress={refresh} style={styles.button}>

+            {({pressed}) => (

+                !pressed ? <Text style={styles.buttonText}>Refresh</Text> : <Text style={styles.buttonTextPressed}>Refresh</Text>) }

+        </Pressable>

+      </View>

    </View>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    alignItems: 'center',

    alignContent: 'center',

  },

  webview: {

    width: '100%',

-    height: '100%',

+    height: '90%',

  },

+  tabbar: {

+    flex: 1,

+    backgroundColor: 'gray',

+    width: '100%',

+    alignItems: 'center',

+    alignContent: 'center',

+  },

+  button: {

+    margin: 10,

+  },

+  buttonText: {

+    fontSize: 20,

+    fontWeight: 'bold',

+    color: '#00D6FF',

+    width: '100%',

+  },

+  buttonTextPressed: {

+    fontSize: 20,

+    fontWeight: 'bold',

+    color: '#00D6FF77',

+    width: '100%',

+  },

});



export default App;
```

```
cd android

./gradlew generateCodegenArtifactsFromSchema



BUILD SUCCESSFUL in 837ms

14 actionable tasks: 3 executed, 11 up-to-date
```

This is automatically run when you build your Android application.

Codegen is run as part of the script phases that's automatically added to the project generated by CocoaPods.

```
cd ios

bundle install

bundle exec pod install
```

The output will look like this:

```
...

Framework build type is static library

[Codegen] Adding script_phases to ReactCodegen.

[Codegen] Generating ./build/generated/ios/ReactCodegen.podspec.json

[Codegen] Analyzing /Users/me/src/TurboModuleExample/package.json

[Codegen] Searching for codegen-enabled libraries in the app.

[Codegen] Found TurboModuleExample

[Codegen] Searching for codegen-enabled libraries in the project dependencies.

[Codegen] Found react-native

...
```

```


//...

  @ReactProp(name = "sourceUrl")

  @Override

  public void setSourceURL(ReactWebView view, String sourceURL) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error);

      return;

    }

    view.loadUrl(sourceURL, new HashMap<>());

  }



+  @Override

+  public void reload(ReactWebView view) {

+    view.reload();

+  }



  public static final String REACT_CLASS = "CustomWebView";

//...
```

ReactWebViewManager.kt

```
  @ReactProp(name = "sourceUrl")

  override fun setSourceURL(view: ReactWebView, sourceURL: String?) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error)

      return;

    }

    view.loadUrl(sourceURL, emptyMap())

  }



+  override fun reload(view: ReactWebView) {

+    view.reload()

+  }



  companion object {

    const val REACT_CLASS = "CustomWebView"

  }
```

In this case, it's enough to call directly the `view.reload()` method because our ReactWebView inherits from the Android's `WebView` and it has a reload method directly available. If you are implementing a custom function, that is not available in your custom view, you might also have to implement the required method in the Android's View that is managed by the React Native's `ViewManager`.

To let your view respond to the Native Command, we need to implement a couple of methods on iOS.

Let's open the `RCTWebView.mm` file and let's modify it as it follows:

RCTWebView\.mm

```
  // Event emitter convenience method

  - (const CustomWebViewEventEmitter &)eventEmitter

  {

  return static_cast<const CustomWebViewEventEmitter &>(*_eventEmitter);

  }



+  - (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args

+  {

+  RCTCustomWebViewHandleCommand(self, commandName, args);

+  }

+

+  - (void)reload

+  {

+  [_webView reloadFromOrigin];

+  }



  + (ComponentDescriptorProvider)componentDescriptorProvider

  {

  return concreteComponentDescriptorProvider<CustomWebViewComponentDescriptor>();

  }
```

To make your view respond to the Native Commands, you need to apply the following changes:

1. Add a `handleCommand:args` function. This function is invoked by the components infrastructure to handle the commands. The function implementation is similar for every component: you need to call an `RCT<componentNameInJS>HandleCommand` function that is generated by Codegen for you. The `RCT<componentNameInJS>HandleCommand` perform a bunch of validation, verifying that the command that we need to invoke is among the supported ones and that the parameters passed matches the one expected. If all the checks pass, the `RCT<componentNameInJS>HandleCommand` will then invoke the proper native method.
2. Implement the `reload` method. In this example, the `reload` method calls the `reloadFromOrigin` function of the WebKit's WebView.

## 5. Run your app[​](#5-run-your-app "Direct link to 5. Run your app")

Finally, you can run your app with the usual commands. Once the app is running, you can tap on the refresh button to see the page getting reloaded.

| Android | iOS |
| ------- | --- |
|         |     |

* [1. Update your component specs](#1-update-your-component-specs)
* [2. Update the App code to use the new command](#2-update-the-app-code-to-use-the-new-command)
* [3. Rerun Codegen](#3-rerun-codegen)
* [4. Implement the Native Code](#4-implement-the-native-code)
* [5. Run your app](#5-run-your-app)

----
url: https://reactnative.dev/docs/global-PerformanceEventTiming
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`PerformanceEventTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEventTiming) class, as defined in Web specifications.

Partial support

The `cancelable` and `target` properties are not supported yet.

----
url: https://reactnative.dev/docs/permissionsandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `check()`[​](#check "Direct link to check")

React TSX

```
static check(permission: Permission): Promise<boolean>;
```

Returns a promise resolving to a boolean value as to whether the specified permissions has been granted.

**Parameters:**

| Name       | Type   | Required | Description                  |
| ---------- | ------ | -------- | ---------------------------- |
| permission | string | Yes      | The permission to check for. |

***

### `request()`[​](#request "Direct link to request")

React TSX

```
static request(

  permission: Permission,

  rationale?: Rationale,

): Promise<PermissionStatus>;
```

Prompts the user to enable a permission and returns a promise resolving to a string value (see result strings above) indicating whether the user allowed or denied the request or does not want to be asked again.

If `rationale` is provided, this function checks with the OS whether it is necessary to show a dialog explaining why the permission is needed (<https://developer.android.com/training/permissions/requesting.html#explain>) and then shows the system permission dialog.

**Parameters:**

| Name       | Type   | Required | Description                |
| ---------- | ------ | -------- | -------------------------- |
| permission | string | Yes      | The permission to request. |
| rationale  | object | No       | See `rationale` below.     |

**Rationale:**

| Name           | Type   | Required | Description                      |
| -------------- | ------ | -------- | -------------------------------- |
| title          | string | Yes      | The title of the dialog.         |
| message        | string | Yes      | The message of the dialog.       |
| buttonPositive | string | Yes      | The text of the positive button. |
| buttonNegative | string | No       | The text of the negative button. |
| buttonNeutral  | string | No       | The text of the neutral button.  |

***

### `requestMultiple()`[​](#requestmultiple "Direct link to requestmultiple")

React TSX

```
static requestMultiple(

  permissions: Permission[],

): Promise<{[key in Permission]: PermissionStatus}>;
```

Prompts the user to enable multiple permissions in the same dialog and returns an object with the permissions as keys and strings as values (see result strings above) indicating whether the user allowed or denied the request or does not want to be asked again.

**Parameters:**

| Name        | Type  | Required | Description                      |
| ----------- | ----- | -------- | -------------------------------- |
| permissions | array | Yes      | Array of permissions to request. |

----
url: https://reactnative.dev/docs/next/communication-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/communication-ios)** (0.87).

Version: Next

In [Integrating with Existing Apps guide](/docs/next/integration-with-existing-apps) and [Native UI Components guide](/docs/next/legacy/native-components-ios) we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.

```
NSArray *imageList = @[@"https://dummyimage.com/600x400/ffffff/000000.png",

                       @"https://dummyimage.com/600x400/000000/ffffff.png"];



NSDictionary *props = @{@"images" : imageList};



RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge

                                                 moduleName:@"ImageBrowserApp"

                                          initialProperties:props];
```

React TSX

```
import {View, Image} from 'react-native';



export default class ImageBrowserApp extends React.Component {

  renderImage(imgURI) {

    return <Image source={{uri: imgURI}} />;

  }

  render() {

    return <View>{this.props.images.map(this.renderImage)}</View>;

  }

}
```

`RCTRootView` also provides a read-write property `appProperties`. After `appProperties` is set, the React Native app is re-rendered with new properties. The update is only performed when the new updated properties differ from the previous ones.

Objective-C

```
NSArray *imageList = @[@"https://dummyimage.com/600x400/ff0000/000000.png",

                       @"https://dummyimage.com/600x400/ffffff/ff0000.png"];



rootView.appProperties = @{@"images" : imageList};
```

It is fine to update properties anytime. However, updates have to be performed on the main thread. You use the getter on any thread.

note

Currently, there is a known issue where setting appProperties during the bridge startup, the change can be lost. See <https://github.com/react/react-native/issues/20115> for more information.

There is no way to update only a few properties at a time. We suggest that you build it into your own wrapper instead.

### Passing properties from React Native to native[​](#passing-properties-from-react-native-to-native "Direct link to Passing properties from React Native to native")

The problem exposing properties of native components is covered in detail in [this article](/docs/next/legacy/native-components-ios#properties). In short, export properties with `RCT_CUSTOM_VIEW_PROPERTY` macro in your custom native component, then use them in React Native as if the component was an ordinary React Native component.

### Limits of properties[​](#limits-of-properties "Direct link to Limits of properties")

The main drawback of cross-language properties is that they do not support callbacks, which would allow us to handle bottom-up data bindings. Imagine you have a small RN view that you want to be removed from the native parent view as a result of a JS action. There is no way to do that with props, as the information would need to go bottom-up.

Although we have a flavor of cross-language callbacks ([described here](/docs/next/legacy/native-modules-ios#callbacks)), these callbacks are not always the thing we need. The main problem is that they are not intended to be passed as properties. Rather, this mechanism allows us to trigger a native action from JS, and handle the result of that action in JS.

## Other ways of cross-language interaction (events and native modules)[​](#other-ways-of-cross-language-interaction-events-and-native-modules "Direct link to Other ways of cross-language interaction (events and native modules)")

As stated in the previous chapter, using properties comes with some limitations. Sometimes properties are not enough to drive the logic of our app and we need a solution that gives more flexibility. This chapter covers other communication techniques available in React Native. They can be used for internal communication (between JS and native layers in RN) as well as for external communication (between RN and the 'pure native' part of your app).

React Native enables you to perform cross-language function calls. You can execute custom native code from JS and vice versa. Unfortunately, depending on the side we are working on, we achieve the same goal in different ways. For native - we use events mechanism to schedule an execution of a handler function in JS, while for React Native we directly call methods exported by native modules.

### Calling React Native functions from native (events)[​](#calling-react-native-functions-from-native-events "Direct link to Calling React Native functions from native (events)")

Events are described in detail in [this article](/docs/next/legacy/native-components-ios#events). Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread.

Events are powerful, because they allow us to change React Native components without needing a reference to them. However, there are some pitfalls that you can fall into while using them:

* As events can be sent from anywhere, they can introduce spaghetti-style dependencies into your project.
* Events share namespace, which means that you may encounter some name collisions. Collisions will not be detected statically, which makes them hard to debug.
* If you use several instances of the same React Native component and you want to distinguish them from the perspective of your event, you'll likely need to introduce identifiers and pass them along with events (you can use the native view's `reactTag` as an identifier).

The common pattern we use when embedding native in React Native is to make the native component's RCTViewManager a delegate for the views, sending events back to JavaScript via the bridge. This keeps related event calls in one place.

### Calling native functions from React Native (native modules)[​](#calling-native-functions-from-react-native-native-modules "Direct link to Calling native functions from React Native (native modules)")

Native modules are Objective-C classes that are available in JS. Typically one instance of each module is created per JS bridge. They can export arbitrary functions and constants to React Native. They have been covered in detail in [this article](/docs/next/legacy/native-modules-ios).

This case is covered in [this article](/docs/next/legacy/native-components-ios#styles). To summarize, since all our native react views are subclasses of `UIView`, most style and size attributes will work like you would expect out of the box.

### Layout of a React Native component embedded in native[​](#layout-of-a-react-native-component-embedded-in-native "Direct link to Layout of a React Native component embedded in native")

#### React Native content with fixed size[​](#react-native-content-with-fixed-size "Direct link to React Native content with fixed size")

The general scenario is when we have a React Native app with a fixed size, which is known to the native side. In particular, a full-screen React Native view falls into this case. If we want a smaller root view, we can explicitly set RCTRootView's frame.

For instance, to make an RN app 200 (logical) pixels high, and the hosting view's width wide, we could do:

SomeViewController.m

```
- (void)viewDidLoad

{

  [...]

  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge

                                                   moduleName:appName

                                            initialProperties:props];

  rootView.frame = CGRectMake(0, 0, self.view.width, 200);

  [self.view addSubview:rootView];

}
```

```
typedef NS_ENUM(NSInteger, RCTRootViewSizeFlexibility) {

  RCTRootViewSizeFlexibilityNone = 0,

  RCTRootViewSizeFlexibilityWidth,

  RCTRootViewSizeFlexibilityHeight,

  RCTRootViewSizeFlexibilityWidthAndHeight,

};
```

`RCTRootViewSizeFlexibilityNone` is the default value, which makes a root view's size fixed (but it still can be updated with `setFrame:`). The other three modes allow us to track React Native content's size updates. For instance, setting mode to `RCTRootViewSizeFlexibilityHeight` will cause React Native to measure the content's height and pass that information back to `RCTRootView`'s delegate. An arbitrary action can be performed within the delegate, including setting the root view's frame, so the content fits. The delegate is called only when the size of the content has changed.

caution

Making a dimension flexible in both JS and native leads to undefined behavior. For example - don't make a top-level React component's width flexible (with `flexbox`) while you're using `RCTRootViewSizeFlexibilityWidth` on the hosting `RCTRootView`.

Let's look at an example.

FlexibleSizeExampleView\.m

```
- (instancetype)initWithFrame:(CGRect)frame

{

  [...]



  _rootView = [[RCTRootView alloc] initWithBridge:bridge

  moduleName:@"FlexibilityExampleApp"

  initialProperties:@{}];



  _rootView.delegate = self;

  _rootView.sizeFlexibility = RCTRootViewSizeFlexibilityHeight;

  _rootView.frame = CGRectMake(0, 0, self.frame.size.width, 0);

}



#pragma mark - RCTRootViewDelegate

- (void)rootViewDidChangeIntrinsicSize:(RCTRootView *)rootView

{

  CGRect newFrame = rootView.frame;

  newFrame.size = rootView.intrinsicContentSize;



  rootView.frame = newFrame;

}
```

----
url: https://reactnative.dev/docs/state
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

State works the same way as it does in React, so for more details on handling state, you can look at the [React.Component API](https://react.dev/reference/react/Component#setstate). At this point, you may have noticed that most of our examples use the default text color. To customize the text color, you will have to [learn about Style](/docs/style).

----
url: https://reactnative.dev/docs/next/platformcolor
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/platformcolor)** (0.87).

Version: Next

JavaScript

```
PlatformColor(color1, [color2, ...colorN]);
```

You can use the `PlatformColor` function to access native colors on the target platform by supplying the native color’s corresponding string value. You pass a string to the `PlatformColor` function and, provided it exists on that platform, it will return the corresponding native color, which you can apply in any part of your application.

If you pass more than one string value to the `PlatformColor` function, it will treat the first value as the default and the rest as fallback.

JavaScript

```
PlatformColor('bogusName', 'linkColor');
```

----
url: https://reactnative.dev/docs/next/global-EventCounts
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-EventCounts)** (0.87).

Version: Next

The global [`EventCounts`](https://developer.mozilla.org/en-US/docs/Web/API/EventCounts) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/alertios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use [`Alert`](/docs/alert) instead.

----
url: https://reactnative.dev/docs/global-intersectionobserver
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Canary 🧪

**This API is currently only available in React Native’s Canary and Experimental channels.**

If you want to try it out, please [enable the Canary Channel](/docs/release-levels) in your app.

The global [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) interface, as defined in Web specifications. It provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

***

# Reference

## Constructor[​](#constructor "Direct link to Constructor")

### `IntersectionObserver()`[​](#intersectionobserver "Direct link to intersectionobserver")

See [documentation in MDN](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver).

Creates a new `IntersectionObserver` object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more `threshold` or `rnRootThreshold` values.

TypeScript

```
new IntersectionObserver(callback, options?)
```

#### Parameters[​](#parameters "Direct link to Parameters")

**`callback`**

A function which is called when the percentage of the target element is visible crosses a threshold. The callback receives two parameters:

* `entries`: An array of [`IntersectionObserverEntry`](/docs/global-intersectionobserverentry) objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.
* `observer`: The `IntersectionObserver` instance which invoked the callback.

**`options`** (optional)

An optional object with the following properties:

| Name                 | Type                                   | Description                                                                                                                                                                                                       |
| -------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `root`               | [Element](/docs/element-nodes) \| null | An element that is an ancestor of the target, whose bounding rectangle will be considered the viewport. Defaults to the root viewport if not specified or if `null`.                                              |
| `rootMargin`         | string                                 | A string which specifies a set of offsets to add to the root's bounding box when calculating intersections. Defaults to `"0px 0px 0px 0px"`.                                                                      |
| `threshold`          | number \| number\[]                    | Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target. Defaults to `[0]` if `rnRootThreshold` is not set. |
| `rnRootThreshold` ⚠️ | number \| number\[]                    | **React Native specific.** Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to the total root area.                                                     |

```
get rnRootThresholds(): ReadonlyArray<number> | null;
```

----
url: https://reactnative.dev/docs/animated
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The `Animated` library is designed to make animations fluid, powerful, and painless to build and maintain. `Animated` focuses on declarative relationships between inputs and outputs, configurable transforms in between, and `start`/`stop` methods to control time-based animation execution.

The core workflow for creating an animation is to create an `Animated.Value`, hook it up to one or more style attributes of an animated component, and then drive updates via animations using `Animated.timing()`.

note

Don't modify the animated value directly. You can use the [`useRef` Hook](https://react.dev/reference/react/useRef) to return a mutable ref object. This ref object's `current` property is initialized as the given argument and persists throughout the component lifecycle.

## Example[​](#example "Direct link to Example")

The following example contains a `View` which will fade in and fade out based on the animated value `fadeAnim`

Refer to the [Animations](/docs/animations#animated-api) guide to see additional examples of `Animated` in action.

## Overview[​](#overview "Direct link to Overview")

There are two value types you can use with `Animated`:

* [`Animated.Value()`](/docs/animated#value) for single values
* [`Animated.ValueXY()`](/docs/animated#valuexy) for vectors

`Animated.Value` can bind to style properties or other props, and can be interpolated as well. A single `Animated.Value` can drive any number of properties.

### Configuring animations[​](#configuring-animations "Direct link to Configuring animations")

`Animated` provides three types of animation types. Each animation type provides a particular animation curve that controls how your values animate from their initial value to the final value:

* [`Animated.decay()`](/docs/animated#decay) starts with an initial velocity and gradually slows to a stop.
* [`Animated.spring()`](/docs/animated#spring) provides a basic spring physics model.
* [`Animated.timing()`](/docs/animated#timing) animates a value over time using [easing functions](/docs/easing).

In most cases, you will be using `timing()`. By default, it uses a symmetric easeInOut curve that conveys the gradual acceleration of an object to full speed and concludes by gradually decelerating to a stop.

### Working with animations[​](#working-with-animations "Direct link to 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}`.

React TSX

```
Animated.timing({}).start(({finished}) => {

  /* completion callback */

});
```

### Using the native driver[​](#using-the-native-driver "Direct link to Using the native driver")

By using the native driver, we send everything about the animation to native before starting the animation, allowing native code to perform the animation on the UI thread without having to go through the bridge on every frame. Once the animation has started, the JS thread can be blocked without affecting the animation.

You can use the native driver by specifying `useNativeDriver: true` in your animation configuration. See the [Animations](/docs/animations#using-the-native-driver) guide to learn more.

### Animatable components[​](#animatable-components "Direct link to Animatable components")

Only animatable components can be animated. These unique components do the magic of binding the animated values to the properties, and do targeted native updates to avoid the cost of the React render and reconciliation process on every frame. They also handle cleanup on unmount so they are safe by default.

* [`createAnimatedComponent()`](/docs/animated#createanimatedcomponent) can be used to make a component animatable.

* [`Animated.delay()`](/docs/animated#delay) starts an animation after a given delay.
* [`Animated.parallel()`](/docs/animated#parallel) starts a number of animations at the same time.
* [`Animated.sequence()`](/docs/animated#sequence) starts the animations in order, waiting for each to complete before starting the next.
* [`Animated.stagger()`](/docs/animated#stagger) starts animations in order and in parallel, but with successive delays.

Animations can also be chained together by setting the `toValue` of one animation to be another `Animated.Value`. See [Tracking dynamic values](/docs/animations#tracking-dynamic-values) in the Animations guide.

By default, if one animation is stopped or interrupted, then all other animations in the group are also stopped.

### Combining animated values[​](#combining-animated-values "Direct link to Combining animated values")

You can combine two animated values via addition, subtraction, multiplication, division, or modulo to make a new animated value:

* [`Animated.add()`](/docs/animated#add)
* [`Animated.subtract()`](/docs/animated#subtract)
* [`Animated.divide()`](/docs/animated#divide)
* [`Animated.modulo()`](/docs/animated#modulo)
* [`Animated.multiply()`](/docs/animated#multiply)

### Interpolation[​](#interpolation "Direct link to Interpolation")

The `interpolate()` function allows input ranges to map to different output ranges. By default, it will extrapolate the curve beyond the ranges given, but you can also have it clamp the output value. It uses linear interpolation by default but also supports easing functions.

* [`interpolate()`](/docs/animatedvalue#interpolate)

Read more about interpolation in the [Animation](/docs/animations#interpolation) guide.

### Handling gestures and other events[​](#handling-gestures-and-other-events "Direct link to Handling gestures and other events")

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.

* [`Animated.event()`](/docs/animated#event)

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`):

React TSX

```
 onScroll={Animated.event(

   // scrollX = e.nativeEvent.contentOffset.x

   [{nativeEvent: {

        contentOffset: {

          x: scrollX

        }

      }

    }],

    {useNativeEvent: true}

 )}
```

***

# Reference

## Methods[​](#methods "Direct link to Methods")

When the given value is a ValueXY instead of a Value, each config option may be a vector of the form `{x: ..., y: ...}` instead of a scalar.

### `decay()`[​](#decay "Direct link to decay")

React TSX

```
static decay(value, config): CompositeAnimation;
```

Animates a value from an initial velocity to zero based on a decay coefficient.

Config is an object that may have the following options:

* `velocity`: Initial velocity. Required.
* `deceleration`: Rate of decay. Default 0.997.
* `isInteraction`: Whether or not this animation creates an "interaction handle". Default true.
* `useNativeDriver`: Uses the native driver when true. Required.

***

### `timing()`[​](#timing "Direct link to timing")

React TSX

```
static timing(value, config): CompositeAnimation;
```

Animates a value along a timed easing curve. The [`Easing`](/docs/easing) module has tons of predefined curves, or you can use your own function.

Config is an object that may have the following options:

* `duration`: Length of animation (milliseconds). Default 500.
* `easing`: Easing function to define curve. Default is `Easing.inOut(Easing.ease)`.
* `delay`: Start the animation after delay (milliseconds). Default 0.
* `isInteraction`: Whether or not this animation creates an "interaction handle". Default true.
* `useNativeDriver`: Uses the native driver when true. Required.

***

### `spring()`[​](#spring "Direct link to spring")

React TSX

```
static spring(value, config): CompositeAnimation;
```

***

### `add()`[​](#add "Direct link to add")

React TSX

```
static add(a: Animated, b: Animated): AnimatedAddition;
```

Creates a new Animated value composed from two Animated values added together.

***

### `subtract()`[​](#subtract "Direct link to subtract")

React TSX

```
static subtract(a: Animated, b: Animated): AnimatedSubtraction;
```

Creates a new Animated value composed by subtracting the second Animated value from the first Animated value.

***

### `divide()`[​](#divide "Direct link to divide")

React TSX

```
static divide(a: Animated, b: Animated): AnimatedDivision;
```

Creates a new Animated value composed by dividing the first Animated value by the second Animated value.

***

### `multiply()`[​](#multiply "Direct link to multiply")

React TSX

```
static multiply(a: Animated, b: Animated): AnimatedMultiplication;
```

Creates a new Animated value composed from two Animated values multiplied together.

***

### `modulo()`[​](#modulo "Direct link to modulo")

React TSX

```
static modulo(a: Animated, modulus: number): AnimatedModulo;
```

Creates a new Animated value that is the (non-negative) modulo of the provided Animated value

***

### `diffClamp()`[​](#diffclamp "Direct link to diffclamp")

React TSX

```
static diffClamp(a: Animated, min: number, max: number): AnimatedDiffClamp;
```

Create a new Animated value that is limited between 2 values. It uses the difference between the last value so even if the value is far from the bounds it will start changing when the value starts getting closer again. (`value = clamp(value + diff, min, max)`).

This is useful with scroll events, for example, to show the navbar when scrolling up and to hide it when scrolling down.

***

### `delay()`[​](#delay "Direct link to delay")

React TSX

```
static delay(time: number): CompositeAnimation;
```

Starts an animation after the given delay.

***

### `sequence()`[​](#sequence "Direct link to sequence")

React TSX

```
static sequence(animations: CompositeAnimation[]): CompositeAnimation;
```

Starts an array of animations in order, waiting for each to complete before starting the next. If the current running animation is stopped, no following animations will be started.

***

### `parallel()`[​](#parallel "Direct link to parallel")

React TSX

```
static parallel(

  animations: CompositeAnimation[],

  config?: ParallelConfig

): CompositeAnimation;
```

Starts an array of animations all at the same time. By default, if one of the animations is stopped, they will all be stopped. You can override this with the `stopTogether` flag.

***

### `stagger()`[​](#stagger "Direct link to stagger")

React TSX

```
static stagger(

  time: number,

  animations: CompositeAnimation[]

): CompositeAnimation;
```

Array of animations may run in parallel (overlap), but are started in sequence with successive delays. Nice for doing trailing effects.

***

### `loop()`[​](#loop "Direct link to loop")

React TSX

```
static loop(

  animation: CompositeAnimation[],

  config?: LoopAnimationConfig

): CompositeAnimation;
```

Loops a given animation continuously, so that each time it reaches the end, it resets and begins again from the start. Will loop without blocking the JS thread if the child animation is set to `useNativeDriver: true`. In addition, loops can prevent `VirtualizedList`-based components from rendering more rows while the animation is running. You can pass `isInteraction: false` in the child animation config to fix this.

Config is an object that may have the following options:

* `iterations`: Number of times the animation should loop. Default `-1` (infinite).

***

### `event()`[​](#event "Direct link to event")

React TSX

```
static event(

  argMapping: Mapping[],

  config?: EventConfig

): (...args: any[]) => void;
```

Takes an array of mappings and extracts values from each arg accordingly, then calls `setValue` on the mapped outputs. e.g.

React TSX

```
onScroll={Animated.event(

  [{nativeEvent: {contentOffset: {x: this._scrollX}}}],

  {listener: (event: ScrollEvent) => console.log(event)}, // Optional async listener

)}

 ...

onPanResponderMove: Animated.event(

  [

    null, // raw event arg ignored

    {dx: this._panX},

  ], // gestureState arg

  {

    listener: (

      event: GestureResponderEvent,

      gestureState: PanResponderGestureState

    ) => console.log(event, gestureState),

  } // Optional async listener

);
```

Config is an object that may have the following options:

* `listener`: Optional async listener.
* `useNativeDriver`: Uses the native driver when true. Required.

***

### `forkEvent()`[​](#forkevent "Direct link to forkevent")

React JSX

```
static forkEvent(event: AnimatedEvent, listener: Function): AnimatedEvent;
```

Advanced imperative API for snooping on animated events that are passed in through props. It permits to add a new javascript listener to an existing `AnimatedEvent`. If `animatedEvent` is a javascript listener, it will merge the 2 listeners into a single one, and if `animatedEvent` is null/undefined, it will assign the javascript listener directly. Use values directly where possible.

***

### `unforkEvent()`[​](#unforkevent "Direct link to unforkevent")

React JSX

```
static unforkEvent(event: AnimatedEvent, listener: Function);
```

***

### `start()`[​](#start "Direct link to start")

React TSX

```
static start(callback?: (result: {finished: boolean}) => void);
```

Animations are started by calling start() on your animation. start() takes a completion callback that will be called when the animation is done or when the animation is done because stop() was called on it before it could finish.

**Parameters:**

| Name     | Type                                    | Required | Description                                                                                                                                                     |
| -------- | --------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 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:

React TSX

```
Animated.timing({}).start(({finished}) => {

  /* completion callback */

});
```

***

### `stop()`[​](#stop "Direct link to stop")

React TSX

```
static stop();
```

Stops any running animation.

***

### `reset()`[​](#reset "Direct link to reset")

React TSX

```
static reset();
```

Stops any running animation and resets the value to its original.

## Properties[​](#properties "Direct link to Properties")

### `Value`[​](#value "Direct link to value")

Standard value class for driving animations. Typically initialized with `useAnimatedValue(0);` or `new Animated.Value(0);` in class components.

You can read more about `Animated.Value` API on the separate [page](/docs/animatedvalue).

***

### `ValueXY`[​](#valuexy "Direct link to valuexy")

2D value class for driving 2D animations, such as pan gestures.

You can read more about `Animated.ValueXY` API on the separate [page](/docs/animatedvaluexy).

***

### `Interpolation`[​](#interpolation-1 "Direct link to interpolation-1")

Exported to use the Interpolation type in flow.

***

### `Node`[​](#node "Direct link to node")

Exported for ease of type checking. All animated values derive from this class.

***

### `createAnimatedComponent`[​](#createanimatedcomponent "Direct link to createanimatedcomponent")

Make any React component Animatable. Used to create `Animated.View`, etc.

***

----
url: https://reactnative.dev/docs/libraries
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React Native provides a set of built-in [Core Components and APIs](/docs/components-and-apis) ready to use in your app. You're not limited to the components and APIs bundled with React Native. React Native has a community of thousands of developers. If the Core Components and APIs don't have what you are looking for, you may be able to find and install a library from the community to add the functionality to your app.

```
npm install react-native-webview
```

```
yarn add react-native-webview
```

The library that we installed includes native code, and we need to link to our app before we use it.

## Linking Native Code on iOS[​](#linking-native-code-on-ios "Direct link to Linking Native Code on iOS")

React Native uses CocoaPods to manage iOS project dependencies and most React Native libraries follow this same convention. If a library you are using does not, then please refer to their README for additional instruction. In most cases, the following instructions will apply.

Run `pod install` in our `ios` directory in order to link it to our native iOS project. A shortcut for doing this without switching to the `ios` directory is to run `npx pod-install`.

```
npx pod-install
```

Once this is complete, re-build the app binary to start using your new library:

* npm
* Yarn

```
npm run ios
```

```
yarn ios
```

## Linking Native Code on Android[​](#linking-native-code-on-android "Direct link to Linking Native Code on Android")

React Native uses Gradle to manage Android project dependencies. After you install a library with native dependencies, you will need to re-build the app binary to use your new library:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

----
url: https://reactnative.dev/docs/the-new-architecture/native-modules-lifecycle
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
+ #import <React/RCTInitializing.h>



//...



- @interface NativeModule : NSObject <NativeModuleSpec>

+ @interface NativeModule : NSObject <NativeModuleSpec, RCTInitializing>

//...

@end
```

2. Implement the `initialize` method in the `NativeModule.mm` file:

NativeModule.mm

```
// ...



@implementation NativeModule



+- (void)initialize {

+ // add the initialization code here

+}



@end
```

These are some Native Modules from core that implements the `initialize` method: [RCTBlobManager](https://github.com/react/react-native/blob/0617accecdcb11159ba15c34885f294bc206aa89/packages/react-native/Libraries/Blob/RCTBlobManager.mm#L58-L68), [RCTTiming](https://github.com/react/react-native/blob/0617accecdcb11159ba15c34885f294bc206aa89/packages/react-native/React/CoreModules/RCTTiming.mm#L121-L124).

If your module needs to run some cleanup code, then you can conform to the `RCTInvalidating` protocol and implement the `invalidate` method. To do so, you have to:

1. Moduify the `NativeModule.h` file by adding the following lines:

NativeModule.h

```
+ #import <React/RCTInvalidating.h>



//...



- @interface NativeModule : NSObject <NativeModuleSpec>

+ @interface NativeModule : NSObject <NativeModuleSpec, RCTInvalidating>



//...



@end
```

2. Implement the `invalidate` method in the `NativeModule.mm` file:

NativeModule.mm

```


// ...



@implementation NativeModule



+- (void)invalidate {

+ // add the cleanup code here

+}



@end
```

These are some Native Modules from core that implements the `invalidate` method: [RCTAppearance](https://github.com/react/react-native/blob/0617accecdcb11159ba15c34885f294bc206aa89/packages/react-native/React/CoreModules/RCTAppearance.mm#L151-L155), [RCTDeviceInfo](https://github.com/react/react-native/blob/0617accecdcb11159ba15c34885f294bc206aa89/packages/react-native/React/CoreModules/RCTDeviceInfo.mm#L127-L133).

* [Android](#android)
* [iOS](#ios)

----
url: https://reactnative.dev/docs/next/height-and-width
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/height-and-width)** (0.87).

Version: Next

After you can control a component's size, the next step is to [learn how to lay it out on the screen](/docs/next/flexbox).

## Percentage Dimensions[​](#percentage-dimensions "Direct link to Percentage Dimensions")

If you want to fill a certain portion of the screen, but you *don't* want to use the `flex` layout, you *can* use **percentage values** in the component's style. Similar to flex dimensions, percentage dimensions require parent with a defined size.

* [Fixed Dimensions](#fixed-dimensions)
* [Flex Dimensions](#flex-dimensions)
* [Percentage Dimensions](#percentage-dimensions)

----
url: https://reactnative.dev/docs/next/view-style-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/view-style-props)** (0.87).

Version: Next

### Example[​](#example "Direct link to Example")

# Reference

## Props[​](#props "Direct link to Props")

### `backfaceVisibility`[​](#backfacevisibility "Direct link to backfacevisibility")

| Type                          |
| ----------------------------- |
| enum(`'visible'`, `'hidden'`) |

***

### `backgroundColor`[​](#backgroundcolor "Direct link to backgroundcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `backgroundImage`[​](#backgroundimage "Direct link to backgroundimage")

`backgroundImage` provides the ability to draw a [`linear-gradient()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/gradient/linear-gradient) and [`radial-gradient()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/gradient/radial-gradient) using a web-like syntax.

React TSX

```
// Simple usage:

<View style={{ backgroundImage: 'linear-gradient(45deg, blue, red)' }} />



<View style={{ backgroundImage: 'radial-gradient(ellipse farthest-corner at 30% 40%, red, blue)' }} />



// Also with PlatformColor:

<View

style={{

  backgroundImage: [

    {

      type: 'linear-gradient',

      direction: 'to bottom',

      colorStops: [

        {

          color: Platform.select({

            ios: PlatformColor('systemTealColor'),

            android: PlatformColor('@android:color/holo_purple'),

            default: 'blue',

          }),

          positions: ['0%'],

        },

        {color: 'green', positions: ['100%']},

      ],

    },

  ],

}}

/>
```

More complex examples of usage can be found in the RNTester app (with `PlatformColor` supports):

* [LinearGradientExample.js](https://github.com/react/react-native/blob/main/packages/rn-tester/js/examples/LinearGradient/LinearGradientExample.js)
* [RadialGradientExample.js](https://github.com/react/react-native/blob/main/packages/rn-tester/js/examples/RadialGradient/RadialGradientExample.js)

| Type                                                                                                                                                                                               |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| string, array of objects: `{type: 'linear-gradient', direction: string, colorStops: object[] }`, `{type: 'radial-gradient', shape: string, position: object, size: string, colorStops: object[] }` |

***

### `backgroundPosition`[​](#backgroundposition "Direct link to backgroundposition")

Controls where the background gradient is placed inside the view. This is useful when `backgroundImage` is set, and you want to offset or center it instead of filling the full area.

React TSX

```
<View

  style={{

    backgroundImage: 'radial-gradient(circle, #ff6b6b, #4ecdc4)',

    backgroundPosition: 'center',

    backgroundRepeat: 'no-repeat',

    backgroundSize: '50px 50px',

  }}

/>
```

| Type                                                                                    |
| --------------------------------------------------------------------------------------- |
| string \| array of objects `{top: string, left: string, right: string, bottom: string}` |

***

### `backgroundRepeat`[​](#backgroundrepeat "Direct link to backgroundrepeat")

Controls whether the background gradient is repeated, and how. This works together with `backgroundImage` to tile gradients across the view.

React TSX

```
<View

  style={{

    backgroundImage: 'linear-gradient(45deg, #ff6b6b, #4ecdc4)',

    backgroundRepeat: 'repeat',

    backgroundSize: '20px 20px',

  }}

/>
```

| Type                                                                                               |
| -------------------------------------------------------------------------------------------------- |
| enum(`'repeat'`, `'space'`, `'round'`, `'no-repeat'`) \| array of objects `{x: string, y: string}` |

***

### `backgroundSize`[​](#backgroundsize "Direct link to backgroundsize")

Controls the size of the background gradient. This is most useful when `backgroundImage` is set and the gradient should not fill the entire view by default.

React TSX

```
<View

  style={{

    backgroundImage: 'linear-gradient(90deg, #a8edea, #fed6e3)',

    backgroundRepeat: 'no-repeat',

    backgroundSize: '100px 100px',

  }}

/>
```

| Type                                                |
| --------------------------------------------------- |
| string \| array of objects `{x: number, y: number}` |

***

### `borderBottomColor`[​](#borderbottomcolor "Direct link to borderbottomcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderBlockColor`[​](#borderblockcolor "Direct link to borderblockcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderBlockEndColor`[​](#borderblockendcolor "Direct link to borderblockendcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderBlockStartColor`[​](#borderblockstartcolor "Direct link to borderblockstartcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderBottomEndRadius`[​](#borderbottomendradius "Direct link to borderbottomendradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderBottomLeftRadius`[​](#borderbottomleftradius "Direct link to borderbottomleftradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderBottomRightRadius`[​](#borderbottomrightradius "Direct link to borderbottomrightradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderBottomStartRadius`[​](#borderbottomstartradius "Direct link to borderbottomstartradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderStartEndRadius`[​](#borderstartendradius "Direct link to borderstartendradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderStartStartRadius`[​](#borderstartstartradius "Direct link to borderstartstartradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderEndEndRadius`[​](#borderendendradius "Direct link to borderendendradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderEndStartRadius`[​](#borderendstartradius "Direct link to borderendstartradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderBottomWidth`[​](#borderbottomwidth "Direct link to borderbottomwidth")

| Type   |
| ------ |
| number |

***

### `borderColor`[​](#bordercolor "Direct link to bordercolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderCurve`iOS[​](#bordercurve-ios "Direct link to bordercurve-ios")

On iOS 13+, it is possible to change the corner curve of borders.

| Type                               |
| ---------------------------------- |
| enum(`'circular'`, `'continuous'`) |

***

### `borderEndColor`[​](#borderendcolor "Direct link to borderendcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderLeftColor`[​](#borderleftcolor "Direct link to borderleftcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderLeftWidth`[​](#borderleftwidth "Direct link to borderleftwidth")

| Type   |
| ------ |
| number |

***

### `borderRadius`[​](#borderradius "Direct link to borderradius")

If the rounded border is not visible, try applying `overflow: 'hidden'` as well.

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderRightColor`[​](#borderrightcolor "Direct link to borderrightcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderRightWidth`[​](#borderrightwidth "Direct link to borderrightwidth")

| Type   |
| ------ |
| number |

***

### `borderStartColor`[​](#borderstartcolor "Direct link to borderstartcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderStyle`[​](#borderstyle "Direct link to borderstyle")

| Type                                    |
| --------------------------------------- |
| enum(`'solid'`, `'dotted'`, `'dashed'`) |

***

### `borderTopColor`[​](#bordertopcolor "Direct link to bordertopcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderTopEndRadius`[​](#bordertopendradius "Direct link to bordertopendradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderTopLeftRadius`[​](#bordertopleftradius "Direct link to bordertopleftradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderTopRightRadius`[​](#bordertoprightradius "Direct link to bordertoprightradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderTopStartRadius`[​](#bordertopstartradius "Direct link to bordertopstartradius")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderTopWidth`[​](#bordertopwidth "Direct link to bordertopwidth")

| Type                              |
| --------------------------------- |
| number, string (percentage value) |

***

### `borderWidth`[​](#borderwidth "Direct link to borderwidth")

| Type   |
| ------ |
| number |

### `boxShadow`[​](#boxshadow "Direct link to boxshadow")

note

`boxShadow` is only available on the [New Architecture](/architecture/landing-page). Outset shadows are only supported on **Android 9+**. Inset shadows are only supported on **Android 10+**.

Adds a shadow effect to an element, with the ability to control the position, color, size, and blurriness of the shadow. This shadow either appears around the outside or inside of the border box of the element, depending on whether or not the shadow is *inset*. This is a spec-compliant implementation of the [web style prop of the same name](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow). Read more about all the arguments available in the [BoxShadowValue](/docs/next/boxshadowvalue) documentation.

These shadows can be composed together so that a single `boxShadow` can be comprised of multiple different shadows.

`boxShadow` takes either a string which mimics the [web syntax](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow#syntax) or an array of [BoxShadowValue](/docs/next/boxshadowvalue) objects.

| Type                                      |
| ----------------------------------------- |
| array of BoxShadowValue objects \| string |

### `cursor`iOS[​](#cursor-ios "Direct link to cursor-ios")

On iOS 17+, Setting to `pointer` allows hover effects when a pointer (such as a trackpad or stylus on iOS, or the users' gaze on visionOS) is over the view.

| Type                        |
| --------------------------- |
| enum(`'auto'`, `'pointer'`) |

***

### `elevation`Android[​](#elevation-android "Direct link to elevation-android")

Sets the elevation of a view, using Android's underlying [elevation API](https://developer.android.com/training/material/shadows-clipping.html#Elevation). This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.

| Type   |
| ------ |
| number |

***

* `dropShadow`: Adds a shadow around the alpha mask of the `View` (only non-zero alpha pixels in the `View` will cast a shadow). Takes an optional color representing the shadow color, and 2 or 3 lengths. If 2 lengths are specified they are interpreted as `offsetX` and `offsetY` which will translate the shadow in the X and Y dimensions respectfully. If a 3rd length is given it is interpreted as the standard deviation of the Gaussian blur used on the shadow - so a larger value will blur the shadow more. Read more about the arguments in [DropShadowValue](/docs/next/dropshadowvalue).

| Type                                                                                                                                                                                                                                                                                                                                        |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| array of objects: `{brightness: number\|string}`, `{opacity: number\|string}`, `{blur: number\|string}`, `{contrast: number\|string}`, `{dropShadow: DropShadowValue\|string}`, `{grayscale: number\|string}`, `{hueRotate: number\|string}`, `{invert: number\|string}`, `{sepia: number\|string}`, `{saturate: number\|string}` or string |

***

### `mixBlendMode`[​](#mixblendmode "Direct link to mixblendmode")

note

`mixBlendMode` is only available on the [New Architecture](/architecture/landing-page) and **Android 10+**

Controls how the `View` blends its colors with the other elements in its **stacking context**. Check out the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode) for a full overview of each blending function.

For more granular control over what should be blending together see [isolation](/docs/next/layout-props#isolation).

| Type                                                                                                                                                                                                                                                   |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| enum(`'normal'`, `'multiply'`, `'screen'`, `'overlay'`, `'darken'`, `'lighten'`, `'color-dodge'`, `'color-burn'`, `'hard-light'`, `'soft-light'`, `'difference'`, `'exclusion'`, `'hue'`, `'saturation'`, `'color'`, `'luminosity'`, `'plus-lighter'`) |

***

### `opacity`[​](#opacity "Direct link to opacity")

| Type   |
| ------ |
| number |

***

### `outlineColor`[​](#outlinecolor "Direct link to outlinecolor")

note

`outlineColor` is only available on the [New Architecture](/architecture/landing-page)

Sets the color of an element's outline. See [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-color) for more details.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `outlineOffset`[​](#outlineoffset "Direct link to outlineoffset")

note

`outlineOffset` is only available on the [New Architecture](/architecture/landing-page)

Sets the amount of space between an outline and the bounds of an element. Does not affect layout. See [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-offset) for more details.

| Type   |
| ------ |
| number |

***

### `outlineStyle`[​](#outlinestyle "Direct link to outlinestyle")

note

`outlineStyle` is only available on the [New Architecture](/architecture/landing-page)

Sets the style of an element's outline. See [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-style) for more details.

| Type                                    |
| --------------------------------------- |
| enum(`'solid'`, `'dotted'`, `'dashed'`) |

***

### `outlineWidth`[​](#outlinewidth "Direct link to outlinewidth")

note

`outlineWidth` is only available on the [New Architecture](/architecture/landing-page)

The width of an outline which is drawn around an element, outside the border. Does not affect layout. See [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/outline-width) for more details.

| Type   |
| ------ |
| number |

***

### `pointerEvents`[​](#pointerevents "Direct link to pointerevents")

Controls whether the `View` can be the target of touch events.

* `'auto'`: The View can be the target of touch events.
* `'none'`: The View is never the target of touch events.
* `'box-none'`: The View is never the target of touch events but its subviews can be.
* `'box-only'`: The view can be the target of touch events but its subviews cannot be.

| Type                                                  |
| ----------------------------------------------------- |
| enum(`'auto'`, `'box-none'`, `'box-only'`, `'none'` ) |

* [Example](#example)

* [Props](#props)

  * [`backfaceVisibility`](#backfacevisibility)
  * [`backgroundColor`](#backgroundcolor)
  * [`backgroundImage`](#backgroundimage)
  * [`backgroundPosition`](#backgroundposition)
  * [`backgroundRepeat`](#backgroundrepeat)
  * [`backgroundSize`](#backgroundsize)

    [iOS](#bordercurve-ios)

    [iOS](#cursor-ios)
  * [`elevation`](#elevation-android)

    [Android](#elevation-android)

----
url: https://reactnative.dev/docs/integration-with-android-fragment
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
<FrameLayout

    android:id="@+id/react_native_fragment"

    android:layout_width="match_parent"

    android:layout_height="match_parent" />
```

```
package <your-package-here>



import android.os.Bundle

import androidx.appcompat.app.AppCompatActivity

+import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler



+class MainActivity : AppCompatActivity() {

+class MainActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler {



    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.main_activity)



        findViewById<Button>(R.id.sample_button).setOnClickListener {

            // Handle button click

        }

    }



+   override fun invokeDefaultOnBackPressed() {

+       onBackPressedDispatcher.onBackPressed()

+   }

}
```

Diff

```
package <your-package-here>;



import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

+import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;



-class MainActivity extends AppCompatActivity {

+class MainActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {



    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity);



        findViewById(R.id.button_appcompose).setOnClickListener(button -> {

            // Handle button click

        });

    }



+   @Override

+   public void invokeDefaultOnBackPressed() {

+       getOnBackPressedDispatcher().onBackPressed();

+   }

}
```

### 4. Add a React Native Fragment to the FrameLayout[​](#4-add-a-react-native-fragment-to-the-framelayout "Direct link to 4. Add a React Native Fragment to the FrameLayout")

Finally, we can update the Activity to add a React Native Fragment to the FrameLayout. In this specific example, we're going to assume that your Activity has a button with id `sample_button` that when clicked will render a React Native Fragment into the FrameLayout.

Update your Activity's `onCreate` method as follows:

* Java
* Kotlin

Diff

```
package <your-package-here>



import android.os.Bundle

import androidx.appcompat.app.AppCompatActivity

+import com.facebook.react.ReactFragment

import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler



public class MainActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler {



    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.main_activity)



        findViewById<Button>(R.id.sample_button).setOnClickListener {

+           val reactNativeFragment = ReactFragment.Builder()

+               .setComponentName("HelloWorld")

+               .setLaunchOptions(Bundle().apply { putString("message", "my value") })

+               .build()

+           supportFragmentManager

+               .beginTransaction()

+               .add(R.id.react_native_fragment, reactNativeFragment)

+               .commit()

        }

    }



   override fun invokeDefaultOnBackPressed() {

       super.onBackPressed()

   }

}
```

Diff

```
package <your-package-here>;



import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

+import com.facebook.react.ReactFragment;

import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;



public class MainActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {



    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity);



        findViewById(R.id.button_appcompose).setOnClickListener(button -> {

+           Bundle launchOptions = new Bundle();

+           launchOptions.putString("message", "my value");

+

+           ReactFragment fragment = new ReactFragment.Builder()

+                   .setComponentName("HelloWorld")

+                   .setLaunchOptions(launchOptions)

+                   .build();

+           getSupportFragmentManager()

+                   .beginTransaction()

+                   .add(R.id.react_native_fragment, fragment)

+                   .commit();

        });

    }



    @Override

    public void invokeDefaultOnBackPressed() {

        super.onBackPressed();

    }

}
```

----
url: https://reactnative.dev/docs/next/the-new-architecture/custom-cxx-types
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/custom-cxx-types)** (0.87).

Version: Next

note

This guide assumes that you are familiar with the [**Pure C++ Turbo Native Modules**](/docs/next/the-new-architecture/pure-cxx-modules) guide. This will build on top of that guide.

```
#pragma once



#include <react/bridging/Bridging.h>



namespace facebook::react {



template <>

struct Bridging<int64_t> {

  // Converts from the JS representation to the C++ representation

  static int64_t fromJs(jsi::Runtime &rt, const jsi::String &value) {

    try {

      size_t pos;

      auto str = value.utf8(rt);

      auto num = std::stoll(str, &pos);

      if (pos != str.size()) {

        throw std::invalid_argument("Invalid number"); // don't support alphanumeric strings

      }

      return num;

    } catch (const std::logic_error &e) {

      throw jsi::JSError(rt, e.what());

    }

  }



  // Converts from the C++ representation to the JS representation

  static jsi::String toJs(jsi::Runtime &rt, int64_t value) {

    return bridging::toJs(rt, std::to_string(value));

  }

};



}
```

```
import {TurboModule, TurboModuleRegistry} from 'react-native';



export interface Spec extends TurboModule {

  readonly reverseString: (input: string) => string;

+  readonly cubicRoot: (input: string) => number;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeSampleModule',

);
```

NativeSampleModule.js

```
// @flow

import type {TurboModule} from 'react-native';

import { TurboModuleRegistry } from "react-native";



export interface Spec extends TurboModule {

  +reverseString: (input: string) => string;

+  +cubicRoot: (input: string) => number;

}



export default (TurboModuleRegistry.getEnforcing<Spec>(

  "NativeSampleModule"

): Spec);
```

In this files, we are defining the function that needs to be implemented in C++.

### 3. Implement the Native Code[​](#3-implement-the-native-code "Direct link to 3. Implement the Native Code")

Now, we need to implement the function that we declared in the JS specification.

1. Open the `specs/NativeSampleModule.h` file and apply the following changes:

NativeSampleModule.h

```
#pragma once



#include <AppSpecsJSI.h>

#include <memory>

#include <string>



+ #include "Int64.h"



namespace facebook::react {



class NativeSampleModule : public NativeSampleModuleCxxSpec<NativeSampleModule> {

public:

  NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker);



  std::string reverseString(jsi::Runtime& rt, std::string input);

+ int32_t cubicRoot(jsi::Runtime& rt, int64_t input);

};



} // namespace facebook::react
```

2. Open the `specs/NativeSampleModule.cpp` file and apply the implement the new function:

NativeSampleModule.cpp

```
#include "NativeSampleModule.h"

+ #include <cmath>



namespace facebook::react {



NativeSampleModule::NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker)

    : NativeSampleModuleCxxSpec(std::move(jsInvoker)) {}



std::string NativeSampleModule::reverseString(jsi::Runtime& rt, std::string input) {

  return std::string(input.rbegin(), input.rend());

}



+int32_t NativeSampleModule::cubicRoot(jsi::Runtime& rt, int64_t input) {

+    return std::cbrt(input);

+}



} // namespace facebook::react
```

The implementation imports the `<cmath>` C++ library to perform mathematical operations, then it implements the `cubicRoot` function using the `cbrt` primitive from the `<cmath>` module.

### 4. Test your code in Your App[​](#4-test-your-code-in-your-app "Direct link to 4. Test your code in Your App")

Now, we can test the code in our app.

First, we need to update the `App.tsx` file to use the new method from the TurboModule. Then, we can build our apps in Android and iOS.

1. Open the `App.tsx` code apply the following changes:

App.tsx

```
// ...

+ const [cubicSource, setCubicSource] = useState('')

+ const [cubicRoot, setCubicRoot] = useState(0)

  return (

    <SafeAreaView style={styles.container}>

      <View>

        <Text style={styles.title}>

          Welcome to C++ Turbo Native Module Example

        </Text>

        <Text>Write down here the text you want to revert</Text>

        <TextInput

          style={styles.textInput}

          placeholder="Write your text here"

          onChangeText={setValue}

          value={value}

        />

        <Button title="Reverse" onPress={onPress} />

        <Text>Reversed text: {reversedValue}</Text>

+        <Text>For which number do you want to compute the Cubic Root?</Text>

+        <TextInput

+          style={styles.textInput}

+          placeholder="Write your text here"

+          onChangeText={setCubicSource}

+          value={cubicSource}

+        />

+        <Button title="Get Cubic Root" onPress={() => setCubicRoot(SampleTurboModule.cubicRoot(cubicSource))} />

+        <Text>The cubic root is: {cubicRoot}</Text>

      </View>

    </SafeAreaView>

  );

}

//...
```

2. To test the app on Android, run `yarn android` from the root folder of your project.
3. To test the app on iOS, run `yarn ios` from the root folder of your project.

## Adding a New Structured Custom Type: Address[​](#adding-a-new-structured-custom-type-address "Direct link to Adding a New Structured Custom Type: Address")

The approach above can be generalized to any kind of type. For structured types, React Native provides some helper functions that make it easier to bridge them from JS to C++ and vice versa.

Let's assume that we want to bridge a custom `Address` type with the following properties:

TypeScript

```
interface Address {

  street: string;

  num: number;

  isInUS: boolean;

}
```

### 1. Define the type in the specs[​](#1-define-the-type-in-the-specs "Direct link to 1. Define the type in the specs")

For the first step, let's define the new custom type in the JS specs, so that Codegen can output all the supporting code. In this way, we don't have to manually write the code.

1. Open the `specs/NativeSampleModule` file and add the following changes.

* TypeScript
* Flow

NativeSampleModule (Add Address type and validateAddress function)

```
import {TurboModule, TurboModuleRegistry} from 'react-native';



+export type Address = {

+  street: string,

+  num: number,

+  isInUS: boolean,

+};



export interface Spec extends TurboModule {

  readonly reverseString: (input: string) => string;

+ readonly validateAddress: (input: Address) => boolean;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeSampleModule',

);
```

NativeSampleModule (Add Address type and validateAddress function)

```


// @flow

import type {TurboModule} from 'react-native';

import { TurboModuleRegistry } from "react-native";



+export type Address = {

+  street: string,

+  num: number,

+  isInUS: boolean,

+};





export interface Spec extends TurboModule {

  +reverseString: (input: string) => string;

+ +validateAddress: (input: Address) => boolean;

}



export default (TurboModuleRegistry.getEnforcing<Spec>(

  "NativeSampleModule"

): Spec);
```

```
#include "Int64.h"

#include <memory>

#include <string>



namespace facebook::react {

+  using Address = NativeSampleModuleAddress<std::string, int32_t, bool>;



+  template <>

+  struct Bridging<Address>

+      : NativeSampleModuleAddressBridging<Address> {};

  // ...

}
```

```
  std::string reverseString(jsi::Runtime& rt, std::string input);



+  bool validateAddress(jsi::Runtime &rt, jsi::Object input);

};



} // namespace facebook::react
```

2. Open the `shared/NativeSampleModule.cpp` file and add the function implementation

NativeSampleModule.cpp (validateAddress implementation)

```
bool NativeSampleModule::validateAddress(jsi::Runtime &rt, jsi::Object input) {

  std::string street = input.getProperty(rt, "street").asString(rt).utf8(rt);

  int32_t number = input.getProperty(rt, "num").asNumber();



  return !street.empty() && number > 0;

}
```

```
const [street, setStreet] = useState('');

const [num, setNum] = useState('');

const [isValidAddress, setIsValidAddress] = useState<

  boolean | null

>(null);



const onPress = () => {

  let houseNum = parseInt(num, 10);

  if (isNaN(houseNum)) {

    houseNum = -1;

  }

  const address = {

    street,

    num: houseNum,

    isInUS: false,

  };

  const result = SampleTurboModule.validateAddress(address);

  setIsValidAddress(result);

};



return (

  <SafeAreaView style={styles.container}>

    <View>

      <Text style={styles.title}>

        Welcome to C Turbo Native Module Example

      </Text>

      <Text>Address:</Text>

      <TextInput

        style={styles.textInput}

        placeholder="Write your address here"

        onChangeText={setStreet}

        value={street}

      />

      <Text>Number:</Text>

      <TextInput

        style={styles.textInput}

        placeholder="Write your address here"

        onChangeText={setNum}

        value={num}

      />

      <Button title="Validate" onPress={onPress} />

      {isValidAddress != null && (

        <Text>

          Your address is {isValidAddress ? 'valid' : 'not valid'}

        </Text>

      )}

    </View>

  </SafeAreaView>

);
```

----
url: https://reactnative.dev/docs/clipboard
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=clipboard) instead.

----
url: https://reactnative.dev/docs/next/global-clearTimeout
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-clearTimeout)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearTimeout) for more information.

The global `clearTimeout` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-PerformanceObserverEntryList
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`PerformanceObserverEntryList`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/scrollview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/scrollview)** (0.87).

Version: Next

Component that wraps platform ScrollView while providing integration with touch locking "responder" system.

Keep in mind that ScrollViews must have a bounded height in order to work, since they contain unbounded-height children into a bounded container (via a scroll interaction). In order to bound the height of a ScrollView, either set the height of the view directly (discouraged) or make sure all parent views have bounded height. Forgetting to transfer `{flex: 1}` down the view stack can lead to errors here, which the element inspector makes quick to debug.

Doesn't yet support other contained responders from blocking this scroll view from becoming the responder.

`<ScrollView>` vs [`<FlatList>`](/docs/next/flatlist) - which one to use?

`ScrollView` renders all its react child components at once, but this has a performance downside.

Imagine you have a very long list of items you want to display, maybe several screens worth of content. Creating JS components and native views for everything all at once, much of which may not even be shown, will contribute to slow rendering and increased memory usage.

This is where `FlatList` comes into play. `FlatList` renders items lazily, when they are about to appear, and removes items that scroll way off screen to save memory and processing time.

`FlatList` is also handy if you want to render separators between your items, multiple columns, infinite scroll loading, or any number of other features it supports out of the box.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### `StickyHeaderComponent`[​](#stickyheadercomponent "Direct link to stickyheadercomponent")

A React Component that will be used to render sticky headers, should be used together with `stickyHeaderIndices`. You may need to set this component if your sticky header uses custom transforms, for example, when you want your list to have an animated and hidable header. If a component has not been provided, the default [`ScrollViewStickyHeader`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Components/ScrollView/ScrollViewStickyHeader.js) component will be used.

| Type               |
| ------------------ |
| component, element |

***

### `alwaysBounceHorizontal`iOS[​](#alwaysbouncehorizontal-ios "Direct link to alwaysbouncehorizontal-ios")

When true, the scroll view bounces horizontally when it reaches the end even if the content is smaller than the scroll view itself.

| Type | Default                                             |
| ---- | --------------------------------------------------- |
| bool | `true` when `horizontal={true}`***`false` otherwise |

***

### `alwaysBounceVertical`iOS[​](#alwaysbouncevertical-ios "Direct link to alwaysbouncevertical-ios")

When true, the scroll view bounces vertically when it reaches the end even if the content is smaller than the scroll view itself.

| Type | Default                                             |
| ---- | --------------------------------------------------- |
| bool | `false` when `horizontal={true}`***`true` otherwise |

***

### `automaticallyAdjustContentInsets`iOS[​](#automaticallyadjustcontentinsets-ios "Direct link to automaticallyadjustcontentinsets-ios")

Controls whether iOS should automatically adjust the content inset for scroll views that are placed behind a navigation bar or tab bar/toolbar.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `automaticallyAdjustKeyboardInsets`iOS[​](#automaticallyadjustkeyboardinsets-ios "Direct link to automaticallyadjustkeyboardinsets-ios")

Controls whether the ScrollView should automatically adjust its `contentInset` and `scrollViewInsets` when the Keyboard changes its size.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `automaticallyAdjustsScrollIndicatorInsets`iOS[​](#automaticallyadjustsscrollindicatorinsets-ios "Direct link to automaticallyadjustsscrollindicatorinsets-ios")

Controls whether iOS should automatically adjust the scroll indicator insets. See Apple's [documentation on the property](https://developer.apple.com/documentation/uikit/uiscrollview/3198043-automaticallyadjustsscrollindica).

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `bounces`iOS[​](#bounces-ios "Direct link to bounces-ios")

When true, the scroll view bounces when it reaches the end of the content if the content is larger than the scroll view along the axis of the scroll direction. When `false`, it disables all bouncing even if the `alwaysBounce*` props are `true`.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `bouncesZoom`iOS[​](#bounceszoom-ios "Direct link to bounceszoom-ios")

When `true`, gestures can drive zoom past min/max and the zoom will animate to the min/max value at gesture end, otherwise the zoom will not exceed the limits.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `canCancelContentTouches`iOS[​](#cancancelcontenttouches-ios "Direct link to cancancelcontenttouches-ios")

When `false`, once tracking starts, won't try to drag if the touch moves.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `centerContent`iOS[​](#centercontent-ios "Direct link to centercontent-ios")

When `true`, the scroll view automatically centers the content when the content is smaller than the scroll view bounds; when the content is larger than the scroll view, this property has no effect.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `contentContainerStyle`[​](#contentcontainerstyle "Direct link to contentcontainerstyle")

These styles will be applied to the scroll view content container which wraps all of the child views. Example:

```
return (

  <ScrollView contentContainerStyle={styles.contentContainer}>

  </ScrollView>

);

...

const styles = StyleSheet.create({

  contentContainer: {

    paddingVertical: 20

  }

});
```

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

***

### `contentInset`iOS[​](#contentinset-ios "Direct link to contentinset-ios")

The amount by which the scroll view content is inset from the edges of the scroll view.

| Type                                                                 | Default                                  |
| -------------------------------------------------------------------- | ---------------------------------------- |
| object: `{top: number, left: number, bottom: number, right: number}` | `{top: 0, left: 0, bottom: 0, right: 0}` |

***

### `contentInsetAdjustmentBehavior`iOS[​](#contentinsetadjustmentbehavior-ios "Direct link to contentinsetadjustmentbehavior-ios")

This property specifies how the safe area insets are used to modify the content area of the scroll view. Available on iOS 11 and later.

| Type                                                           | Default   |
| -------------------------------------------------------------- | --------- |
| enum(`'automatic'`, `'scrollableAxes'`, `'never'`, `'always'`) | `'never'` |

***

### `contentOffset`[​](#contentoffset "Direct link to contentoffset")

Used to manually set the starting scroll offset.

| Type  | Default        |
| ----- | -------------- |
| Point | `{x: 0, y: 0}` |

***

### `decelerationRate`[​](#decelerationrate "Direct link to decelerationrate")

A floating-point number that determines how quickly the scroll view decelerates after the user lifts their finger. You may also use string shortcuts `"normal"` and `"fast"` which match the underlying iOS settings for `UIScrollViewDecelerationRateNormal` and `UIScrollViewDecelerationRateFast` respectively.

* `'normal'` 0.998 on iOS, 0.985 on Android.
* `'fast'`, 0.99 on iOS, 0.9 on Android.

| Type                               | Default    |
| ---------------------------------- | ---------- |
| enum(`'fast'`, `'normal'`), number | `'normal'` |

***

### `directionalLockEnabled`iOS[​](#directionallockenabled-ios "Direct link to directionallockenabled-ios")

When true, the ScrollView will try to lock to only vertical or horizontal scrolling while dragging.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `disableIntervalMomentum`[​](#disableintervalmomentum "Direct link to disableintervalmomentum")

When true, the scroll view stops on the next index (in relation to scroll position at release) regardless of how fast the gesture is. This can be used for pagination when the page is less than the width of the horizontal ScrollView or the height of the vertical ScrollView.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `disableScrollViewPanResponder`[​](#disablescrollviewpanresponder "Direct link to disablescrollviewpanresponder")

When true, the default JS pan responder on the ScrollView is disabled, and full control over touches inside the ScrollView is left to its child components. This is particularly useful if `snapToInterval` is enabled, since it does not follow typical touch patterns. Do not use this on regular ScrollView use cases without `snapToInterval` as it may cause unexpected touches to occur while scrolling.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `endFillColor`Android[​](#endfillcolor-android "Direct link to endfillcolor-android")

Sometimes a scrollview takes up more space than its content fills. When this is the case, this prop will fill the rest of the scrollview with a color to avoid setting a background and creating unnecessary overdraw. This is an advanced optimization that is not needed in the general case.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `fadingEdgeLength`Android[​](#fadingedgelength-android "Direct link to fadingedgelength-android")

Fades out the edges of the scroll content.

If the value is greater than `0`, the fading edges will be set accordingly to the current scroll direction and position, indicating if there is more content to show.

| Type                                            | Default |
| ----------------------------------------------- | ------- |
| number***object: `{start: number, end: number}` | `0`     |

***

### `horizontal`[​](#horizontal "Direct link to horizontal")

When `true`, the scroll view's children are arranged horizontally in a row instead of vertically in a column.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `indicatorStyle`iOS[​](#indicatorstyle-ios "Direct link to indicatorstyle-ios")

The style of the scroll indicators.

* `'default'` same as `black`.
* `'black'`, scroll indicator is `black`. This style is good against a light background.
* `'white'`, scroll indicator is `white`. This style is good against a dark background.

| Type                                    | Default     |
| --------------------------------------- | ----------- |
| enum(`'default'`, `'black'`, `'white'`) | `'default'` |

***

### `invertStickyHeaders`[​](#invertstickyheaders "Direct link to invertstickyheaders")

If sticky headers should stick at the bottom instead of the top of the ScrollView. This is usually used with inverted ScrollViews.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `keyboardDismissMode`[​](#keyboarddismissmode "Direct link to keyboarddismissmode")

Determines whether the keyboard gets dismissed in response to a drag.

* `'none'`, drags do not dismiss the keyboard.
* `'on-drag'`, the keyboard is dismissed when a drag begins.

**iOS Only**

* `'interactive'`, the keyboard is dismissed interactively with the drag and moves in synchrony with the touch, dragging upwards cancels the dismissal. On Android this is not supported and it will have the same behavior as `'none'`.

| Type                                                                                 | Default  |
| ------------------------------------------------------------------------------------ | -------- |
| enum(`'none'`, `'on-drag'`)Android***enum(`'none'`, `'on-drag'`, `'interactive'`)iOS | `'none'` |

***

### `keyboardShouldPersistTaps`[​](#keyboardshouldpersisttaps "Direct link to keyboardshouldpersisttaps")

Determines when the keyboard should stay visible after a tap.

* `'never'` tapping outside of the focused text input when the keyboard is up dismisses the keyboard. When this happens, children won't receive the tap.
* `'always'`, the keyboard will not dismiss automatically, and the scroll view will not catch taps, but children of the scroll view can catch taps.
* `'handled'`, the keyboard will not dismiss automatically when the tap was handled by children of the scroll view (or captured by an ancestor).

| Type                                     | Default   |
| ---------------------------------------- | --------- |
| enum(`'always'`, `'never'`, `'handled'`) | `'never'` |

***

### `maintainVisibleContentPosition`[​](#maintainvisiblecontentposition "Direct link to maintainvisiblecontentposition")

When set, the scroll view will adjust the scroll position so that the first child that is currently visible and at or beyond `minIndexForVisible` will not change position. This is useful for lists that are loading content in both directions, e.g. a chat thread, where new messages coming in might otherwise cause the scroll position to jump. A value of 0 is common, but other values such as 1 can be used to skip loading spinners or other content that should not maintain position.

The optional `autoscrollToTopThreshold` can be used to make the content automatically scroll to the top after making the adjustment if the user was within the threshold of the top before the adjustment was made. This is also useful for chat-like applications where you want to see new messages scroll into place, but not if the user has scrolled up a ways and it would be disruptive to scroll a bunch.

Caveat 1: Reordering elements in the scrollview with this enabled will probably cause jumpiness and jank. It can be fixed, but there are currently no plans to do so. For now, don't re-order the content of any ScrollViews or Lists that use this feature.

Caveat 2: This uses `contentOffset` and `frame.origin` in native code to compute visibility. Occlusion, transforms, and other complexity won't be taken into account as to whether content is "visible" or not.

| Type                                                                     |
| ------------------------------------------------------------------------ |
| object: `{minIndexForVisible: number, autoscrollToTopThreshold: number}` |

***

### `maximumZoomScale`iOS[​](#maximumzoomscale-ios "Direct link to maximumzoomscale-ios")

The maximum allowed zoom scale.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

### `minimumZoomScale`iOS[​](#minimumzoomscale-ios "Direct link to minimumzoomscale-ios")

The minimum allowed zoom scale.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

### `nestedScrollEnabled`Android[​](#nestedscrollenabled-android "Direct link to nestedscrollenabled-android")

Enables nested scrolling for Android API level 21+.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `onContentSizeChange`[​](#oncontentsizechange "Direct link to oncontentsizechange")

Called when scrollable content view of the ScrollView changes.

The handler function will receive two parameters: the content width and content height `(contentWidth, contentHeight)`.

It's implemented using onLayout handler attached to the content container which this ScrollView renders.

| Type     |
| -------- |
| function |

***

### `onMomentumScrollBegin`[​](#onmomentumscrollbegin "Direct link to onmomentumscrollbegin")

Called when the momentum scroll starts (scroll which occurs as the ScrollView starts gliding).

| Type     |
| -------- |
| function |

***

### `onMomentumScrollEnd`[​](#onmomentumscrollend "Direct link to onmomentumscrollend")

Called when the momentum scroll ends (scroll which occurs as the ScrollView glides to a stop).

| Type     |
| -------- |
| function |

***

### `onScroll`[​](#onscroll "Direct link to onscroll")

Fires at most once per frame during scrolling. The event has the following shape (all values with unspecified type are numbers):

JavaScript

```
{

  nativeEvent: {

    contentInset: {bottom, left, right, top},

    contentOffset: {x, y},

    contentSize: {height, width},

    layoutMeasurement: {height, width},

    velocity: {x, y},

    responderIgnoreScroll: boolean,

    zoomScale,

    // iOS only

    targetContentOffset: {x, y}

  }

}
```

| Type     |
| -------- |
| function |

***

### `onScrollBeginDrag`[​](#onscrollbegindrag "Direct link to onscrollbegindrag")

Called when the user begins to drag the scroll view.

| Type     |
| -------- |
| function |

***

### `onScrollEndDrag`[​](#onscrollenddrag "Direct link to onscrollenddrag")

Called when the user stops dragging the scroll view and it either stops or begins to glide.

| Type     |
| -------- |
| function |

***

### `onScrollToTop`iOS[​](#onscrolltotop-ios "Direct link to onscrolltotop-ios")

Fires when the scroll view scrolls to top after the status bar has been tapped.

| Type     |
| -------- |
| function |

***

### `overScrollMode`Android[​](#overscrollmode-android "Direct link to overscrollmode-android")

Used to override default value of overScroll mode.

Possible values:

* `'auto'` - Allow a user to over-scroll this view only if the content is large enough to meaningfully scroll.
* `'always'` - Always allow a user to over-scroll this view.
* `'never'` - Never allow a user to over-scroll this view.

| Type                                  | Default  |
| ------------------------------------- | -------- |
| enum(`'auto'`, `'always'`, `'never'`) | `'auto'` |

***

### `pagingEnabled`[​](#pagingenabled "Direct link to pagingenabled")

When true, the scroll view stops on multiples of the scroll view's size when scrolling. This can be used for horizontal pagination.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `persistentScrollbar`Android[​](#persistentscrollbar-android "Direct link to persistentscrollbar-android")

Causes the scrollbars not to turn transparent when they are not in use.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `pinchGestureEnabled`iOS[​](#pinchgestureenabled-ios "Direct link to pinchgestureenabled-ios")

When true, ScrollView allows use of pinch gestures to zoom in and out.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `refreshControl`[​](#refreshcontrol "Direct link to refreshcontrol")

A RefreshControl component, used to provide pull-to-refresh functionality for the ScrollView. Only works for vertical ScrollViews (`horizontal` prop must be `false`).

See [RefreshControl](/docs/next/refreshcontrol).

| Type    |
| ------- |
| element |

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

warning

Using this property may lead to bugs (missing content) in some circumstances - use at your own risk.

When `true`, offscreen child views are removed from their native backing superview when offscreen. This may improve scroll performance for large lists. On Android the default value is `true`.

| Type    |
| ------- |
| boolean |

***

### `scrollEnabled`[​](#scrollenabled "Direct link to scrollenabled")

When false, the view cannot be scrolled via touch interaction.

Note that the view can always be scrolled by calling `scrollTo`.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `scrollEventThrottle`[​](#scrolleventthrottle "Direct link to scrolleventthrottle")

Limits how often scroll events will be fired while scrolling, specified as a time interval in ms. This may be useful when expensive work is performed in response to scrolling. Values ≤ `16` will disable throttling, regardless of the refresh rate of the device.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

***

### `scrollIndicatorInsets`iOS[​](#scrollindicatorinsets-ios "Direct link to scrollindicatorinsets-ios")

The amount by which the scroll view indicators are inset from the edges of the scroll view. This should normally be set to the same value as the `contentInset`.

| Type                                                                 | Default                                  |
| -------------------------------------------------------------------- | ---------------------------------------- |
| object: `{top: number, left: number, bottom: number, right: number}` | `{top: 0, left: 0, bottom: 0, right: 0}` |

***

### `scrollPerfTag`Android[​](#scrollperftag-android "Direct link to scrollperftag-android")

Tag used to log scroll performance on this scroll view. Will force momentum events to be turned on (see sendMomentumEvents). This doesn't do anything out of the box and you need to implement a custom native FpsListener for it to be useful.

| Type   |
| ------ |
| string |

***

### `scrollsChildToFocus`Android[​](#scrollschildtofocus-android "Direct link to scrollschildtofocus-android")

When `true`, the ScrollView automatically scrolls to bring a focused child into view. Set to `false` to disable this behavior and take manual control of scroll position when focus changes.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `scrollToOverflowEnabled`iOS[​](#scrolltooverflowenabled-ios "Direct link to scrolltooverflowenabled-ios")

When `true`, the scroll view can be programmatically scrolled beyond its content size.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `scrollsToTop`iOS[​](#scrollstotop-ios "Direct link to scrollstotop-ios")

When `true`, the scroll view scrolls to top when the status bar is tapped.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `showsHorizontalScrollIndicator`[​](#showshorizontalscrollindicator "Direct link to showshorizontalscrollindicator")

When `true`, shows a horizontal scroll indicator.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `showsVerticalScrollIndicator`[​](#showsverticalscrollindicator "Direct link to showsverticalscrollindicator")

When `true`, shows a vertical scroll indicator.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `snapToAlignment`[​](#snaptoalignment "Direct link to snaptoalignment")

When `snapToInterval` is set, `snapToAlignment` will define the relationship of the snapping to the scroll view.

Possible values:

* `'start'` will align the snap at the left (horizontal) or top (vertical).
* `'center'` will align the snap in the center.
* `'end'` will align the snap at the right (horizontal) or bottom (vertical).

| Type                                 | Default   |
| ------------------------------------ | --------- |
| enum(`'start'`, `'center'`, `'end'`) | `'start'` |

***

### `snapToEnd`[​](#snaptoend "Direct link to snaptoend")

Use in conjunction with `snapToOffsets`. By default, the end of the list counts as a snap offset. Set `snapToEnd` to false to disable this behavior and allow the list to scroll freely between its end and the last `snapToOffsets` offset.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `snapToInterval`[​](#snaptointerval "Direct link to snaptointerval")

When set, causes the scroll view to stop at multiples of the value of `snapToInterval`. This can be used for paginating through children that have lengths smaller than the scroll view. Typically used in combination with `snapToAlignment` and `decelerationRate="fast"`. Overrides less configurable `pagingEnabled` prop.

| Type   |
| ------ |
| number |

***

### `snapToOffsets`[​](#snaptooffsets "Direct link to snaptooffsets")

When set, causes the scroll view to stop at the defined offsets. This can be used for paginating through variously sized children that have lengths smaller than the scroll view. Typically used in combination with `decelerationRate="fast"`. Overrides less configurable `pagingEnabled` and `snapToInterval` props.

| Type            |
| --------------- |
| array of number |

***

### `snapToStart`[​](#snaptostart "Direct link to snaptostart")

Use in conjunction with `snapToOffsets`. By default, the beginning of the list counts as a snap offset. Set `snapToStart` to `false` to disable this behavior and allow the list to scroll freely between its start and the first `snapToOffsets` offset.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `stickyHeaderHiddenOnScroll`[​](#stickyheaderhiddenonscroll "Direct link to stickyheaderhiddenonscroll")

When set to `true`, sticky header will be hidden when scrolling down the list, and it will dock at the top of the list when scrolling up.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `stickyHeaderIndices`[​](#stickyheaderindices "Direct link to stickyheaderindices")

An array of child indices determining which children get docked to the top of the screen when scrolling. For example, passing `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the top of the scroll view. You can also use like \[x,y,z] to make multiple items sticky when they are at the top. This property is not supported in conjunction with `horizontal={true}`.

| Type            |
| --------------- |
| array of number |

***

### `zoomScale`iOS[​](#zoomscale-ios "Direct link to zoomscale-ios")

The current scale of the scroll view content.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

## Methods[​](#methods "Direct link to Methods")

### `flashScrollIndicators()`[​](#flashscrollindicators "Direct link to flashscrollindicators")

React TSX

```
flashScrollIndicators();
```

Displays the scroll indicators momentarily.

***

### `scrollTo()`[​](#scrollto "Direct link to scrollto")

React TSX

```
scrollTo(

  options?: {x?: number, y?: number, animated?: boolean} | number,

  deprecatedX?: number,

  deprecatedAnimated?: boolean,

);
```

Scrolls to a given x, y offset, either immediately, with a smooth animation.

**Example:**

`scrollTo({x: 0, y: 0, animated: true})`

note

The weird function signature is due to the fact that, for historical reasons, the function also accepts separate arguments as an alternative to the options object. This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.

***

### `scrollToEnd()`[​](#scrolltoend "Direct link to scrolltoend")

React TSX

```
scrollToEnd(options?: {animated?: boolean});
```

    [iOS](#alwaysbouncehorizontal-ios)
  * [`alwaysBounceVertical`](#alwaysbouncevertical-ios)

    [iOS](#alwaysbouncevertical-ios)
  * [`automaticallyAdjustContentInsets`](#automaticallyadjustcontentinsets-ios)

    [iOS](#automaticallyadjustcontentinsets-ios)
  * [`automaticallyAdjustKeyboardInsets`](#automaticallyadjustkeyboardinsets-ios)

    [iOS](#automaticallyadjustkeyboardinsets-ios)
  * [`automaticallyAdjustsScrollIndicatorInsets`](#automaticallyadjustsscrollindicatorinsets-ios)

    [iOS](#automaticallyadjustsscrollindicatorinsets-ios)
  * [`bounces`](#bounces-ios)

    [iOS](#bounces-ios)
  * [`bouncesZoom`](#bounceszoom-ios)

    [iOS](#bounceszoom-ios)
  * [`canCancelContentTouches`](#cancancelcontenttouches-ios)

    [iOS](#cancancelcontenttouches-ios)
  * [`centerContent`](#centercontent-ios)

    [iOS](#centercontent-ios)
  * [`contentContainerStyle`](#contentcontainerstyle)
  * [`contentInset`](#contentinset-ios)

    [iOS](#contentinset-ios)
  * [`contentInsetAdjustmentBehavior`](#contentinsetadjustmentbehavior-ios)

    [iOS](#contentinsetadjustmentbehavior-ios)
  * [`contentOffset`](#contentoffset)
  * [`decelerationRate`](#decelerationrate)
  * [`directionalLockEnabled`](#directionallockenabled-ios)

    [iOS](#directionallockenabled-ios)
  * [`disableIntervalMomentum`](#disableintervalmomentum)
  * [`disableScrollViewPanResponder`](#disablescrollviewpanresponder)
  * [`endFillColor`](#endfillcolor-android)

    [Android](#endfillcolor-android)
  * [`fadingEdgeLength`](#fadingedgelength-android)

    [Android](#fadingedgelength-android)
  * [`horizontal`](#horizontal)
  * [`indicatorStyle`](#indicatorstyle-ios)

    [iOS](#indicatorstyle-ios)
  * [`invertStickyHeaders`](#invertstickyheaders)
  * [`keyboardDismissMode`](#keyboarddismissmode)
  * [`keyboardShouldPersistTaps`](#keyboardshouldpersisttaps)
  * [`maintainVisibleContentPosition`](#maintainvisiblecontentposition)
  * [`maximumZoomScale`](#maximumzoomscale-ios)

    [iOS](#maximumzoomscale-ios)
  * [`minimumZoomScale`](#minimumzoomscale-ios)

    [iOS](#minimumzoomscale-ios)
  * [`nestedScrollEnabled`](#nestedscrollenabled-android)

    [Android](#nestedscrollenabled-android)

    [iOS](#onscrolltotop-ios)
  * [`overScrollMode`](#overscrollmode-android)

    [Android](#overscrollmode-android)
  * [`pagingEnabled`](#pagingenabled)
  * [`persistentScrollbar`](#persistentscrollbar-android)

    [Android](#persistentscrollbar-android)
  * [`pinchGestureEnabled`](#pinchgestureenabled-ios)

    [iOS](#pinchgestureenabled-ios)
  * [`refreshControl`](#refreshcontrol)
  * [`removeClippedSubviews`](#removeclippedsubviews)
  * [`scrollEnabled`](#scrollenabled)
  * [`scrollEventThrottle`](#scrolleventthrottle)
  * [`scrollIndicatorInsets`](#scrollindicatorinsets-ios)

    [iOS](#scrollindicatorinsets-ios)
  * [`scrollPerfTag`](#scrollperftag-android)

    [Android](#scrollperftag-android)
  * [`scrollsChildToFocus`](#scrollschildtofocus-android)

    [Android](#scrollschildtofocus-android)
  * [`scrollToOverflowEnabled`](#scrolltooverflowenabled-ios)

    [iOS](#scrolltooverflowenabled-ios)
  * [`scrollsToTop`](#scrollstotop-ios)

    [iOS](#scrollstotop-ios)

    [iOS](#zoomscale-ios)

* [Methods](#methods)

  * [`flashScrollIndicators()`](#flashscrollindicators)
  * [`scrollTo()`](#scrollto)
  * [`scrollToEnd()`](#scrolltoend)

----
url: https://reactnative.dev/docs/next/fabric-native-components-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/fabric-native-components-ios)** (0.87).

Version: Next

Now it's time to write some iOS platform code to be able to render the web view. The steps you need to follow are:

* Run Codegen.
* Write the code for the `RCTWebView`
* Register the `RCTWebView` in the application

### 1. Run Codegen[​](#1-run-codegen "Direct link to 1. Run Codegen")

You can [manually run](/docs/next/the-new-architecture/codegen-cli) the Codegen, however it's simpler to use the application you're going to demo the component in to do this for you.

```
cd ios

bundle install

bundle exec pod install
```

Importantly you will see logging output from Codegen, which we're going to use in Xcode to build our WebView native component.

warning

You should be careful about committing generated code to your repository. Generated code is specific to each version of React Native. Use npm [peerDependencies](https://nodejs.org/en/blog/npm/peer-dependencies) to restrict compatibility with version of React Native.

### 3. Write the `RCTWebView`[​](#3-write-the-rctwebview "Direct link to 3-write-the-rctwebview")

We need to prepare your iOS project using Xcode by completing these **5 steps**:

1. Open the CocoaPods generated Xcode Workspace:

```
cd ios

open Demo.xcworkspace
```

2. Right click on app and select `New Group`, call the new group `WebView`.

3) In the `WebView` group, create `New`→`File from Template`.

4. Use the `Objective-C File` template, and name it `RCTWebView`.

5) Repeat step 4 and create a header file named `RCTWebView.h`.

6) Rename `RCTWebView.m` → `RCTWebView.mm` making it an Objective-C++ file.

Demo/ios

```
Podfile

...

Demo

├── AppDelegate.swift

├── SceneDelegate.swift

...

├── RCTWebView.h

└── RCTWebView.mm
```

After creating the header file and the implementation file, you can start implementing them.

This is the code for the `RCTWebView.h` file, which declares the component interface.

Demo/RCTWebView/RCTWebView\.h

```
#import <React/RCTViewComponentView.h>

#import <UIKit/UIKit.h>



NS_ASSUME_NONNULL_BEGIN



@interface RCTWebView : RCTViewComponentView



// You would declare native methods you'd want to access from the view here



@end



NS_ASSUME_NONNULL_END
```

This class defines an `RCTWebView` which extends the `RCTViewComponentView` class. This is the base class for all the native components and it is provided by React Native.

The code for the implementation file (`RCTWebView.mm`) is the following:

Demo/RCTWebView/RCTWebView\.mm

```
#import "RCTWebView.h"



#import <react/renderer/components/AppSpec/ComponentDescriptors.h>

#import <react/renderer/components/AppSpec/EventEmitters.h>

#import <react/renderer/components/AppSpec/Props.h>

#import <react/renderer/components/AppSpec/RCTComponentViewHelpers.h>

#import <WebKit/WebKit.h>



using namespace facebook::react;



@interface RCTWebView () <RCTCustomWebViewViewProtocol, WKNavigationDelegate>

@end



@implementation RCTWebView {

  NSURL * _sourceURL;

  WKWebView * _webView;

}



-(instancetype)init

{

  if(self = [super init]) {

    _webView = [WKWebView new];

    _webView.navigationDelegate = self;

    [self addSubview:_webView];

  }

  return self;

}



- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps

{

  const auto &oldViewProps = *std::static_pointer_cast<CustomWebViewProps const>(_props);

  const auto &newViewProps = *std::static_pointer_cast<CustomWebViewProps const>(props);



  // Handle your props here

  if (oldViewProps.sourceURL != newViewProps.sourceURL) {

    NSString *urlString = [NSString stringWithCString:newViewProps.sourceURL.c_str() encoding:NSUTF8StringEncoding];

    _sourceURL = [NSURL URLWithString:urlString];

    if ([self urlIsValid:newViewProps.sourceURL]) {

      [_webView loadRequest:[NSURLRequest requestWithURL:_sourceURL]];

    }

  }



  [super updateProps:props oldProps:oldProps];

}



-(void)layoutSubviews

{

  [super layoutSubviews];

  _webView.frame = self.bounds;



}



#pragma mark - WKNavigationDelegate



-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{

  CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Success};

  self.eventEmitter.onScriptLoaded(result);

}



- (BOOL)urlIsValid:(std::string)propString

{

  if (propString.length() > 0 && !_sourceURL) {

    CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Error};



    self.eventEmitter.onScriptLoaded(result);

    return NO;

  }

  return YES;

}



// Event emitter convenience method

- (const CustomWebViewEventEmitter &)eventEmitter

{

  return static_cast<const CustomWebViewEventEmitter &>(*_eventEmitter);

}



+ (ComponentDescriptorProvider)componentDescriptorProvider

{

  return concreteComponentDescriptorProvider<CustomWebViewComponentDescriptor>();

}



@end
```

----
url: https://reactnative.dev/docs/next/javascript-environment
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/javascript-environment)** (0.87).

Version: Next

## JavaScript Runtime[​](#javascript-runtime "Direct link to JavaScript Runtime")

When using React Native, you're going to be running your JavaScript code in up to three environments:

* In most cases, React Native will use [Hermes](/docs/next/hermes), an open-source JavaScript engine optimized for React Native.

| Transformation                                                                                              | Code                                                                               |
| ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| ECMAScript 5                                                                                                |                                                                                    |
| Reserved Words                                                                                              | ```
promise.catch(function() {...});
```                                           |
| ECMAScript 2015 (ES6)                                                                                       |                                                                                    |
| [Arrow functions](https://babeljs.io/docs/learn-es2015/#arrows)                                             | ```
<C onPress={() => this.setState({pressed: true})} />
```                       |
| [Block scoping](https://babeljs.io/docs/learn-es2015/#let-const)                                            | ```
let greeting = 'hi';
```                                                       |
| [Call spread](https://babeljs.io/docs/learn-es2015/#default-rest-spread)                                    | ```
Math.max(...array);
```                                                        |
| [Classes](https://babeljs.io/docs/learn-es2015/#classes)                                                    | ```
class C extends React.Component {render() { return <View />; }}
```            |
| [Computed Properties](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals)                       | ```
const key = 'abc'; const obj = {[key]: 10};
```                                |
| [Constants](https://babeljs.io/docs/learn-es2015/#let-const)                                                | ```
const answer = 42;
```                                                         |
| [Destructuring](https://babeljs.io/docs/learn-es2015/#destructuring)                                        | ```
const {isActive, style} = this.props;
```                                      |
| [for…of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)             | ```
for (var num of [1, 2, 3]) {...};
```                                          |
| [Function Name](https://babeljs.io/docs/en/babel-plugin-transform-function-name)                            | ```
let number = x => x;
```                                                       |
| [Literals](https://babeljs.io/docs/en/babel-plugin-transform-literals)                                      | ```
const b = 0b11; const o = 0o7; const u = 'Hello\u{000A}\u{0009}!';
```         |
| [Modules](https://babeljs.io/docs/learn-es2015/#modules)                                                    | ```
import {Component} from 'react';
```                                           |
| [Object Concise Method](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals)                     | ```
const obj = {method() { return 10; }};
```                                     |
| [Object Short Notation](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals)                     | ```
const name = 'vjeux'; const obj = {name};
```                                  |
| [Parameters](https://babeljs.io/docs/en/babel-plugin-transform-parameters)                                  | ```
function test(x = 'hello', {a, b}, ...args) {}
```                             |
| [Rest Params](https://github.com/sebmarkbage/ecmascript-rest-spread)                                        | ```
function(type, ...args) {};
```                                                |
| [Shorthand Properties](https://babeljs.io/docs/en/babel-plugin-transform-shorthand-properties)              | ```
const o = {a, b, c};
```                                                       |
| [Sticky Regex](https://babeljs.io/docs/en/babel-plugin-transform-sticky-regex)                              | ```
const a = /o+/y;
```                                                           |
| [Template Literals](https://babeljs.io/docs/learn-es2015/#template-strings)                                 | ```
const who = 'world'; const str = `Hello ${who}`;
```                           |
| [Unicode Regex](https://babeljs.io/docs/en/babel-plugin-transform-unicode-regex)                            | ```
const string = 'foo💩bar'; const match = string.match(/foo(.)bar/u);
```       |
| ECMAScript 2016 (ES7)                                                                                       |                                                                                    |
| [Exponentiation Operator](https://babeljs.io/docs/en/babel-plugin-transform-exponentiation-operator)        | ```
let x = 10 ** 2;
```                                                           |
| ECMAScript 2017 (ES8)                                                                                       |                                                                                    |
| [Async Functions](https://github.com/tc39/ecmascript-asyncawait)                                            | ```
async function doStuffAsync() {const foo = await doOtherStuffAsync();};
```    |
| [Function Trailing Comma](https://github.com/jeffmo/es-trailing-function-commas)                            | ```
function f(a, b, c,) {};
```                                                   |
| ECMAScript 2018 (ES9)                                                                                       |                                                                                    |
| [Object Spread](https://github.com/tc39/proposal-object-rest-spread)                                        | ```
const extended = {...obj, a: 10};
```                                          |
| ECMAScript 2019 (ES10)                                                                                      |                                                                                    |
| [Optional Catch Binding](https://babeljs.io/docs/en/babel-plugin-proposal-optional-catch-binding)           | ```
try {throw 0; } catch { doSomethingWhichDoesNotCareAboutTheValueThrown();}
``` |
| ECMAScript 2020 (ES11)                                                                                      |                                                                                    |
| [Dynamic Imports](https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import)                            | ```
const package = await import('package'); package.function()
```                |
| [Nullish Coalescing Operator](https://babeljs.io/docs/en/babel-plugin-proposal-nullish-coalescing-operator) | ```
const foo = object.foo ?? 'default';
```                                       |
| [Optional Chaining](https://github.com/tc39/proposal-optional-chaining)                                     | ```
const name = obj.user?.name;
```                                               |
| ECMAScript 2022 (ES13)                                                                                      |                                                                                    |
| [Class Fields](https://babeljs.io/docs/en/babel-plugin-proposal-class-properties)                           | ```
class Bork {static a = 'foo'; static b; x = 'bar'; y;}
```                     |
| Stage 1 Proposal                                                                                            |                                                                                    |
| [Export Default From](https://babeljs.io/docs/en/babel-plugin-proposal-export-default-from)                 | ```
export v from 'mod';
```                                                       |
| Miscellaneous                                                                                               |                                                                                    |
| [Babel Template](https://babeljs.io/docs/en/babel-template)                                                 | ```
template(`const %%importName%% = require(%%source%%);`);
```                   |
| [Flow](https://flowtype.org/)                                                                               | ```
function foo(x: ?number): string {};
```                                       |
| [ESM to CJS](https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs)                            | ```
export default 42;
```                                                         |
| [JSX](https://react.dev/learn/writing-markup-with-jsx)                                                      | ```
<View style={{color: 'red'}} />
```                                            |
| [Object Assign](https://babeljs.io/docs/en/babel-plugin-transform-object-assign)                            | ```
Object.assign(a, b);
```                                                       |
| [React Display Name](https://babeljs.io/docs/en/babel-plugin-transform-react-display-name)                  | ```
const bar = createReactClass({});
```                                          |
| [TypeScript](https://www.typescriptlang.org/)                                                               | ```
function foo(x: {hello: true, target: 'react native!'}): string {};
```        |

## Polyfills[​](#polyfills "Direct link to Polyfills")

Many standard functions are also available on all the supported JavaScript runtimes.

#### Browser[​](#browser "Direct link to Browser")

* [CommonJS `require`](https://nodejs.org/docs/latest/api/modules.html)
* `console.{log, warn, error, info, debug, trace, table, group, groupCollapsed, groupEnd}`
* [`XMLHttpRequest`, `fetch`](/docs/next/network)
* [`{set, clear}{Timeout, Interval, Immediate}, {request, cancel}AnimationFrame`](/docs/next/timers)

#### ECMAScript 2015 (ES6)[​](#ecmascript-2015-es6 "Direct link to ECMAScript 2015 (ES6)")

* [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
* `Array.prototype.{find, findIndex}`
* [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
* `String.prototype.{startsWith, endsWith, repeat, includes}`

#### ECMAScript 2016 (ES7)[​](#ecmascript-2016-es7 "Direct link to ECMAScript 2016 (ES7)")

* `Array.prototype.includes`

#### ECMAScript 2017 (ES8)[​](#ecmascript-2017-es8 "Direct link to ECMAScript 2017 (ES8)")

* `Object.{entries, values}`

#### Specific[​](#specific "Direct link to Specific")

* `__DEV__`

- [JavaScript Runtime](#javascript-runtime)
- [JavaScript Syntax Transformers](#javascript-syntax-transformers)
- [Polyfills](#polyfills)

----
url: https://reactnative.dev/docs/next/share
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/share)** (0.87).

Version: Next

```
static share(content: ShareContent, options?: ShareOptions);
```

Open a dialog to share text content.

In iOS, returns a Promise which will be invoked with an object containing `action` and `activityType`. If the user dismissed the dialog, the Promise will still be resolved with action being `Share.dismissedAction` and all the other keys being undefined. Note that some share options will not appear or work on the iOS simulator.

In Android, returns a Promise which will always be resolved with action being `Share.sharedAction`.

**Properties:**

| Name            | Type   | Description                                                                                                                                                                                    |
| --------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| contentRequired | object | `message` - a message to share `url` - a URL to shareiOS `title` - title of the messageAndroid***At least one of `url` and `message` is required.                                              |
| options         | object | `dialogTitle`Android `excludedActivityTypes`iOS `subject` - a subject to share via emailiOS `tintColor`iOS `anchor` - the node to which the action sheet should be anchored (used for iPad)iOS |

***

## Properties[​](#properties "Direct link to Properties")

### `sharedAction`[​](#sharedaction "Direct link to sharedaction")

React TSX

```
static sharedAction: 'sharedAction';
```

The content was successfully shared.

***

### `dismissedAction`iOS[​](#dismissedaction-ios "Direct link to dismissedaction-ios")

React TSX

```
static dismissedAction: 'dismissedAction';
```

    [iOS](#dismissedaction-ios)

----
url: https://reactnative.dev/docs/global-Headers
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Headers) for more information.

The global `Headers` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-window
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

[`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window/window) is an alias for [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), as defined in Web specifications.

The use of `globalThis` is recommended over `window`.

----
url: https://reactnative.dev/docs/optimizing-flatlist-configuration
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

| Type    | Default                              |
| ------- | ------------------------------------ |
| Boolean | `true` on Android, otherwise `false` |

If `true`, views that are outside of the viewport are automatically detached from the native view hierarchy.

**Pros:** This reduces time spent on the main thread, and thus reduces the risk of dropped frames, by excluding views outside of the viewport from the native rendering and drawing traversals.

**Cons:** Be aware that this implementation can have bugs, such as missing content (mainly observed on iOS), especially if you are doing complex things with transforms and/or absolute positioning. Also note this does not save significant memory because the views are not deallocated, only detached.

### `maxToRenderPerBatch`[​](#maxtorenderperbatch "Direct link to maxtorenderperbatch")

| Type   | Default |
| ------ | ------- |
| Number | 10      |

It is a `VirtualizedList` prop that can be passed through `FlatList`. This controls the amount of items rendered per batch, which is the next chunk of items rendered on every scroll.

**Pros:** Setting a bigger number means less visual blank areas when scrolling (increases the fill rate).

**Cons:** More items per batch means longer periods of JavaScript execution potentially blocking other event processing, like presses, hurting responsiveness.

### `updateCellsBatchingPeriod`[​](#updatecellsbatchingperiod "Direct link to updatecellsbatchingperiod")

| Type   | Default |
| ------ | ------- |
| Number | 50      |

While `maxToRenderPerBatch` tells the amount of items rendered per batch, setting `updateCellsBatchingPeriod` tells your `VirtualizedList` the delay in milliseconds between batch renders (how frequently your component will be rendering the windowed items).

**Pros:** Combining this prop with `maxToRenderPerBatch` gives you the power to, for example, render more items in a less frequent batch, or less items in a more frequent batch.

**Cons:** Less frequent batches may cause blank areas, More frequent batches may cause responsiveness issues.

### initialNumToRender[​](#initialnumtorender "Direct link to initialNumToRender")

| Type   | Default |
| ------ | ------- |
| Number | 10      |

The initial amount of items to render.

**Pros:** Define precise number of items that would cover the screen for every device. This can be a big performance boost for the initial render.

**Cons:** Setting a low `initialNumToRender` may cause blank areas, especially if it's too small to cover the viewport on initial render.

### `windowSize`[​](#windowsize "Direct link to windowsize")

| Type   | Default |
| ------ | ------- |
| Number | 21      |

```
import {memo} from 'react';

import {View, Text} from 'react-native';



const MyListItem = memo(

  ({title}: {title: string}) => (

    <View>

      <Text>{title}</Text>

    </View>

  ),

  (prevProps, nextProps) => {

    return prevProps.title === nextProps.title;

  },

);



export default MyListItem;
```

In this example, we have determined that MyListItem should be re-rendered only when the title changes. We passed the comparison function as the second argument to React.memo() so that the component is re-rendered only when the specified prop is changed. If the comparison function returns true, the component will not be re-rendered.

### Use cached optimized images[​](#use-cached-optimized-images "Direct link to Use cached optimized images")

You can use the community packages (such as [@d11/react-native-fast-image](https://github.com/ds-horizon/react-native-fast-image) from [Dream11](https://github.com/ds-horizon)) for more performant images. Every image in your list is a `new Image()` instance. The faster it reaches the `loaded` hook, the faster your JavaScript thread will be free again.

### Use `getItemLayout`[​](#use-getitemlayout "Direct link to use-getitemlayout")

If all your list item components have the same height (or width, for a horizontal list), providing the [getItemLayout](/docs/flatlist#getitemlayout) prop removes the need for your `FlatList` to manage async layout calculations. This is a very desirable optimization technique.

If your components have dynamic size and you really need performance, consider asking your design team if they may think of a redesign in order to perform better.

### Use `keyExtractor` or `key`[​](#use-keyextractor-or-key "Direct link to use-keyextractor-or-key")

You can set the [`keyExtractor`](/docs/flatlist#keyextractor) to your `FlatList` component. This prop is used for caching and as the React `key` to track item re-ordering.

You can also use a `key` prop in your item component.

### Avoid anonymous function on `renderItem`[​](#avoid-anonymous-function-on-renderitem "Direct link to avoid-anonymous-function-on-renderitem")

For functional components, move the `renderItem` function outside of the returned JSX. Also, ensure that it is wrapped in a `useCallback` hook to prevent it from being recreated each render.

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.

React TSX

```
const renderItem = useCallback(({item}) => (

   <View key={item.key}>

      <Text>{item.title}</Text>

   </View>

 ), []);



return (

  // ...

  <FlatList data={items} renderItem={renderItem} />;

  // ...

);
```

----
url: https://reactnative.dev/docs/communication-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

In [Integrating with Existing Apps guide](/docs/integration-with-existing-apps) and [Native UI Components guide](/docs/legacy/native-components-android) we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.

```
public class MainActivity extends ReactActivity {

  @Override

  protected ReactActivityDelegate createReactActivityDelegate() {

    return new ReactActivityDelegate(this, getMainComponentName()) {

      @Override

      protected Bundle getLaunchOptions() {

        Bundle initialProperties = new Bundle();

        ArrayList<String> imageList = new ArrayList<String>(Arrays.asList(

                "https://dummyimage.com/600x400/ffffff/000000.png",

                "https://dummyimage.com/600x400/000000/ffffff.png"

        ));

        initialProperties.putStringArrayList("images", imageList);

        return initialProperties;

      }

    };

  }

}
```

Kotlin

```
class MainActivity : ReactActivity() {

    override fun createReactActivityDelegate(): ReactActivityDelegate {

        return object : ReactActivityDelegate(this, mainComponentName) {

            override fun getLaunchOptions(): Bundle {

                val imageList = arrayListOf("https://dummyimage.com/600x400/ffffff/000000.png", "https://dummyimage.com/600x400/000000/ffffff.png")

                val initialProperties = Bundle().apply { putStringArrayList("images", imageList) }

                return initialProperties

            }

        }

    }

}
```

React TSX

```
import {View, Image} from 'react-native';



export default class ImageBrowserApp extends React.Component {

  renderImage(imgURI) {

    return <Image source={{uri: imgURI}} />;

  }

  render() {

    return <View>{this.props.images.map(this.renderImage)}</View>;

  }

}
```

`ReactRootView` provides a read-write property `appProperties`. After `appProperties` is set, the React Native app is re-rendered with new properties. The update is only performed when the new updated properties differ from the previous ones.

* Java
* Kotlin

Java

```
Bundle updatedProps = mReactRootView.getAppProperties();

ArrayList<String> imageList = new ArrayList<String>(Arrays.asList(

        "https://dummyimage.com/600x400/ff0000/000000.png",

        "https://dummyimage.com/600x400/ffffff/ff0000.png"

));

updatedProps.putStringArrayList("images", imageList);



mReactRootView.setAppProperties(updatedProps);
```

Kotlin

```
var updatedProps: Bundle = reactRootView.getAppProperties()

var imageList = arrayListOf("https://dummyimage.com/600x400/ff0000/000000.png", "https://dummyimage.com/600x400/ffffff/ff0000.png")
```

It is fine to update properties anytime. However, updates have to be performed on the main thread. You use the getter on any thread.

There is no way to update only a few properties at a time. We suggest that you build it into your own wrapper instead.

info

Currently, JS function `componentWillUpdateProps` of the top level RN component will not be called after a prop update. However, you can access the new props in `componentDidMount` function.

### Passing properties from React Native to native[​](#passing-properties-from-react-native-to-native "Direct link to Passing properties from React Native to native")

The problem exposing properties of native components is covered in detail in [this article](/docs/legacy/native-components-android#3-expose-view-property-setters-using-reactprop-or-reactpropgroup-annotation). In short, properties that are to be reflected in JavaScript needs to be exposed as setter method annotated with `@ReactProp`, then use them in React Native as if the component was an ordinary React Native component.

### Limits of properties[​](#limits-of-properties "Direct link to Limits of properties")

The main drawback of cross-language properties is that they do not support callbacks, which would allow us to handle bottom-up data bindings. Imagine you have a small RN view that you want to be removed from the native parent view as a result of a JS action. There is no way to do that with props, as the information would need to go bottom-up.

Although we have a flavor of cross-language callbacks ([described here](/docs/legacy/native-modules-android#callbacks)), these callbacks are not always the thing we need. The main problem is that they are not intended to be passed as properties. Rather, this mechanism allows us to trigger a native action from JS, and handle the result of that action in JS.

## Other ways of cross-language interaction (events and native modules)[​](#other-ways-of-cross-language-interaction-events-and-native-modules "Direct link to Other ways of cross-language interaction (events and native modules)")

As stated in the previous chapter, using properties comes with some limitations. Sometimes properties are not enough to drive the logic of our app and we need a solution that gives more flexibility. This chapter covers other communication techniques available in React Native. They can be used for internal communication (between JS and native layers in RN) as well as for external communication (between RN and the 'pure native' part of your app).

React Native enables you to perform cross-language function calls. You can execute custom native code from JS and vice versa. Unfortunately, depending on the side we are working on, we achieve the same goal in different ways. For native - we use events mechanism to schedule an execution of a handler function in JS, while for React Native we directly call methods exported by native modules.

### Calling React Native functions from native (events)[​](#calling-react-native-functions-from-native-events "Direct link to Calling React Native functions from native (events)")

Events are described in detail in [this article](/docs/legacy/native-components-android#events). Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread.

Events are powerful, because they allow us to change React Native components without needing a reference to them. However, there are some pitfalls that you can fall into while using them:

* As events can be sent from anywhere, they can introduce spaghetti-style dependencies into your project.
* Events share namespace, which means that you may encounter some name collisions. Collisions will not be detected statically, which makes them hard to debug.
* If you use several instances of the same React Native component and you want to distinguish them from the perspective of your event, you'll likely need to introduce identifiers and pass them along with events (you can use the native view's `reactTag` as an identifier).

### Calling native functions from React Native (native modules)[​](#calling-native-functions-from-react-native-native-modules "Direct link to Calling native functions from React Native (native modules)")

Native modules are Java/Kotlin classes that are available in JS. Typically one instance of each module is created per JS bridge. They can export arbitrary functions and constants to React Native. They have been covered in detail in [this article](/docs/legacy/native-modules-android).

----
url: https://reactnative.dev/docs/debugging-release-builds
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

## Symbolicating a stack trace[​](#symbolicating-a-stack-trace "Direct link to Symbolicating a stack trace")

If a React Native app throws an unhandled exception in a release build, the output may be obfuscated and hard to read.

```
07-15 10:58:25.820 18979 18998 E AndroidRuntime: FATAL EXCEPTION: mqt_native_modules

07-15 10:58:25.820 18979 18998 E AndroidRuntime: Process: com.awesomeproject, PID: 18979 07-15 10:58:25.820 18979 18998 E AndroidRuntime: com.facebook.react.common.JavascriptException: Failed, js engine: hermes, stack:

07-15 10:58:25.820 18979 18998 E AndroidRuntime: p@1:132161

07-15 10:58:25.820 18979 18998 E AndroidRuntime: p@1:132084

07-15 10:58:25.820 18979 18998 E AndroidRuntime: f@1:131854

07-15 10:58:25.820 18979 18998 E AndroidRuntime: anonymous@1:131119
```

```
react {

    hermesFlags = ["-O", "-output-source-map"]

}
```

If done correctly you should see the output location of the source map during Metro build output.

Text

```
Writing bundle output to:, android/app/build/generated/assets/react/release/index.android.bundle

Writing sourcemap output to:, android/app/build/intermediates/sourcemaps/react/release/index.android.bundle.packager.map
```

info

On iOS, source maps are **disabled** by default. Use the following instructions to enable them.

To enable source map generation:

* Open Xcode and edit the build phase "Bundle React Native code and images".
* Above the other exports, add a `SOURCEMAP_FILE` entry with the desired output path.

Diff

```
+ export SOURCEMAP_FILE="$(pwd)/../main.jsbundle.map"

  WITH_ENVIRONMENT="../node_modules/react-native/scripts/xcode/with-environment.sh"
```

If done correctly you should see the output location of the source map during Metro build output.

Text

```
Writing bundle output to:, Build/Intermediates.noindex/ArchiveIntermediates/application/BuildProductsPath/Release-iphoneos/main.jsbundle

Writing sourcemap output to:, Build/Intermediates.noindex/ArchiveIntermediates/application/BuildProductsPath/Release-iphoneos/main.jsbundle.map
```

### Using `metro-symbolicate`[​](#using-metro-symbolicate "Direct link to using-metro-symbolicate")

With source maps being generated, we can now translate our stack traces.

```
# Print usage instructions

npx metro-symbolicate



# From a file containing the stack trace

npx metro-symbolicate android/app/build/generated/sourcemaps/react/release/index.android.bundle.map < stacktrace.txt



# From adb logcat (Android)

adb logcat -d | npx metro-symbolicate android/app/build/generated/sourcemaps/react/release/index.android.bundle.map
```

----
url: https://reactnative.dev/docs/keyboardavoidingview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This component will automatically adjust its height, position, or bottom padding based on the keyboard height to remain visible while the virtual keyboard is displayed.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### `behavior`[​](#behavior "Direct link to behavior")

Specify how to react to the presence of the keyboard.

note

Android and iOS both interact with this prop differently. On both iOS and Android, setting `behavior` is recommended.

| Type                                        |
| ------------------------------------------- |
| enum(`'height'`, `'position'`, `'padding'`) |

***

### `contentContainerStyle`[​](#contentcontainerstyle "Direct link to contentcontainerstyle")

The style of the content container (View) when behavior is `'position'`.

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

***

### `enabled`[​](#enabled "Direct link to enabled")

Enabled or disabled KeyboardAvoidingView.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

***

### `keyboardVerticalOffset`[​](#keyboardverticaloffset "Direct link to keyboardverticaloffset")

This is the distance between the top of the user screen and the react native view, may be non-zero in some use cases.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

----
url: https://reactnative.dev/docs/global-Response
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Response) for more information.

The global `Response` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/integration-with-android-fragment
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/integration-with-android-fragment)** (0.87).

Version: Next

```
<FrameLayout

    android:id="@+id/react_native_fragment"

    android:layout_width="match_parent"

    android:layout_height="match_parent" />
```

```
package <your-package-here>



import android.os.Bundle

import androidx.appcompat.app.AppCompatActivity

+import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler



+class MainActivity : AppCompatActivity() {

+class MainActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler {



    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.main_activity)



        findViewById<Button>(R.id.sample_button).setOnClickListener {

            // Handle button click

        }

    }



+   override fun invokeDefaultOnBackPressed() {

+       onBackPressedDispatcher.onBackPressed()

+   }

}
```

Diff

```
package <your-package-here>;



import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

+import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;



-class MainActivity extends AppCompatActivity {

+class MainActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {



    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity);



        findViewById(R.id.button_appcompose).setOnClickListener(button -> {

            // Handle button click

        });

    }



+   @Override

+   public void invokeDefaultOnBackPressed() {

+       getOnBackPressedDispatcher().onBackPressed();

+   }

}
```

### 4. Add a React Native Fragment to the FrameLayout[​](#4-add-a-react-native-fragment-to-the-framelayout "Direct link to 4. Add a React Native Fragment to the FrameLayout")

Finally, we can update the Activity to add a React Native Fragment to the FrameLayout. In this specific example, we're going to assume that your Activity has a button with id `sample_button` that when clicked will render a React Native Fragment into the FrameLayout.

Update your Activity's `onCreate` method as follows:

* Java
* Kotlin

Diff

```
package <your-package-here>



import android.os.Bundle

import androidx.appcompat.app.AppCompatActivity

+import com.facebook.react.ReactFragment

import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler



public class MainActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler {



    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.main_activity)



        findViewById<Button>(R.id.sample_button).setOnClickListener {

+           val reactNativeFragment = ReactFragment.Builder()

+               .setComponentName("HelloWorld")

+               .setLaunchOptions(Bundle().apply { putString("message", "my value") })

+               .build()

+           supportFragmentManager

+               .beginTransaction()

+               .add(R.id.react_native_fragment, reactNativeFragment)

+               .commit()

        }

    }



   override fun invokeDefaultOnBackPressed() {

       super.onBackPressed()

   }

}
```

Diff

```
package <your-package-here>;



import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

+import com.facebook.react.ReactFragment;

import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;



public class MainActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {



    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity);



        findViewById(R.id.button_appcompose).setOnClickListener(button -> {

+           Bundle launchOptions = new Bundle();

+           launchOptions.putString("message", "my value");

+

+           ReactFragment fragment = new ReactFragment.Builder()

+                   .setComponentName("HelloWorld")

+                   .setLaunchOptions(launchOptions)

+                   .build();

+           getSupportFragmentManager()

+                   .beginTransaction()

+                   .add(R.id.react_native_fragment, fragment)

+                   .commit();

        });

    }



    @Override

    public void invokeDefaultOnBackPressed() {

        super.onBackPressed();

    }

}
```

----
url: https://reactnative.dev/docs/next/touchablenativefeedback
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/touchablenativefeedback)** (0.87).

Version: Next

tip

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the [Pressable](/docs/next/pressable) API.

A wrapper for making views respond properly to touches (Android only). On Android this component uses native state drawable to display touch feedback.

At the moment it only supports having a single View instance as a child node, as it's implemented by replacing that View with another instance of RCTView node with some additional properties set.

Background drawable of native feedback touchable can be customized with `background` property.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [TouchableWithoutFeedback Props](/docs/next/touchablewithoutfeedback#props)[​](#touchablewithoutfeedback-props "Direct link to touchablewithoutfeedback-props")

Inherits [TouchableWithoutFeedback Props](/docs/next/touchablewithoutfeedback#props).

***

### `background`[​](#background "Direct link to background")

Determines the type of background drawable that's going to be used to display feedback. It takes an object with `type` property and extra data depending on the `type`. It's recommended to use one of the static methods to generate that dictionary.

| Type               |
| ------------------ |
| backgroundPropType |

***

### `useForeground`[​](#useforeground "Direct link to useforeground")

Set to true to add the ripple effect to the foreground of the view, instead of the background. This is useful if one of your child views has a background of its own, or you're e.g. displaying images, and you don't want the ripple to be covered by them.

Check TouchableNativeFeedback.canUseNativeForeground() first, as this is only available on Android 6.0 and above. If you try to use this on older versions you will get a warning and fallback to background.

| Type |
| ---- |
| bool |

***

### `hasTVPreferredFocus`Android[​](#hastvpreferredfocus-android "Direct link to hastvpreferredfocus-android")

TV preferred focus (see documentation for the View component).

| Type |
| ---- |
| bool |

***

### `nextFocusDown`Android[​](#nextfocusdown-android "Direct link to nextfocusdown-android")

TV next focus down (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`Android[​](#nextfocusforward-android "Direct link to nextfocusforward-android")

TV next focus forward (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`Android[​](#nextfocusleft-android "Direct link to nextfocusleft-android")

TV next focus left (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`Android[​](#nextfocusright-android "Direct link to nextfocusright-android")

TV next focus right (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`Android[​](#nextfocusup-android "Direct link to nextfocusup-android")

TV next focus up (see documentation for the View component).

| Type   |
| ------ |
| number |

## Methods[​](#methods "Direct link to Methods")

### `SelectableBackground()`[​](#selectablebackground "Direct link to selectablebackground")

React TSX

```
static SelectableBackground(

  rippleRadius: number | null,

): ThemeAttributeBackgroundPropType;
```

Creates an object that represents android theme's default background for selectable elements (`?android:attr/selectableItemBackground`). `rippleRadius` parameter controls the radius of the ripple effect.

***

### `SelectableBackgroundBorderless()`[​](#selectablebackgroundborderless "Direct link to selectablebackgroundborderless")

React TSX

```
static SelectableBackgroundBorderless(

  rippleRadius: number | null,

): ThemeAttributeBackgroundPropType;
```

Creates an object that represent android theme's default background for borderless selectable elements (`?android:attr/selectableItemBackgroundBorderless`). Available on android API level 21+. `rippleRadius` parameter controls the radius of the ripple effect.

***

### `Ripple()`[​](#ripple "Direct link to ripple")

React TSX

```
static Ripple(

  color: ColorValue,

  borderless: boolean,

  rippleRadius?: number | null,

): RippleBackgroundPropType;
```

Creates an object that represents ripple drawable with specified color (as a string). If property `borderless` evaluates to true the ripple will render outside of the view bounds (see native actionbar buttons as an example of that behavior). This background type is available on Android API level 21+.

**Parameters:**

| Name         | Type    | Required | Description                                 |
| ------------ | ------- | -------- | ------------------------------------------- |
| color        | string  | Yes      | The ripple color                            |
| borderless   | boolean | Yes      | If the ripple can render outside its bounds |
| rippleRadius | ?number | No       | controls the radius of the ripple effect    |

***

### `canUseNativeForeground()`[​](#canusenativeforeground "Direct link to canusenativeforeground")

React TSX

```
static canUseNativeForeground(): boolean;
```

* [Example](#example)

* [Props](#props)

  * [TouchableWithoutFeedback Props](#touchablewithoutfeedback-props)
  * [`background`](#background)
  * [`useForeground`](#useforeground)
  * [`hasTVPreferredFocus`](#hastvpreferredfocus-android)

    [Android](#hastvpreferredfocus-android)
  * [`nextFocusDown`](#nextfocusdown-android)

    [Android](#nextfocusdown-android)
  * [`nextFocusForward`](#nextfocusforward-android)

    [Android](#nextfocusforward-android)
  * [`nextFocusLeft`](#nextfocusleft-android)

    [Android](#nextfocusleft-android)
  * [`nextFocusRight`](#nextfocusright-android)

    [Android](#nextfocusright-android)
  * [`nextFocusUp`](#nextfocusup-android)

    [Android](#nextfocusup-android)

* [Methods](#methods)

  * [`SelectableBackground()`](#selectablebackground)
  * [`SelectableBackgroundBorderless()`](#selectablebackgroundborderless)
  * [`Ripple()`](#ripple)
  * [`canUseNativeForeground()`](#canusenativeforeground)

----
url: https://reactnative.dev/docs/segmentedcontrolios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=segmentedcontrol) instead.

***

----
url: https://reactnative.dev/docs/next/global-PerformanceEventTiming
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-PerformanceEventTiming)** (0.87).

Version: Next

The global [`PerformanceEventTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEventTiming) class, as defined in Web specifications.

Partial support

The `cancelable` and `target` properties are not supported yet.

----
url: https://reactnative.dev/docs/next/dynamiccolorios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/dynamiccolorios)** (0.87).

Version: Next

The `DynamicColorIOS` function is a platform color type specific to iOS.

React TSX

```
DynamicColorIOS({

  light: color,

  dark: color,

  highContrastLight: color, // (optional) will fallback to "light" if not provided

  highContrastDark: color, // (optional) will fallback to "dark" if not provided

});
```

```
import {DynamicColorIOS} from 'react-native';



const customDynamicTextColor = DynamicColorIOS({

  dark: 'lightskyblue',

  light: 'midnightblue',

});



const customContrastDynamicTextColor = DynamicColorIOS({

  dark: 'darkgray',

  light: 'lightgray',

  highContrastDark: 'black',

  highContrastLight: 'white',

});
```

* [Example](#example)

----
url: https://reactnative.dev/docs/next/components-and-apis
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/components-and-apis)** (0.87).

Version: Next

React Native provides a number of built-in [Core Components](/docs/next/intro-react-native-components) ready for you to use in your app. You can find them all in the left sidebar (or menu above, if you are on a narrow screen). If you're not sure where to get started, take a look at the following categories:

* [Basic Components](/docs/next/components-and-apis#basic-components)
* [User Interface](/docs/next/components-and-apis#user-interface)
* [List Views](/docs/next/components-and-apis#list-views)
* [Android-specific](/docs/next/components-and-apis#android-components-and-apis)
* [iOS-specific](/docs/next/components-and-apis#ios-components-and-apis)
* [Others](/docs/next/components-and-apis#others)

You're not limited to the components and APIs bundled with React Native. React Native has a community of thousands of developers. If you're looking for a library that does something specific, please refer to [this guide about finding libraries](/docs/next/libraries#finding-libraries).

Unlike the more generic [`ScrollView`](/docs/next/scrollview), the following list view components only render elements that are currently showing on the screen. This makes them a performant choice for displaying long lists of data.

----
url: https://reactnative.dev/docs/next/flatlist
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/flatlist)** (0.87).

Version: Next

If you need section support, use [`<SectionList>`](/docs/next/sectionlist).

## Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

To render multiple columns, use the [`numColumns`](/docs/next/flatlist#numcolumns) prop. Using this approach instead of a `flexWrap` layout can prevent conflicts with the item height logic.

More complex, selectable example below.

* Passing `extraData={selectedId}` to `FlatList` ensures that `FlatList` re-renders when `selectedId` changes. Because `FlatList` implements `PureComponent`, it only re-renders if its props change. While `renderItem` in this example is recreated on each render because it is defined inline, passing `extraData` is essential whenever `renderItem` has a stable reference (such as when memoized or defined outside the component) so that `FlatList` knows that an external dependency has updated.
* `keyExtractor` tells the list to use the `id`s for the react keys instead of the default `key` property.

- TypeScript
- JavaScript

This is a convenience wrapper around [`<VirtualizedList>`](/docs/next/virtualizedlist), and thus inherits its props (as well as those of [`<ScrollView>`](/docs/next/scrollview)) that aren't explicitly listed here, along with the following caveats:

* Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
* This is a `PureComponent` which means that it will not re-render if `props` remain shallow-equal. Make sure that everything your `renderItem` function depends on is passed as a prop (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on changes. This includes the `data` prop and parent component state.
* In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
* By default, the list looks for a `key` prop on each item and uses that for the React key. Alternatively, you can provide a custom `keyExtractor` prop.

***

# Reference

## Props[​](#props "Direct link to Props")

### [VirtualizedList Props](/docs/next/virtualizedlist#props)[​](#virtualizedlist-props "Direct link to virtualizedlist-props")

Inherits [VirtualizedList Props](/docs/next/virtualizedlist#props).

***

### Require&#x64;**`renderItem`**[​](#required-renderitem "Direct link to required-renderitem")

React TSX

```
renderItem({

  item: ItemT,

  index: number,

  separators: {

    highlight: () => void;

    unhighlight: () => void;

    updateProps: (select: 'leading' | 'trailing', newProps: any) => void;

  }

}): JSX.Element;
```

Takes an item from `data` and renders it into the list.

Provides additional metadata like `index` if you need it, as well as a more generic `separators.updateProps` function which let you set whatever props you want to change the rendering of either the leading separator or trailing separator in case the more common `highlight` and `unhighlight` (which set the `highlighted: boolean` prop) are insufficient for your use case.

| Type     |
| -------- |
| function |

* `item` (Object): The item from `data` being rendered.

* `index` (number): The index corresponding to this item in the `data` array.

* `separators` (Object)

  * `highlight` (Function)

  * `unhighlight` (Function)

  * `updateProps` (Function)

    * `select` (enum('leading', 'trailing'))
    * `newProps` (Object)

Example usage:

React TSX

```
<FlatList

  ItemSeparatorComponent={

    Platform.OS !== 'android' &&

    (({highlighted}) => (

      <View

        style={[style.separator, highlighted && {marginLeft: 0}]}

      />

    ))

  }

  data={[{title: 'Title Text', key: 'item1'}]}

  renderItem={({item, index, separators}) => (

    <TouchableHighlight

      key={item.key}

      onPress={() => this._onPress(item)}

      onShowUnderlay={separators.highlight}

      onHideUnderlay={separators.unhighlight}>

      <View style={{backgroundColor: 'white'}}>

        <Text>{item.title}</Text>

      </View>

    </TouchableHighlight>

  )}

/>
```

***

### Require&#x64;**`data`**[​](#required-data "Direct link to required-data")

An array (or array-like list) of items to render. Other data types can be used by targeting [`VirtualizedList`](/docs/next/virtualizedlist) directly.

| Type      |
| --------- |
| ArrayLike |

***

### `ItemSeparatorComponent`[​](#itemseparatorcomponent "Direct link to itemseparatorcomponent")

Rendered in between each item, but not at the top or bottom. By default, `highlighted` and `leadingItem` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` which will update the `highlighted` prop, but you can also add custom props with `separators.updateProps`. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type                         |
| ---------------------------- |
| component, function, element |

***

### `ListEmptyComponent`[​](#listemptycomponent "Direct link to listemptycomponent")

Rendered when the list is empty. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListFooterComponent`[​](#listfootercomponent "Direct link to listfootercomponent")

Rendered at the bottom of all the items. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListFooterComponentStyle`[​](#listfootercomponentstyle "Direct link to listfootercomponentstyle")

Styling for internal View for `ListFooterComponent`.

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

***

### `ListHeaderComponent`[​](#listheadercomponent "Direct link to listheadercomponent")

Rendered at the top of all the items. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListHeaderComponentStyle`[​](#listheadercomponentstyle "Direct link to listheadercomponentstyle")

Styling for internal View for `ListHeaderComponent`.

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

***

### `ListItemComponent`[​](#listitemcomponent "Direct link to listitemcomponent")

Each data item is rendered using this element, as an alternative to `renderItem`. It receives the same props, and takes precedence over `renderItem` when both are provided.

| Type               |
| ------------------ |
| component, element |

***

### `columnWrapperStyle`[​](#columnwrapperstyle "Direct link to columnwrapperstyle")

Optional custom style for multi-item rows generated when `numColumns > 1`.

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

***

### `extraData`[​](#extradata "Direct link to extradata")

A marker property for telling the list to re-render (since it implements `PureComponent`). If any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the `data` prop, stick it here and treat it immutably.

| Type |
| ---- |
| any  |

***

### `getItemLayout`[​](#getitemlayout "Direct link to getitemlayout")

React 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:

React TSX

```
  getItemLayout={(data, index) => (

    {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}

  )}
```

Adding `getItemLayout` can be a great performance boost for lists of several hundred items. Remember to include separator length (height or width) in your offset calculation if you specify `ItemSeparatorComponent`.

| Type     |
| -------- |
| function |

***

### `horizontal`[​](#horizontal "Direct link to horizontal")

If `true`, renders items next to each other horizontally instead of stacked vertically.

| Type    |
| ------- |
| boolean |

***

### `initialNumToRender`[​](#initialnumtorender "Direct link to initialnumtorender")

How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.

| Type   | Default |
| ------ | ------- |
| number | `10`    |

***

### `initialScrollIndex`[​](#initialscrollindex "Direct link to initialscrollindex")

Instead of starting at the top with the first item, start at `initialScrollIndex`. This disables the "scroll to top" optimization that keeps the first `initialNumToRender` items always rendered and immediately renders the items starting at this initial index. Requires `getItemLayout` to be implemented.

| Type   |
| ------ |
| number |

***

### `inverted`[​](#inverted "Direct link to inverted")

Reverses the direction of scroll. Uses scale transforms of `-1`.

| Type    |
| ------- |
| boolean |

***

### `keyExtractor`[​](#keyextractor "Direct link to keyextractor")

React TSX

```
(item: ItemT, index: number) => string;
```

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks `item.key`, then `item.id`, and then falls back to using the index, like React does.

| Type     |
| -------- |
| function |

***

### `numColumns`[​](#numcolumns "Direct link to numcolumns")

Multiple columns can only be rendered with `horizontal={false}` and will zig-zag like a `flexWrap` layout. Items should all be the same height - masonry layouts are not supported.

| Type   |
| ------ |
| number |

***

### `onRefresh`[​](#onrefresh "Direct link to onrefresh")

React TSX

```
() => void;
```

If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the `refreshing` prop correctly.

| Type     |
| -------- |
| function |

***

### `onViewableItemsChanged`[​](#onviewableitemschanged "Direct link to onviewableitemschanged")

Called when the viewability of rows changes, as defined by the `viewabilityConfig` prop.

| Type                                                                     |
| ------------------------------------------------------------------------ |
| `(callback: {changed: ViewToken[], viewableItems: ViewToken[]} => void;` |

***

### `progressViewOffset`[​](#progressviewoffset "Direct link to progressviewoffset")

Set this when offset is needed for the loading indicator to show correctly.

| Type   |
| ------ |
| number |

***

### `refreshing`[​](#refreshing "Direct link to refreshing")

Set this true while waiting for new data from a refresh.

| Type    |
| ------- |
| boolean |

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

warning

Using this property may lead to bugs (missing content) in some circumstances - use at your own risk.

When `true`, offscreen child views are removed from their native backing superview when offscreen. This may improve scroll performance for large lists. On Android the default value is `true`.

| Type    |
| ------- |
| boolean |

***

### `viewabilityConfig`[​](#viewabilityconfig "Direct link to viewabilityconfig")

See [`ViewabilityHelper.js`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Lists/ViewabilityHelper.js) for flow type and further documentation.

| Type              |
| ----------------- |
| ViewabilityConfig |

`viewabilityConfig` takes a type `ViewabilityConfig` an object with following properties

| Property                         | Type    |
| -------------------------------- | ------- |
| minimumViewTime                  | number  |
| viewAreaCoveragePercentThreshold | number  |
| itemVisiblePercentThreshold      | number  |
| waitForInteraction               | boolean |

At least one of the `viewAreaCoveragePercentThreshold` or `itemVisiblePercentThreshold` is required. This needs to be done in the `constructor` to avoid following error ([ref](https://github.com/react/react-native/issues/17408)):

```
  Error: Changing viewabilityConfig on the fly is not supported
```

React TSX

```
constructor (props) {

  super(props)



  this.viewabilityConfig = {

      waitForInteraction: true,

      viewAreaCoveragePercentThreshold: 95

  }

}
```

React TSX

```
<FlatList

    viewabilityConfig={this.viewabilityConfig}

  ...
```

***

### `viewabilityConfigCallbackPairs`[​](#viewabilityconfigcallbackpairs "Direct link to viewabilityconfigcallbackpairs")

List of `ViewabilityConfig`/`onViewableItemsChanged` pairs. A specific `onViewableItemsChanged` will be called when its corresponding `ViewabilityConfig`'s conditions are met. See `ViewabilityHelper.js` for flow type and further documentation.

| Type                                   |
| -------------------------------------- |
| array of ViewabilityConfigCallbackPair |

## Methods[​](#methods "Direct link to Methods")

### `flashScrollIndicators()`[​](#flashscrollindicators "Direct link to flashscrollindicators")

React TSX

```
flashScrollIndicators();
```

Displays the scroll indicators momentarily.

***

### `getNativeScrollRef()`[​](#getnativescrollref "Direct link to getnativescrollref")

React TSX

```
getNativeScrollRef(): React.ElementRef<typeof ScrollViewComponent>;
```

Provides a reference to the underlying scroll component

***

### `getScrollResponder()`[​](#getscrollresponder "Direct link to getscrollresponder")

React TSX

```
getScrollResponder(): ScrollResponderMixin;
```

Provides a handle to the underlying scroll responder.

***

### `getScrollableNode()`[​](#getscrollablenode "Direct link to getscrollablenode")

React TSX

```
getScrollableNode(): any;
```

Provides a handle to the underlying scroll node.

### `scrollToEnd()`[​](#scrolltoend "Direct link to scrolltoend")

React TSX

```
scrollToEnd(params?: {animated?: boolean});
```

Scrolls to the end of the content. May be janky without `getItemLayout` prop.

**Parameters:**

| Name   | Type   |
| ------ | ------ |
| params | object |

Valid `params` keys are:

* 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to `true`.

***

### `scrollToIndex()`[​](#scrolltoindex "Direct link to scrolltoindex")

React TSX

```
scrollToIndex: (params: {

  index: number;

  animated?: boolean;

  viewOffset?: number;

  viewPosition?: number;

});
```

Scrolls to the item at the specified index such that it is positioned in the viewable area such that `viewPosition` 0 places it at the top, 1 at the bottom, and 0.5 centered in the middle.

note

Cannot scroll to locations outside the render window without specifying the `getItemLayout` prop.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| paramsRequired | object |

Valid `params` keys are:

* 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to `true`.
* 'index' (number) - The index to scroll to. Required.
* 'viewOffset' (number) - A fixed number of pixels to offset the final target position.
* 'viewPosition' (number) - A value of `0` places the item specified by index at the top, `1` at the bottom, and `0.5` centered in the middle.

***

### `scrollToItem()`[​](#scrolltoitem "Direct link to scrolltoitem")

React TSX

```
scrollToItem(params: {

  animated?: ?boolean,

  item: Item,

  viewPosition?: number,

});
```

Requires linear scan through data - use `scrollToIndex` instead if possible.

note

Cannot scroll to locations outside the render window without specifying the `getItemLayout` prop.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| paramsRequired | object |

Valid `params` keys are:

* 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to `true`.
* 'item' (object) - The item to scroll to. Required.
* 'viewPosition' (number)

***

### `scrollToOffset()`[​](#scrolltooffset "Direct link to scrolltooffset")

React TSX

```
scrollToOffset(params: {

  offset: number;

  animated?: boolean;

});
```

Scroll to a specific content pixel offset in the list.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| paramsRequired | object |

    [**`renderItem`**](#required-renderitem)
  * [Required](#required-data)

    [**`data`**](#required-data)
  * [`ItemSeparatorComponent`](#itemseparatorcomponent)
  * [`ListEmptyComponent`](#listemptycomponent)
  * [`ListFooterComponent`](#listfootercomponent)
  * [`ListFooterComponentStyle`](#listfootercomponentstyle)
  * [`ListHeaderComponent`](#listheadercomponent)
  * [`ListHeaderComponentStyle`](#listheadercomponentstyle)
  * [`ListItemComponent`](#listitemcomponent)

----
url: https://reactnative.dev/docs/next/images
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/images)** (0.87).

Version: Next

## Static Image Resources[​](#static-image-resources "Direct link to Static Image Resources")

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:

React TSX

```
<Image source={require('./my-icon.png')} />
```

The image name is resolved the same way JS modules are resolved. In the example above, the bundler will look for `my-icon.png` in the same folder as the component that requires it.

You can use the `@2x` and `@3x` suffixes to provide images for different screen densities. If you have the following file structure:

```
.

├── button.js

└── img

    ├── check.png

    ├── check@2x.png

    └── check@3x.png
```

...and `button.js` code contains:

React TSX

```
<Image source={require('./img/check.png')} />
```

```
// GOOD

<Image source={require('./my-icon.png')} />;



// BAD

const icon = this.props.active

  ? 'my-icon-active'

  : 'my-icon-inactive';

<Image source={require('./' + icon + '.png')} />;



// GOOD

const icon = this.props.active

  ? require('./my-icon-active.png')

  : require('./my-icon-inactive.png');

<Image source={icon} />;
```

Note that image sources required this way include size (width, height) info for the Image. If you need to scale the image dynamically (i.e. via flex), you may need to manually set `{width: undefined, height: undefined}` on the style attribute.

### Bundling images in an asset catalog (iOS)[​](#bundling-images-in-an-asset-catalog-ios "Direct link to Bundling images in an asset catalog (iOS)")

By default the bundler copies each required image, along with every `@2x` and `@3x` variant, into your iOS app as a loose file next to the JavaScript bundle. On iOS you can instead have them compiled into an [asset catalog](https://developer.apple.com/documentation/xcode/managing-assets-with-asset-catalogs), so the system ships only the scale a device needs.

To opt in, set the `RCTUseAssetCatalog` key to `true` in your app's `Info.plist`:

XML

```
<key>RCTUseAssetCatalog</key>

<true/>
```

```
<Image

  source={{uri: 'app_icon'}}

  style={{width: 40, height: 40}}

/>
```

For images in the Android assets folder, use the `asset:/` scheme:

React TSX

```
<Image

  source={{uri: 'asset:/app_icon.png'}}

  style={{width: 40, height: 40}}

/>
```

These approaches provide no safety checks. It's up to you to guarantee that those images are available in the application. Also you have to specify image dimensions manually.

## Network Images[​](#network-images "Direct link to Network Images")

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](https://developer.apple.com/documentation/security/preventing_insecure_network_connections) requirements on iOS.

React TSX

```
// GOOD

<Image source={{uri: 'https://reactjs.org/logo-og.png'}}

       style={{width: 400, height: 400}} />



// BAD

<Image source={{uri: 'https://reactjs.org/logo-og.png'}} />
```

### Network Requests for Images[​](#network-requests-for-images "Direct link to Network Requests for Images")

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:

React TSX

```
<Image

  source={{

    uri: 'https://reactjs.org/logo-og.png',

    method: 'POST',

    headers: {

      Pragma: 'no-cache',

    },

    body: 'Your Body goes here',

  }}

  style={{width: 400, height: 400}}

/>
```

## URI Data Images[​](#uri-data-images "Direct link to URI Data Images")

Sometimes, you might be getting encoded image data from a REST API call. You can use the `'data:'` URI scheme to use these images. Same as for network resources, *you will need to manually specify the dimensions of your image*.

info

This is recommended for very small and dynamic images only, like icons in a list from a DB.

React TSX

```
// include at least width and height!

<Image

  style={{

    width: 51,

    height: 51,

    resizeMode: 'contain',

  }}

  source={{

    uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',

  }}

/>
```

```
<Image

  source={{

    uri: 'https://reactjs.org/logo-og.png',

    cache: 'only-if-cached',

  }}

  style={{width: 400, height: 400}}

/>
```

## Local Filesystem Images[​](#local-filesystem-images "Direct link to Local Filesystem Images")

See [CameraRoll](https://github.com/react-native-community/react-native-cameraroll) for an example of using local resources that are outside of `Images.xcassets`.

### Drawable resources[​](#drawable-resources "Direct link to Drawable resources")

Android supports loading [drawable resources](https://developer.android.com/guide/topics/resources/drawable-resource) via the `xml` file type. This means you can use [vector drawables](https://developer.android.com/develop/ui/views/graphics/vector-drawable-resources) for rendering icons or [shape drawables](https://developer.android.com/guide/topics/resources/drawable-resource#Shape) for, well, drawing shapes! You can import and use these resource types the same as any other [static resource](#static-image-resources) or [hybrid resource](#images-from-hybrid-apps-resources). 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):

React TSX

```
<Image

  source={require('./img/my_icon.xml')}

  style={{width: 40, height: 40}}

/>
```

For drawables included in the Android drawable folder (i.e. `res/drawable`), use the resource name without the extension:

React TSX

```
<Image

  source={{uri: 'my_icon'}}

  style={{width: 40, height: 40}}

/>
```

```
{"__packager_asset":true,"uri":"my-icon.png","width":591,"height":573}
```

## Source as an object[​](#source-as-an-object "Direct link to Source as an object")

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.

React TSX

```
<Image source={{uri: 'something.jpg'}} />
```

On the infrastructure side, the reason is that it allows us to attach metadata to this object. For example if you are using `require('./my-icon.png')`, then we add information about its actual location and size (don't rely on this fact, it might change in the future!). This is also future proofing, for example we may want to support sprites at some point, instead of outputting `{uri: ...}`, we can output `{uri: ..., crop: {left: 10, top: 50, width: 20, height: 40}}` and transparently support spriting on all the existing call sites.

On the user side, this lets you annotate the object with useful attributes such as the dimension of the image in order to compute the size it's going to be displayed in. Feel free to use it as your data structure to store more information about your image.

## Background Image via Nesting[​](#background-image-via-nesting "Direct link to Background Image via Nesting")

To layer content over an image, render an absolutely positioned [`Image`](/docs/next/image) inside a [`View`](/docs/next/view), followed by the content that should appear on top.

React TSX

```
return (

  <View style={{width: '100%', height: '100%'}}>

    <Image source={...} style={StyleSheet.absoluteFill} />

    <Text>Inside</Text>

  </View>

);
```

On iOS, we expose an API to override React Native's default image cache limits. Call this early during app startup from your `SceneDelegate` (in `scene:willConnectToSession:options:`) or from `AppDelegate` if you are not using the UIScene lifecycle (for example, within `application:didFinishLaunchingWithOptions:`).

Objective-C

```
RCTSetImageCacheLimits(4*1024*1024, 200*1024*1024);
```

**Parameters:**

| Name           | Type   | Required | Description             |
| -------------- | ------ | -------- | ----------------------- |
| imageSizeLimit | number | Yes      | Image cache size limit. |
| totalCostLimit | number | Yes      | Total cache cost limit. |

----
url: https://reactnative.dev/docs/handling-text-input
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

[`TextInput`](/docs/textinput) is a [Core Component](/docs/intro-react-native-components) that allows the user to enter text. It has an `onChangeText` prop that takes a function to be called every time the text changed, and an `onSubmitEditing` prop that takes a function to be called when the text is submitted.

For example, let's say that as the user types, you're translating their words into a different language. In this new language, every single word is written the same way: 🍕. So the sentence "Hello there Bob" would be translated as "🍕 🍕 🍕".

In this example, we store `text` in the state, because it changes over time.

There are a lot more things you might want to do with a text input. For example, you could validate the text inside while the user types. For more detailed examples, see the [React docs on controlled components](https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable), or the [reference docs for TextInput](/docs/textinput).

A `TextInput` is one of many ways for the user to interact with your app. For examples of other ways to handle input, see the documentation on [how to handle touches](/docs/handling-touches).

Now, let's take a look at [ScrollView](/docs/using-a-scrollview), another Core Component.

----
url: https://reactnative.dev/docs/next/virtualview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/virtualview)** (0.87).

Version: Next

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

`VirtualView` is a core component that behaves similar to [`View`](/docs/next/view).

When it is the descendent of a [`ScrollView`](/docs/next/scrollview), it gains additional virtualization capabilities to reduce its memory footprint when obscured by the scroll viewport.

React TSX

```
<ScrollView>

  <VirtualView>

    <Text>Hello world!</Text>

  </VirtualView>

</ScrollView>
```

A `VirtualView` without an ancestor[`ScrollView`](/docs/next/scrollview) does not have any virtualization capabilities.

## Virtualization[​](#virtualization "Direct link to Virtualization")

When a `VirtualView` leaves the visible region of a [`ScrollView`](/docs/next/scrollview), it becomes hidden. When hidden, a `VirtualView` will cache its most recent layout and may unmount its children — a process called virtualization.

When a `VirtualView` returns to the visible region of a [`ScrollView`](/docs/next/scrollview), it becomes visible. When visible, its children are *guaranteed* to be rendered. This guarantee is maintained by blocking the main thread from rendering the next frame that would reveal the `VirtualView` until its children can be rendered.

note

In future developments, a hidden `VirtualView` may instead render its children in an [`<Activity mode="hidden">`](https://react.dev/reference/react/Activity) to preserve state for as long as possible while balancing memory overhead.

### Blocking the Main Thread[​](#blocking-the-main-thread "Direct link to Blocking the Main Thread")

This is the first time in React Native’s feature set where rendering a React component can block the main thread. This is a new capability enabled by the [New Architecture](/architecture/landing-page)!

Blocking the main thread can provide a better user experience by preventing flashes of blank frames that sometimes occur when using components like [`FlatList`](/docs/next/flatlist). It can also enable better performance by using main thread priority, which is also typically run on higher performance cores.

However, blocking the main thread also comes with tradeoffs. If an update operation, such as mounting the children of a `VirtualView`, takes too long to finish, it can now drop frames. Dropping more than a couple frames can lead to a worse user experience by making the app feel sluggish and non-responsive. Dropping too many frames may cause the operating system to display a modal indicating the app is not responsive, or it may even terminate your app!

warning

DevTools does not currently support debugging JavaScript on the main thread. This means if you are using breakpoints to debug code called from `onModeChange`, that is executed on the main thread, your debugger may freeze.

Debugging all other parts of your JavaScript code should work as expected. We are working on closing this gap before releasing `VirtualView` to stable channels of React Native.

### Prerendering[​](#prerendering "Direct link to Prerendering")

`VirtualView` enables you to benefit from main thread rendering while mitigating the disadvantages of dropped frames by rendering earlier before it is needed. This is called “prerendering”.

By default, each `VirtualView` will prerender its children when it approaches the visible region of a [`ScrollView`](/docs/next/scrollview). When this happens, its children will be rendered on a background thread at a lower priority (using a [transition](https://react.dev/reference/react/startTransition)). This ensures that the main thread and React are available to handle other critical user interactions at a higher priority.

note

`VirtualView`'s prerender logic is not currently configurable. The algorithm for determining this is undergoing active design iteration and is likely to change in a future release.

***

## Props[​](#props "Direct link to Props")

### `children`[​](#children "Direct link to children")

Content to render inside this `VirtualView`.

| Type                                |
| ----------------------------------- |
| [React Node](/docs/next/react-node) |

***

### `onModeChange`[​](#onmodechange "Direct link to onmodechange")

Invoked when the `VirtualView` changes how it renders its children.

If a callback is supplied, it may be invoked from different threads and priorities depending on the internal state change. This can be detected by checking the `mode` property on the event:

* If `mode` is [`VirtualViewMode.Visible`](#virtualviewmode), the callback is being invoked from the main thread with immediate priority.
* If `mode` is [`VirtualViewMode.Prerender`](#virtualviewmode) or [`VirtualViewMode.Hidden`](#virtualviewmode), the callback is being invoked from a background thread with transition priority.

The callback will never be invoked consecutively with the same `mode` value. However, there are few guarantees about sequencing of events. Also, the callback may never be invoked with [`VirtualViewMode.Visible`](#virtualviewmode) even if it becomes visible, if the children were successfully prerendered.

| Type                        |
| --------------------------- |
| `(ModeChangeEvent) => void` |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

An identifier for locating this view from native classes.

| Type   |
| ------ |
| string |

***

### `style`[​](#style "Direct link to style")

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

***

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### `ModeChangeEvent`[​](#modechangeevent "Direct link to modechangeevent")

Argument supplied to [`onModeChange`](#onmodechange).

| Type   |
| ------ |
| object |

**Properties:**

| Name          | Type                                | Description                                                                                       |
| ------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------- |
| mode          | [VirtualViewMode](#virtualviewmode) | New mode of the `VirtualView`.                                                                    |
| target        | element                             | `VirtualView` emitting this event.                                                                |
| targetRect    | [Rect](/docs/next/rect)             | Layout of `target` relative to the nearest ancestor `ScrollView`.                                 |
| thresholdRect | [Rect](/docs/next/rect)             | Layout of the threshold that triggered this event, relative to the nearest ancestor `ScrollView`. |

note

For example, if a `VirtualView` enters the visible region of a [`ScrollView`](/docs/next/scrollview)...

* `mode` would be [`VirtualViewMode.Visible`](#virtualviewmode)
* `thresholdRect` would describe the visible viewport of the nearest ancestor [`ScrollView`](/docs/next/scrollview)
* `targetRect` would be the layout of `target` that overlaps with `thresholdRect` (i.e. it is within the visible region of the [`ScrollView`](/docs/next/scrollview))

### `VirtualViewMode`[​](#virtualviewmode "Direct link to virtualviewmode")

Possible modes of a `VirtualView`.

| Name      | Value | Description                                    |
| --------- | ----- | ---------------------------------------------- |
| Visible   | `0`   | Target view is visible.                        |
| Prerender | `1`   | Target view is hidden, but can be prerendered. |
| Hidden    | `2`   | Target view is hidden.                         |

***

## Static Methods[​](#static-methods "Direct link to Static Methods")

### `createHiddenVirtualView()`[​](#createhiddenvirtualview "Direct link to createhiddenvirtualview")

React TSX

```
static createHiddenVirtualView(height: number): typeof VirtualView;
```

`VirtualView` initially renders its children as visible, even if it is initially obscured by an ancestor [`ScrollView`](/docs/next/scrollview). This is because when a component is initially rendered, the presence of an ancestor [`ScrollView`](/docs/next/scrollview) — let alone its size and scroll position — are unknown.

For advanced use cases, `createHiddenVirtualView()` creates a component that renders an initially hidden `VirtualView` with the supplied estimated layout.

React TSX

```
const HiddenVirtualView = createHiddenVirtualView(100);



<ScrollView>

  <HiddenVirtualView>

    <Text>Hello world!</Text>

  </HiddenVirtualView>

</ScrollView>;
```

**Parameters:**

| Name           | Type   | Description                                            |
| -------------- | ------ | ------------------------------------------------------ |
| heightRequired | number | Estimated height of initially rendering `VirtualView`. |

----
url: https://reactnative.dev/docs/next/using-a-listview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/using-a-listview)** (0.87).

Version: Next

React Native provides a suite of components for presenting lists of data. Generally, you'll want to use either [FlatList](/docs/next/flatlist) or [SectionList](/docs/next/sectionlist).

The `FlatList` component displays a scrolling list of changing, but similarly structured, data. `FlatList` works well for long lists of data, where the number of items might change over time. Unlike the more generic [`ScrollView`](/docs/next/using-a-scrollview), the `FlatList` only renders elements that are currently showing on the screen, not all the elements at once.

The `FlatList` component requires two props: `data` and `renderItem`. `data` is the source of information for the list. `renderItem` takes one item from the source and returns a formatted component to render.

This example creates a basic `FlatList` of hardcoded data. Each item in the `data` props is rendered as a `Text` component. The `FlatListBasics` component then renders the `FlatList` and all `Text` components.

If you want to render a set of data broken into logical sections, maybe with section headers, similar to `UITableView` on iOS, then a [SectionList](/docs/next/sectionlist) is the way to go.

One of the most common uses for a list view is displaying data that you fetch from a server. To do that, you will need to [learn about networking in React Native](/docs/next/network).

----
url: https://reactnative.dev/docs/height-and-width
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

After you can control a component's size, the next step is to [learn how to lay it out on the screen](/docs/flexbox).

## Percentage Dimensions[​](#percentage-dimensions "Direct link to Percentage Dimensions")

If you want to fill a certain portion of the screen, but you *don't* want to use the `flex` layout, you *can* use **percentage values** in the component's style. Similar to flex dimensions, percentage dimensions require parent with a defined size.

* [Fixed Dimensions](#fixed-dimensions)
* [Flex Dimensions](#flex-dimensions)
* [Percentage Dimensions](#percentage-dimensions)

----
url: https://reactnative.dev/docs/performance
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

A compelling reason to use React Native instead of WebView-based tools is to achieve at least 60 frames per second and provide a native look and feel to your apps. Whenever feasible, we aim for React Native to handle optimizations automatically, allowing you to focus on your app without worrying about performance. However, there are certain areas where we haven't quite reached that level yet, and others where React Native (similar to writing native code directly) cannot determine the best optimization approach for you. In such cases, manual intervention becomes necessary. We strive to deliver buttery-smooth UI performance by default, but there may be instances where that isn't possible.

This guide is intended to teach you some basics to help you to [troubleshoot performance issues](/docs/profiling), as well as discuss [common sources of problems and their suggested solutions](/docs/performance#common-sources-of-performance-problems).

## What you need to know about frames[​](#what-you-need-to-know-about-frames "Direct link to What you need to know about frames")

Your grandparents' generation called movies ["moving pictures"](https://www.youtube.com/watch?v=F1i40rnpOsA) for a reason: realistic motion in video is an illusion created by quickly changing static images at a consistent speed. We refer to each of these images as frames. The number of frames that is displayed each second has a direct impact on how smooth and ultimately life-like a video (or user interface) seems to be. iOS and Android devices display at least 60 frames per second, which gives you and the UI system at most 16.67ms to do all of the work needed to generate the static image (frame) that the user will see on the screen for that interval. If you are unable to do the work necessary to generate that frame within the allotted time slot, then you will "drop a frame" and the UI will appear unresponsive.

Now to confuse the matter a little bit, open up the [Dev Menu](/docs/debugging#opening-the-dev-menu) in your app and toggle `Show Perf Monitor`. You will notice that there are two different frame rates.

JavaScript thread performance suffers greatly when running in dev mode. This is unavoidable: a lot more work needs to be done at runtime to provide you with good warnings and error messages. Always make sure to test performance in [release builds](/docs/running-on-device#building-your-app-for-production).

### Using `console.log` statements[​](#using-consolelog-statements "Direct link to using-consolelog-statements")

When running a bundled app, these statements can cause a big bottleneck in the JavaScript thread. This includes calls from debugging libraries such as [redux-logger](https://github.com/evgenyrodionov/redux-logger), so make sure to remove them before bundling. You can also use this [babel plugin](https://babeljs.io/docs/plugins/transform-remove-console/) that removes all the `console.*` calls. You need to install it first with `npm i babel-plugin-transform-remove-console --save-dev`, and then edit the `.babelrc` file under your project directory like this:

JSON

```
{

  "env": {

    "production": {

      "plugins": ["transform-remove-console"]

    }

  }

}
```

This will automatically remove all `console.*` calls in the release (production) versions of your project.

It is recommended to use the plugin even if no `console.*` calls are made in your project. A third party library could also call them.

### `FlatList` rendering is too slow or scroll performance is bad for large lists[​](#flatlist-rendering-is-too-slow-or-scroll-performance-is-bad-for-large-lists "Direct link to flatlist-rendering-is-too-slow-or-scroll-performance-is-bad-for-large-lists")

If your [`FlatList`](/docs/flatlist) is rendering slowly, be sure that you've implemented [`getItemLayout`](/docs/flatlist#getitemlayout) to optimize rendering speed by skipping measurement of the rendered items.

There are also other third-party list libraries that are optimized for performance, including [FlashList](https://github.com/shopify/flash-list) and [Legend List](https://github.com/legendapp/legend-list).

### Dropping JS thread FPS because of doing a lot of work on the JavaScript thread at the same time[​](#dropping-js-thread-fps-because-of-doing-a-lot-of-work-on-the-javascript-thread-at-the-same-time "Direct link to Dropping JS thread FPS because of doing a lot of work on the JavaScript thread at the same time")

"Slow Navigator transitions" is the most common manifestation of this, but there are other times this can happen. Deferring work until the JS thread is idle (for example, with `requestIdleCallback`) can be a good approach, but if the user experience cost is too high to delay work during an animation, then you might want to consider [`LayoutAnimation`](/docs/layoutanimation).

The [`Animated API`](/docs/animated) currently calculates each keyframe on-demand on the JavaScript thread unless you [set `useNativeDriver: true`](/blog/2017/02/14/using-native-driver-for-animated#how-do-i-use-this-in-my-app), while [`LayoutAnimation`](/docs/layoutanimation) leverages Core Animation and is unaffected by JS thread and main thread frame drops.

One case for using this is animating in a modal (sliding down from top and fading in a translucent overlay) while initializing and perhaps receiving responses for several network requests, rendering the contents of the modal, and updating the view where the modal was opened from. See the [Animations guide](/docs/animations) for more information about how to use `LayoutAnimation`.

**Caveats:**

* `LayoutAnimation` only works for fire-and-forget animations ("static" animations) -- if it must be interruptible, you will need to use [`Animated`](/docs/animated).

### Moving a view on the screen (scrolling, translating, rotating) drops UI thread FPS[​](#moving-a-view-on-the-screen-scrolling-translating-rotating-drops-ui-thread-fps "Direct link to Moving a view on the screen (scrolling, translating, rotating) drops UI thread FPS")

This is especially true on Android when you have text with a transparent background positioned on top of an image, or any other situation where alpha compositing would be required to re-draw the view on each frame. You will find that enabling `renderToHardwareTextureAndroid` can help with this significantly. For iOS, `shouldRasterizeIOS` is already enabled by default.

Be careful not to overuse this or your memory usage could go through the roof. Profile your performance and memory usage when using these props. If you don't plan to move a view anymore, turn this property off.

### Animating the size of an image drops UI thread FPS[​](#animating-the-size-of-an-image-drops-ui-thread-fps "Direct link to Animating the size of an image drops UI thread FPS")

On iOS, each time you adjust the width or height of an [`Image` component](/docs/image) it is re-cropped and scaled from the original image. This can be very expensive, especially for large images. Instead, use the `transform: [{scale}]` style property to animate the size. An example of when you might do this is when you tap an image and zoom it in to full screen.

### My TouchableX view isn't very responsive[​](#my-touchablex-view-isnt-very-responsive "Direct link to 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. This may occur if `onPress` sets a state that results in a heavy re-render and a few frames are dropped as a result. A solution to this is to wrap any action inside of your `onPress` handler in `requestAnimationFrame`:

React TSX

```
function handleOnPress() {

  requestAnimationFrame(() => {

    this.doExpensiveAction();

  });

}
```

----
url: https://reactnative.dev/docs/next/nodes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/nodes)** (0.87).

Version: Next

----
url: https://reactnative.dev/docs/next/react-native-devtools
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/react-native-devtools)** (0.87).

Version: Next

* Use the [`PerformanceObserver` API](/docs/next/global-PerformanceObserver) in your app to observe performance events at runtime — useful if you want to capture performance telemetry.

    [Since 0.83](#network-since-083)
  * [Performance](#performance-since-083)

    [Since 0.83](#performance-since-083)
  * [Memory](#memory)

- [React DevTools features](#react-devtools-features)

  * [React Components](#react-components)
  * [React Profiler](#react-profiler)

- [Reconnecting DevTools](#reconnecting-devtools)

----
url: https://reactnative.dev/docs/next/usecolorscheme
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/usecolorscheme)** (0.87).

Version: Next

React TSX

```
import {useColorScheme} from 'react-native';
```

The `useColorScheme` React hook provides and subscribes to color scheme updates from the [`Appearance`](/docs/next/appearance) module. The return value indicates the active color scheme. The value may be updated later, either through direct user action (e.g. theme selection in device settings or application-level selected user interface style via [`setColorScheme`](/docs/next/appearance#setcolorscheme)) or on a schedule (e.g. light and dark themes that follow the day/night cycle).

### Return values[​](#return-values "Direct link to Return values")

* `'light'`: The light color scheme is applied.
* `'dark'`: The dark color scheme is applied.
* `null`: May be returned if the native Appearance module is not available.

***

## Example[​](#example "Direct link to Example")

You can find a complete example that demonstrates the use of this hook alongside a React context to add support for light and dark themes to your application in [`AppearanceExample.js`](https://github.com/react/react-native/blob/main/packages/rn-tester/js/examples/Appearance/AppearanceExample.js).

* [Return values](#return-values)
* [Example](#example)

----
url: https://reactnative.dev/docs/backhandler
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds. It is Android-only.

The event subscriptions are called in reverse order (i.e. the last registered subscription is called first).

* **If one subscription returns true,** then subscriptions registered earlier will not be called.
* **If no subscription returns true or none are registered,** it programmatically invokes the default back button functionality to exit the app.

Warning for modal users

If your app shows an opened `Modal`, `BackHandler` will not publish any events ([see `Modal` docs](/docs/modal#onrequestclose)).

## Pattern[​](#pattern "Direct link to Pattern")

React TSX

```
const subscription = BackHandler.addEventListener(

  'hardwareBackPress',

  function () {

    /**

     * this.onMainScreen and this.goBack are just examples,

     * you need to use your own implementation here.

     *

     * Typically you would use the navigator here to go to the last state.

     */



    if (!this.onMainScreen()) {

      this.goBack();

      /**

       * When true is returned the event will not be bubbled up

       * & no other back action will execute

       */

      return true;

    }

    /**

     * Returning false will let the event to bubble up & let other event listeners

     * or the system's default back action to be executed.

     */

    return false;

  },

);



// Unsubscribe the listener on unmount

subscription.remove();
```

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `addEventListener()`[​](#addeventlistener "Direct link to addeventlistener")

React TSX

```
static addEventListener(

  eventName: BackPressEventName,

  handler: () => boolean | null | undefined,

): EventSubscription;
```

***

### `exitApp()`[​](#exitapp "Direct link to exitapp")

React TSX

```
static exitApp();
```

----
url: https://reactnative.dev/docs/build-speed
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
$ yarn react-native run-android --active-arch-only



[ ... ]

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.

Jetifier found 1037 file(s) to forward-jetify. Using 32 workers...

info JS server already running.

info Detected architectures arm64-v8a

info Installing the app...
```

This mechanism relies on the `reactNativeArchitectures` Gradle property.

Therefore, if you're building directly with Gradle from the command line and without the CLI, you can specify the ABI you want to build as follows:

```
$ ./gradlew :app:assembleDebug -PreactNativeArchitectures=x86,x86_64
```

This can be useful if you wish to build your Android App on a CI and use a matrix to parallelize the build of the different architectures.

If you wish, you can also override this value locally, using the `gradle.properties` file you have in the [top-level folder](https://github.com/react/react-native/blob/19cf70266eb8ca151aa0cc46ac4c09cb987b2ceb/template/android/gradle.properties#L30-L33) of your project:

```
# Use this property to specify which architecture you want to build.

# You can also override it from the CLI using

# ./gradlew <task> -PreactNativeArchitectures=x86_64

reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
```

```
org.gradle.configuration-cache=true
```

Please refer to the [official Gradle documentation](https://docs.gradle.org/current/userguide/configuration_cache.html) for more resources on Configuration Caching.

## Using a Maven Mirror (Android-only)[​](#using-a-maven-mirror-android-only "Direct link to Using a Maven Mirror (Android-only)")

When building Android apps, your Gradle builds will need to download the necessary dependencies from Maven Central and other repositories from the internet.

If your organization is running a Maven repository mirror, you should consider using it as it will speed up your build, by downloading the artifacts from the mirror rather than from the internet.

You can configure a mirror by specifying the `exclusiveEnterpriseRepository` property in your `android/gradle.properties` file:

Diff

```
# Use this property to enable or disable the Hermes JS engine.

# If set to false, you will be using JSC instead.

hermesEnabled=true



# Use this property to configure a Maven enterprise repository

# that will be used exclusively to fetch all of your dependencies.

+exclusiveEnterpriseRepository=https://my.internal.proxy.net/
```

```
$ ccache -s

Summary:

  Hits:             196 /  3068 (6.39 %)

    Direct:           0 /  3068 (0.00 %)

    Preprocessed:   196 /  3068 (6.39 %)

  Misses:          2872

    Direct:        3068

    Preprocessed:  2872

  Uncacheable:        1

Primary storage:

  Hits:             196 /  6136 (3.19 %)

  Misses:          5940

  Cache size (GB): 0.60 / 20.00 (3.00 %)
```

Note that `ccache` aggregates the stats over all builds. You can use `ccache --zero-stats` to reset them before a build to verify the cache-hit ratio.

Should you need to wipe your cache, you can do so with `ccache --clear`

#### Xcode Specific Setup[​](#xcode-specific-setup "Direct link to Xcode Specific Setup")

To make sure `ccache` works correctly with iOS and Xcode, you need to enable React Native support for ccache in `ios/Podfile`.

Open `ios/Podfile` in your editor and uncomment the `ccache_enabled` line.

Ruby

```
  post_install do |installer|

    # https://github.com/react/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202

    react_native_post_install(

      installer,

      config[:reactNativePath],

      :mac_catalyst_enabled => false,

      # TODO: Uncomment the line below

      :ccache_enabled => true

    )

  end
```

----
url: https://reactnative.dev/docs/turbo-native-modules-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Now it's time to write some Android platform code to make sure `localStorage` survives after the application is closed.

The first step is to implement the generated `NativeLocalStorageSpec` interface:

* Java
* Kotlin

android/app/src/main/java/com/nativelocalstorage/NativeLocalStorageModule.java

```
package com.nativelocalstorage;



import android.content.Context;

import android.content.SharedPreferences;

import com.nativelocalstorage.NativeLocalStorageSpec;

import com.facebook.react.bridge.ReactApplicationContext;



public class NativeLocalStorageModule extends NativeLocalStorageSpec {



  public static final String NAME = "NativeLocalStorage";



  public NativeLocalStorageModule(ReactApplicationContext reactContext) {

    super(reactContext);

  }



  @Override

  public String getName() {

    return NAME;

  }



  @Override

  public void setItem(String value, String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();

    editor.putString(key, value);

    editor.apply();

  }



  @Override

  public String getItem(String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    String username = sharedPref.getString(key, null);

    return username;

  }



  @Override

  public void removeItem(String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    sharedPref.edit().remove(key).apply();

  }



  @Override

  public void clear() {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    sharedPref.edit().clear().apply();

  }

}
```

android/app/src/main/java/com/nativelocalstorage/NativeLocalStorageModule.kt

```
package com.nativelocalstorage



import android.content.Context

import android.content.SharedPreferences

import com.nativelocalstorage.NativeLocalStorageSpec

import com.facebook.react.bridge.ReactApplicationContext



class NativeLocalStorageModule(reactContext: ReactApplicationContext) : NativeLocalStorageSpec(reactContext) {



  override fun getName() = NAME



  override fun setItem(value: String, key: String) {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.putString(key, value)

    editor.apply()

  }



  override fun getItem(key: String): String? {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val username = sharedPref.getString(key, null)

    return username.toString()

  }



  override fun removeItem(key: String) {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.remove(key)

    editor.apply()

  }



  override fun clear() {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.clear()

    editor.apply()

  }



  companion object {

    const val NAME = "NativeLocalStorage"

  }

}
```

Next we need to create `NativeLocalStoragePackage`. It provides an object to register our Module in the React Native runtime, by wrapping it as a Base Native Package:

* Java
* Kotlin

android/app/src/main/java/com/nativelocalstorage/NativeLocalStoragePackage.java

```
package com.nativelocalstorage;



import com.facebook.react.BaseReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.model.ReactModuleInfo;

import com.facebook.react.module.model.ReactModuleInfoProvider;



import java.util.HashMap;

import java.util.Map;



public class NativeLocalStoragePackage extends BaseReactPackage {



  @Override

  public NativeModule getModule(String name, ReactApplicationContext reactContext) {

    if (name.equals(NativeLocalStorageModule.NAME)) {

      return new NativeLocalStorageModule(reactContext);

    } else {

      return null;

    }

  }



  @Override

  public ReactModuleInfoProvider getReactModuleInfoProvider() {

    return new ReactModuleInfoProvider() {

      @Override

      public Map<String, ReactModuleInfo> getReactModuleInfos() {

        Map<String, ReactModuleInfo> map = new HashMap<>();

        map.put(NativeLocalStorageModule.NAME, new ReactModuleInfo(

          NativeLocalStorageModule.NAME,       // name

          NativeLocalStorageModule.NAME,       // className

          false, // canOverrideExistingModule

          false, // needsEagerInit

          false, // isCXXModule

          true   // isTurboModule

        ));

        return map;

      }

    };

  }

}
```

android/app/src/main/java/com/nativelocalstorage/NativeLocalStoragePackage.kt

```
package com.nativelocalstorage



import com.facebook.react.BaseReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.module.model.ReactModuleInfo

import com.facebook.react.module.model.ReactModuleInfoProvider



class NativeLocalStoragePackage : BaseReactPackage() {



  override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =

    if (name == NativeLocalStorageModule.NAME) {

      NativeLocalStorageModule(reactContext)

    } else {

      null

    }



  override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {

    mapOf(

      NativeLocalStorageModule.NAME to ReactModuleInfo(

        name = NativeLocalStorageModule.NAME,

        className = NativeLocalStorageModule.NAME,

        canOverrideExistingModule = false,

        needsEagerInit = false,

        isCxxModule = false,

        isTurboModule = true

      )

    )

  }

}
```

```
package com.inappmodule;



import android.app.Application;

import com.facebook.react.PackageList;

import com.facebook.react.ReactApplication;

import com.facebook.react.ReactHost;

import com.facebook.react.ReactNativeHost;

import com.facebook.react.ReactPackage;

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;

import com.facebook.react.defaults.DefaultReactHost;

import com.facebook.react.defaults.DefaultReactNativeHost;

import com.facebook.soloader.SoLoader;

import com.nativelocalstorage.NativeLocalStoragePackage;



import java.util.ArrayList;

import java.util.List;



public class MainApplication extends Application implements ReactApplication {



  private final ReactNativeHost reactNativeHost = new DefaultReactNativeHost(this) {

    @Override

    public List<ReactPackage> getPackages() {

      List<ReactPackage> packages = new PackageList(this).getPackages();

      // Packages that cannot be autolinked yet can be added manually here, for example:

      // packages.add(new MyReactNativePackage());

      packages.add(new NativeLocalStoragePackage());

      return packages;

    }



    @Override

    public String getJSMainModuleName() {

      return "index";

    }



    @Override

    public boolean getUseDeveloperSupport() {

      return BuildConfig.DEBUG;

    }



    @Override

    public boolean isNewArchEnabled() {

      return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;

    }



    @Override

    public boolean isHermesEnabled() {

      return BuildConfig.IS_HERMES_ENABLED;

    }

  };



  @Override

  public ReactHost getReactHost() {

    return DefaultReactHost.getDefaultReactHost(getApplicationContext(), reactNativeHost);

  }



  @Override

  public void onCreate() {

    super.onCreate();

    SoLoader.init(this, false);

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      // If you opted-in for the New Architecture, we load the native entry point for this app.

      DefaultNewArchitectureEntryPoint.load();

    }

  }

}
```

android/app/src/main/java/com/turobmoduleexample/MainApplication.kt

```
package com.inappmodule



import android.app.Application

import com.facebook.react.PackageList

import com.facebook.react.ReactApplication

import com.facebook.react.ReactHost

import com.facebook.react.ReactNativeHost

import com.facebook.react.ReactPackage

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

import com.facebook.react.defaults.DefaultReactNativeHost

import com.facebook.soloader.SoLoader

import com.nativelocalstorage.NativeLocalStoragePackage



class MainApplication : Application(), ReactApplication {



  override val reactNativeHost: ReactNativeHost =

      object : DefaultReactNativeHost(this) {

        override fun getPackages(): List<ReactPackage> =

            PackageList(this).packages.apply {

              // Packages that cannot be autolinked yet can be added manually here, for example:

              // add(MyReactNativePackage())

              add(NativeLocalStoragePackage())

            }



        override fun getJSMainModuleName(): String = "index"



        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG



        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

      }



  override val reactHost: ReactHost

    get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

    SoLoader.init(this, false)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      // If you opted-in for the New Architecture, we load the native entry point for this app.

      load()

    }

  }

}
```

You can now build and run your code on an emulator:

* npm
* Yarn

```
npm run android
```

```
yarn run android
```

----
url: https://reactnative.dev/docs/next/layout-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/layout-props)** (0.87).

Version: Next

info

More detailed examples about those properties can be found on the [Layout with Flexbox](/docs/next/flexbox) page.

### Example[​](#example "Direct link to Example")

The following example shows how different properties can affect or shape a React Native layout. You can try for example to add or remove squares from the UI while changing the values of the property `flexWrap`.

* TypeScript
* JavaScript

***

# Reference

## Props[​](#props "Direct link to Props")

### `alignContent`[​](#aligncontent "Direct link to aligncontent")

`alignContent` controls how rows align in the cross direction, overriding the `alignContent` of the parent.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content) for more details.

| Type                                                                                                 | Required |
| ---------------------------------------------------------------------------------------------------- | -------- |
| enum('flex-start', 'flex-end', 'center', 'stretch', 'space-between', 'space-around', 'space-evenly') | No       |

***

### `alignItems`[​](#alignitems "Direct link to alignitems")

`alignItems` aligns children in the cross direction. For example, if children are flowing vertically, `alignItems` controls how they align horizontally. It works like `align-items` in CSS (default: stretch).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items) for more details.

| Type                                                            | Required |
| --------------------------------------------------------------- | -------- |
| enum('flex-start', 'flex-end', 'center', 'stretch', 'baseline') | No       |

***

### `alignSelf`[​](#alignself "Direct link to alignself")

`alignSelf` controls how a child aligns in the cross direction, overriding the `alignItems` of the parent. It works like `align-self` in CSS (default: auto).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self) for more details.

| Type                                                                    | Required |
| ----------------------------------------------------------------------- | -------- |
| enum('auto', 'flex-start', 'flex-end', 'center', 'stretch', 'baseline') | No       |

***

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `borderBottomWidth`[​](#borderbottomwidth "Direct link to borderbottomwidth")

`borderBottomWidth` works like `border-bottom-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderEndWidth`[​](#borderendwidth "Direct link to borderendwidth")

When direction is `ltr`, `borderEndWidth` is equivalent to `borderRightWidth`. When direction is `rtl`, `borderEndWidth` is equivalent to `borderLeftWidth`.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderLeftWidth`[​](#borderleftwidth "Direct link to borderleftwidth")

`borderLeftWidth` works like `border-left-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderRightWidth`[​](#borderrightwidth "Direct link to borderrightwidth")

`borderRightWidth` works like `border-right-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderStartWidth`[​](#borderstartwidth "Direct link to borderstartwidth")

When direction is `ltr`, `borderStartWidth` is equivalent to `borderLeftWidth`. When direction is `rtl`, `borderStartWidth` is equivalent to `borderRightWidth`.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderTopWidth`[​](#bordertopwidth "Direct link to bordertopwidth")

`borderTopWidth` works like `border-top-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderWidth`[​](#borderwidth "Direct link to borderwidth")

`borderWidth` works like `border-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `bottom`[​](#bottom "Direct link to bottom")

`bottom` is the number of logical pixels to offset the bottom edge of this component.

It works similarly to `bottom` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/bottom) for more details of how `bottom` affects layout.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `boxSizing`[​](#boxsizing "Direct link to boxsizing")

`boxSizing` defines how the element's various sizing props (`width`, `height`, `minWidth`, `minHeight`, etc.) are computed. If `boxSizing` is `border-box`, these sizes apply to the border box of the element. If it is `content-box`, they apply to the content box of the element. The default value is `border-box`. The [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) is a good source of information if you wish to learn more about how this prop works.

| Type                              | Required |
| --------------------------------- | -------- |
| enum('border-box', 'content-box') | No       |

***

### `columnGap`[​](#columngap "Direct link to columngap")

`columnGap` works like `column-gap` in CSS. It accepts numbers (in points) or percentage strings (e.g. `'10%'`). Percentage values are supported on the [New Architecture](/architecture/landing-page).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-gap) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `direction`[​](#direction "Direct link to direction")

`direction` specifies the directional flow of the user interface. The default is `inherit`, except for root node which will have value based on the current locale.

See [MDN CSS Reference](https://www.yogalayout.dev/docs/styling/layout-direction) for more details.

| Type                          | Required |
| ----------------------------- | -------- |
| enum('inherit', 'ltr', 'rtl') | No       |

***

### `display`[​](#display "Direct link to display")

`display` sets the display type of this component.

It works similarly to `display` in CSS but only supports the values 'flex', 'none', and 'contents'. The default is `flex`.

| Type                             | Required |
| -------------------------------- | -------- |
| enum('none', 'flex', 'contents') | No       |

***

### `end`[​](#end "Direct link to end")

When the direction is `ltr`, `end` is equivalent to `right`. When the direction is `rtl`, `end` is equivalent to `left`.

This style takes precedence over the `left` and `right` styles.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `flex`[​](#flex "Direct link to flex")

In React Native `flex` does not work the same way that it does in CSS. `flex` is a number rather than a string, and it works according to the [Yoga](https://github.com/facebook/yoga) layout engine.

When `flex` is a positive number, it makes the component flexible, and it will be sized proportional to its flex value. So a component with `flex` set to `2` will take twice the space as a component with `flex` set to 1. `flex: <positive number>` equates to `flexGrow: <positive number>, flexShrink: 1, flexBasis: 0`.

When `flex` is `0`, the component is sized according to `width` and `height`, and it is inflexible.

When `flex` is `-1`, the component is normally sized according to `width` and `height`. However, if there's not enough space, the component will shrink to its `minWidth` and `minHeight`.

`flexGrow`, `flexShrink`, and `flexBasis` work the same as in CSS.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `flexBasis`[​](#flexbasis "Direct link to flexbasis")

`flexBasis` is an axis-independent way of providing the default size of an item along the main axis. Setting the `flexBasis` of a child is similar to setting the `width` of that child if its parent is a container with `flexDirection: row` or setting the `height` of a child if its parent is a container with `flexDirection: column`. The `flexBasis` of an item is the default size of that item, the size of the item before any `flexGrow` and `flexShrink` calculations are performed.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `flexDirection`[​](#flexdirection "Direct link to flexdirection")

`flexDirection` controls which directions children of a container go. `row` goes left to right, `column` goes top to bottom, and you may be able to guess what the other two do. It works like `flex-direction` in CSS, except the default is `column`.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction) for more details.

| Type                                                   | Required |
| ------------------------------------------------------ | -------- |
| enum('row', 'row-reverse', 'column', 'column-reverse') | No       |

***

### `flexGrow`[​](#flexgrow "Direct link to flexgrow")

`flexGrow` describes how any space within a container should be distributed among its children along the main axis. After laying out its children, a container will distribute any remaining space according to the flex grow values specified by its children.

`flexGrow` accepts any floating point value >= 0, with 0 being the default value. A container will distribute any remaining space among its children weighted by the children’s `flexGrow` values.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `flexShrink`[​](#flexshrink "Direct link to flexshrink")

[`flexShrink`](/docs/next/layout-props#flexshrink) describes how to shrink children along the main axis in the case in which the total size of the children overflows the size of the container on the main axis. `flexShrink` is very similar to `flexGrow` and can be thought of in the same way if any overflowing size is considered to be negative remaining space. These two properties also work well together by allowing children to grow and shrink as needed.

`flexShrink` accepts any floating point value >= 0, with 0 being the default value. A container will shrink its children weighted by the children’s `flexShrink` values.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `flexWrap`[​](#flexwrap "Direct link to flexwrap")

`flexWrap` controls whether children can wrap around after they hit the end of a flex container. It works like `flex-wrap` in CSS (default: nowrap).

Note it does not work anymore with `alignItems: stretch` (the default), so you may want to use `alignItems: flex-start` for example (breaking change details: <https://github.com/react/react-native/releases/tag/v0.28.0>).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap) for more details.

| Type                                   | Required |
| -------------------------------------- | -------- |
| enum('wrap', 'nowrap', 'wrap-reverse') | No       |

***

### `gap`[​](#gap "Direct link to gap")

`gap` works like `gap` in CSS. It is a shorthand for `rowGap` and `columnGap`. It accepts numbers (in points) or percentage strings (e.g. `'10%'`). Percentage values are supported on the [New Architecture](/architecture/landing-page).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/gap) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `height`[​](#height "Direct link to height")

`height` sets the height of this component.

It works similarly to `height` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/height) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `inset`[​](#inset "Direct link to inset")

note

`inset` is only available on the [New Architecture](/architecture/landing-page)

Setting `inset` has the same effect as setting each of `top`, `bottom`, `right` and `left` props.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/inset) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetBlock`[​](#insetblock "Direct link to insetblock")

note

`insetBlock` is only available on the [New Architecture](/architecture/landing-page)

Equivalent to [`top`](/docs/next/layout-props#top) and [`bottom`](/docs/next/layout-props#bottom).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetBlockEnd`[​](#insetblockend "Direct link to insetblockend")

note

`insetBlockEnd` is only available on the [New Architecture](/architecture/landing-page)

Equivalent to [`bottom`](/docs/next/layout-props#bottom).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetBlockStart`[​](#insetblockstart "Direct link to insetblockstart")

note

`insetBlockStart` is only available on the [New Architecture](/architecture/landing-page)

Equivalent to [`top`](/docs/next/layout-props#top).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetInline`[​](#insetinline "Direct link to insetinline")

note

`insetInline` is only available on the [New Architecture](/architecture/landing-page)

Equivalent to [`right`](/docs/next/layout-props#right) and [`left`](/docs/next/layout-props#left).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetInlineEnd`[​](#insetinlineend "Direct link to insetinlineend")

note

`insetInlineEnd` is only available on the [New Architecture](/architecture/landing-page)

When direction is `ltr`, `insetInlineEnd` is equivalent to [`right`](/docs/next/layout-props#right). When direction is `rtl`, `insetInlineEnd` is equivalent to [`left`](/docs/next/layout-props#left).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetInlineStart`[​](#insetinlinestart "Direct link to insetinlinestart")

note

`insetInlineStart` is only available on the [New Architecture](/architecture/landing-page)

When direction is `ltr`, `insetInlineStart` is equivalent to [`left`](/docs/next/layout-props#left). When direction is `rtl`, `insetInlineStart` is equivalent to [`right`](/docs/next/layout-props#right).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

| Type                    | Required |
| ----------------------- | -------- |
| enum('auto', 'isolate') | No       |

***

### `justifyContent`[​](#justifycontent "Direct link to justifycontent")

`justifyContent` aligns children in the main direction. For example, if children are flowing vertically, `justifyContent` controls how they align vertically. It works like `justify-content` in CSS (default: flex-start).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) for more details.

| Type                                                                                      | Required |
| ----------------------------------------------------------------------------------------- | -------- |
| enum('flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly') | No       |

***

### `left`[​](#left "Direct link to left")

`left` is the number of logical pixels to offset the left edge of this component.

It works similarly to `left` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/left) for more details of how `left` affects layout.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `margin`[​](#margin "Direct link to margin")

Setting `margin` has the same effect as setting each of `marginTop`, `marginLeft`, `marginBottom`, and `marginRight`.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginBottom`[​](#marginbottom "Direct link to marginbottom")

`marginBottom` works like `margin-bottom` in CSS. See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginBlock`[​](#marginblock "Direct link to marginblock")

Equivalent to [`marginVertical`](/docs/next/layout-props#marginvertical).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-block) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginBlockEnd`[​](#marginblockend "Direct link to marginblockend")

Equivalent to [`marginBottom`](/docs/next/layout-props#marginbottom).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-block-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginBlockStart`[​](#marginblockstart "Direct link to marginblockstart")

Equivalent to [`marginTop`](/docs/next/layout-props#margintop).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-block-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginEnd`[​](#marginend "Direct link to marginend")

When direction is `ltr`, `marginEnd` is equivalent to `marginRight`. When direction is `rtl`, `marginEnd` is equivalent to `marginLeft`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginHorizontal`[​](#marginhorizontal "Direct link to marginhorizontal")

Setting `marginHorizontal` has the same effect as setting both `marginLeft` and `marginRight`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginInline`[​](#margininline "Direct link to margininline")

Equivalent to [`marginHorizontal`](/docs/next/layout-props#marginhorizontal).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-inline) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginInlineEnd`[​](#margininlineend "Direct link to margininlineend")

When direction is `ltr`, `marginInlineEnd` is equivalent to [`marginEnd`](/docs/next/layout-props#marginend) (i.e. `marginRight`). When direction is `rtl`, `marginInlineEnd` is equivalent to [`marginEnd`](/docs/next/layout-props#marginend) (i.e. `marginLeft`).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-inline-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginInlineStart`[​](#margininlinestart "Direct link to margininlinestart")

When direction is `ltr`, `marginInlineStart` is equivalent to [`marginStart`](/docs/next/layout-props#marginstart) (i.e. `marginLeft`). When direction is `rtl`, `marginInlineStart` is equivalent to [`marginStart`](/docs/next/layout-props#marginstart) (i.e. `marginRight`).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-inline-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginLeft`[​](#marginleft "Direct link to marginleft")

`marginLeft` works like `margin-left` in CSS. See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginRight`[​](#marginright "Direct link to marginright")

`marginRight` works like `margin-right` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginStart`[​](#marginstart "Direct link to marginstart")

When direction is `ltr`, `marginStart` is equivalent to `marginLeft`. When direction is `rtl`, `marginStart` is equivalent to `marginRight`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginTop`[​](#margintop "Direct link to margintop")

`marginTop` works like `margin-top` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-top) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginVertical`[​](#marginvertical "Direct link to marginvertical")

Setting `marginVertical` has the same effect as setting both `marginTop` and `marginBottom`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `maxHeight`[​](#maxheight "Direct link to maxheight")

`maxHeight` is the maximum height for this component, in logical pixels.

It works similarly to `max-height` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-height) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `maxWidth`[​](#maxwidth "Direct link to maxwidth")

`maxWidth` is the maximum width for this component, in logical pixels.

It works similarly to `max-width` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-width) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `minHeight`[​](#minheight "Direct link to minheight")

`minHeight` is the minimum height for this component, in logical pixels.

It works similarly to `min-height` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-height) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `minWidth`[​](#minwidth "Direct link to minwidth")

`minWidth` is the minimum width for this component, in logical pixels.

It works similarly to `min-width` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-width) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `overflow`[​](#overflow "Direct link to overflow")

`overflow` controls how children are measured and displayed. `overflow: hidden` causes views to be clipped while `overflow: scroll` causes views to be measured independently of their parents' main axis. It works like `overflow` in CSS (default: visible).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) for more details.

| Type                                | Required |
| ----------------------------------- | -------- |
| enum('visible', 'hidden', 'scroll') | No       |

***

### `padding`[​](#padding "Direct link to padding")

Setting `padding` has the same effect as setting each of `paddingTop`, `paddingBottom`, `paddingLeft`, and `paddingRight`.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingBottom`[​](#paddingbottom "Direct link to paddingbottom")

`paddingBottom` works like `padding-bottom` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-bottom) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingBlock`[​](#paddingblock "Direct link to paddingblock")

Equivalent to [`paddingVertical`](/docs/next/layout-props#paddingvertical).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-block) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingBlockEnd`[​](#paddingblockend "Direct link to paddingblockend")

Equivalent to [`paddingBottom`](/docs/next/layout-props#paddingbottom).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-block-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingBlockStart`[​](#paddingblockstart "Direct link to paddingblockstart")

Equivalent to [`paddingTop`](/docs/next/layout-props#paddingtop).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-block-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingEnd`[​](#paddingend "Direct link to paddingend")

When direction is `ltr`, `paddingEnd` is equivalent to `paddingRight`. When direction is `rtl`, `paddingEnd` is equivalent to `paddingLeft`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingHorizontal`[​](#paddinghorizontal "Direct link to paddinghorizontal")

Setting `paddingHorizontal` is like setting both of `paddingLeft` and `paddingRight`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingInline`[​](#paddinginline "Direct link to paddinginline")

Equivalent to [`paddingHorizontal`](/docs/next/layout-props#paddinghorizontal).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-inline) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingInlineEnd`[​](#paddinginlineend "Direct link to paddinginlineend")

When direction is `ltr`, `paddingInlineEnd` is equivalent to [`paddingEnd`](/docs/next/layout-props#paddingend) (i.e. `paddingRight`). When direction is `rtl`, `paddingInlineEnd` is equivalent to [`paddingEnd`](/docs/next/layout-props#paddingend) (i.e. `paddingLeft`).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-inline-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingInlineStart`[​](#paddinginlinestart "Direct link to paddinginlinestart")

When direction is `ltr`, `paddingInlineStart` is equivalent to [`paddingStart`](/docs/next/layout-props#paddingstart) (i.e. `paddingLeft`). When direction is `rtl`, `paddingInlineStart` is equivalent to [`paddingStart`](/docs/next/layout-props#paddingstart) (i.e. `paddingRight`).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-inline-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingLeft`[​](#paddingleft "Direct link to paddingleft")

`paddingLeft` works like `padding-left` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-left) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingRight`[​](#paddingright "Direct link to paddingright")

`paddingRight` works like `padding-right` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-right) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingStart`[​](#paddingstart "Direct link to paddingstart")

When direction is `ltr`, `paddingStart` is equivalent to `paddingLeft`. When direction is `rtl`, `paddingStart` is equivalent to `paddingRight`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingTop`[​](#paddingtop "Direct link to paddingtop")

`paddingTop` works like `padding-top` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-top) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingVertical`[​](#paddingvertical "Direct link to paddingvertical")

Setting `paddingVertical` is like setting both of `paddingTop` and `paddingBottom`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `position`[​](#position "Direct link to position")

`position` in React Native is similar to [regular CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/position), but everything is set to `relative` by default.

`relative` will position an element according to the normal flow of the layout. Insets (`top`, `bottom`, `left`, `right`) will offset relative to this layout.

`absolute` takes the element out of the normal flow of the layout. Insets will offset relative to its [containing block](/docs/next/flexbox#the-containing-block).

`static` will position an element according to the normal flow of the layout. Insets will have no effect. `static` elements do not form a containing block for absolute descendants.

For more information, see the [Layout with Flexbox docs](/docs/next/flexbox#position). Also, [the Yoga documentation](https://www.yogalayout.dev/docs/styling/position) has more details on how `position` differs between React Native and CSS.

| Type                                   | Required |
| -------------------------------------- | -------- |
| enum('absolute', 'relative', 'static') | No       |

***

### `right`[​](#right "Direct link to right")

`right` is the number of logical pixels to offset the right edge of this component.

It works similarly to `right` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/right) for more details of how `right` affects layout.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `rowGap`[​](#rowgap "Direct link to rowgap")

`rowGap` works like `row-gap` in CSS. It accepts numbers (in points) or percentage strings (e.g. `'10%'`). Percentage values are supported on the [New Architecture](/architecture/landing-page).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/row-gap) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `start`[​](#start "Direct link to start")

When the direction is `ltr`, `start` is equivalent to `left`. When the direction is `rtl`, `start` is equivalent to `right`.

This style takes precedence over the `left`, `right`, and `end` styles.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `top`[​](#top "Direct link to top")

`top` is the number of logical pixels to offset the top edge of this component.

It works similarly to `top` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/top) for more details of how `top` affects layout.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `width`[​](#width "Direct link to width")

`width` sets the width of this component.

It works similarly to `width` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/width) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `zIndex`[​](#zindex "Direct link to zindex")

`zIndex` controls which components display on top of others. Normally, you don't use `zIndex`. Components render according to their order in the document tree, so later components draw over earlier ones. `zIndex` may be useful if you have animations or custom modal interfaces where you don't want this behavior.

It works like the CSS `z-index` property - components with a larger `zIndex` will render on top. Think of the z-direction like it's pointing from the phone into your eyeball.

On iOS, `zIndex` may require `View`s to be siblings of each other for it to work as expected.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/z-index) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

----
url: https://reactnative.dev/docs/next/the-new-architecture/what-is-codegen
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/what-is-codegen)** (0.87).

Version: Next

----
url: https://reactnative.dev/docs/gesture-responder-system
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

For higher-level gesture interpretation, check out [PanResponder](/docs/panresponder).

* [Best Practices](#best-practices)

* [TouchableHighlight and Touchable\*](#touchablehighlight-and-touchable)

* [Responder Lifecycle](#responder-lifecycle)

  * [Capture ShouldSet Handlers](#capture-shouldset-handlers)
  * [PanResponder](#panresponder)

----
url: https://reactnative.dev/docs/modal
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The Modal component is a basic way to present content above an enclosing view.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### `animationType`[​](#animationtype "Direct link to animationtype")

The `animationType` prop controls how the modal animates.

Possible values:

* `slide` slides in from the bottom
* `fade` fades into view
* `none` appears without an animation

| Type                                | Default |
| ----------------------------------- | ------- |
| enum(`'none'`, `'slide'`, `'fade'`) | `none`  |

***

### `backdropColor`[​](#backdropcolor "Direct link to backdropcolor")

The `backdropColor` of the modal (or background color of the modal's container.) Defaults to `white` if not provided and transparent is `false`. Ignored if `transparent` is `true`.

| Type                  | Default |
| --------------------- | ------- |
| [color](/docs/colors) | white   |

***

### `hardwareAccelerated`Android[​](#hardwareaccelerated-android "Direct link to hardwareaccelerated-android")

The `hardwareAccelerated` prop controls whether to force hardware acceleration for the underlying window.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `navigationBarTranslucent`Android[​](#navigationbartranslucent-android "Direct link to navigationbartranslucent-android")

The `navigationBarTranslucent` prop determines whether your modal should go under the system navigation bar. However, `statusBarTranslucent` also needs to be set to `true` to make navigation bar translucent.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `onDismiss`iOS[​](#ondismiss-ios "Direct link to ondismiss-ios")

The `onDismiss` prop allows passing a function that will be called once the modal has been dismissed.

| Type     |
| -------- |
| function |

***

### `onOrientationChange`iOS[​](#onorientationchange-ios "Direct link to onorientationchange-ios")

The `onOrientationChange` callback is called when the orientation changes while the modal is being displayed. The orientation provided is only 'portrait' or 'landscape'. This callback is also called on initial render, regardless of the current orientation.

| Type     |
| -------- |
| function |

***

### `allowSwipeDismissal`iOS[​](#allowswipedismissal-ios "Direct link to allowswipedismissal-ios")

Controls whether the modal can be dismissed by swiping down on iOS. This requires you to implement the `onRequestClose` prop to handle the dismissal.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/element-nodes) when mounted.

***

### `onRequestClose`[​](#onrequestclose "Direct link to onrequestclose")

The `onRequestClose` callback is called when the user taps the hardware back button on Android or the menu button on Apple TV. Because of this required prop, be aware that `BackHandler` events will not be emitted as long as the modal is open. On iOS, this callback is called when a Modal is being dismissed using a drag gesture when `presentationStyle` is `pageSheet` or `formSheet`. When `allowSwipeDismissal` is enabled this callback will be called after dismissing the modal.

| Type                                    |
| --------------------------------------- |
| functionRequiredAndroidTV***functioniOS |

***

### `onShow`[​](#onshow "Direct link to onshow")

The `onShow` prop allows passing a function that will be called once the modal has been shown.

| Type     |
| -------- |
| function |

***

| Type                                                                   | Default                                                                          |
| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| enum(`'fullScreen'`, `'pageSheet'`, `'formSheet'`, `'overFullScreen'`) | `fullScreen` if `transparent={false}`***`overFullScreen` if `transparent={true}` |

***

### `statusBarTranslucent`Android[​](#statusbartranslucent-android "Direct link to statusbartranslucent-android")

The `statusBarTranslucent` prop determines whether your modal should go under the system statusbar.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `supportedOrientations`iOS[​](#supportedorientations-ios "Direct link to supportedorientations-ios")

The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations. On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field.

note

When using `presentationStyle` of `pageSheet` or `formSheet`, this property will be ignored on iOS.

| Type                                                                                                           | Default        |
| -------------------------------------------------------------------------------------------------------------- | -------------- |
| array of enums(`'portrait'`, `'portrait-upside-down'`, `'landscape'`, `'landscape-left'`, `'landscape-right'`) | `['portrait']` |

***

### `transparent`[​](#transparent "Direct link to transparent")

The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `visible`[​](#visible "Direct link to visible")

The `visible` prop determines whether your modal is visible.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

* [Example](#example)

* [Props](#props)

  * [View Props](#view-props)
  * [`animationType`](#animationtype)
  * [`backdropColor`](#backdropcolor)
  * [`hardwareAccelerated`](#hardwareaccelerated-android)

    [Android](#hardwareaccelerated-android)
  * [`navigationBarTranslucent`](#navigationbartranslucent-android)

    [Android](#navigationbartranslucent-android)
  * [`onDismiss`](#ondismiss-ios)

    [iOS](#ondismiss-ios)
  * [`onOrientationChange`](#onorientationchange-ios)

    [iOS](#onorientationchange-ios)
  * [`allowSwipeDismissal`](#allowswipedismissal-ios)

    [iOS](#allowswipedismissal-ios)
  * [`ref`](#ref)
  * [`onRequestClose`](#onrequestclose)
  * [`onShow`](#onshow)
  * [`presentationStyle`](#presentationstyle-ios)

    [iOS](#presentationstyle-ios)
  * [`statusBarTranslucent`](#statusbartranslucent-android)

    [Android](#statusbartranslucent-android)
  * [`supportedOrientations`](#supportedorientations-ios)

    [iOS](#supportedorientations-ios)
  * [`transparent`](#transparent)
  * [`visible`](#visible)

----
url: https://reactnative.dev/docs/rect
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`Rect` accepts numeric pixel values to describe how far to extend a rectangular area. These values are added to the original area's size to expand it.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

    bottom: 20,

    left: null,

    right: undefined,

    top: 50

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `bottom`[​](#bottom "Direct link to bottom")

| Type                        | Required |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

### `left`[​](#left "Direct link to left")

| Type                        | Required |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

### `right`[​](#right "Direct link to right")

| Type                        | Required |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

### `top`[​](#top "Direct link to top")

| Type                        | Required |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

## Used by[​](#used-by "Direct link to Used by")

* [`Image`](/docs/image)
* [`Pressable`](/docs/pressable)
* [`Text`](/docs/text)
* [`TouchableWithoutFeedback`](/docs/touchablewithoutfeedback)

----
url: https://reactnative.dev/docs/scrollview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Component that wraps platform ScrollView while providing integration with touch locking "responder" system.

Keep in mind that ScrollViews must have a bounded height in order to work, since they contain unbounded-height children into a bounded container (via a scroll interaction). In order to bound the height of a ScrollView, either set the height of the view directly (discouraged) or make sure all parent views have bounded height. Forgetting to transfer `{flex: 1}` down the view stack can lead to errors here, which the element inspector makes quick to debug.

Doesn't yet support other contained responders from blocking this scroll view from becoming the responder.

`<ScrollView>` vs [`<FlatList>`](/docs/flatlist) - which one to use?

`ScrollView` renders all its react child components at once, but this has a performance downside.

Imagine you have a very long list of items you want to display, maybe several screens worth of content. Creating JS components and native views for everything all at once, much of which may not even be shown, will contribute to slow rendering and increased memory usage.

This is where `FlatList` comes into play. `FlatList` renders items lazily, when they are about to appear, and removes items that scroll way off screen to save memory and processing time.

`FlatList` is also handy if you want to render separators between your items, multiple columns, infinite scroll loading, or any number of other features it supports out of the box.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### `StickyHeaderComponent`[​](#stickyheadercomponent "Direct link to stickyheadercomponent")

A React Component that will be used to render sticky headers, should be used together with `stickyHeaderIndices`. You may need to set this component if your sticky header uses custom transforms, for example, when you want your list to have an animated and hidable header. If a component has not been provided, the default [`ScrollViewStickyHeader`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Components/ScrollView/ScrollViewStickyHeader.js) component will be used.

| Type               |
| ------------------ |
| component, element |

***

### `alwaysBounceHorizontal`iOS[​](#alwaysbouncehorizontal-ios "Direct link to alwaysbouncehorizontal-ios")

When true, the scroll view bounces horizontally when it reaches the end even if the content is smaller than the scroll view itself.

| Type | Default                                             |
| ---- | --------------------------------------------------- |
| bool | `true` when `horizontal={true}`***`false` otherwise |

***

### `alwaysBounceVertical`iOS[​](#alwaysbouncevertical-ios "Direct link to alwaysbouncevertical-ios")

When true, the scroll view bounces vertically when it reaches the end even if the content is smaller than the scroll view itself.

| Type | Default                                             |
| ---- | --------------------------------------------------- |
| bool | `false` when `horizontal={true}`***`true` otherwise |

***

### `automaticallyAdjustContentInsets`iOS[​](#automaticallyadjustcontentinsets-ios "Direct link to automaticallyadjustcontentinsets-ios")

Controls whether iOS should automatically adjust the content inset for scroll views that are placed behind a navigation bar or tab bar/toolbar.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `automaticallyAdjustKeyboardInsets`iOS[​](#automaticallyadjustkeyboardinsets-ios "Direct link to automaticallyadjustkeyboardinsets-ios")

Controls whether the ScrollView should automatically adjust its `contentInset` and `scrollViewInsets` when the Keyboard changes its size.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `automaticallyAdjustsScrollIndicatorInsets`iOS[​](#automaticallyadjustsscrollindicatorinsets-ios "Direct link to automaticallyadjustsscrollindicatorinsets-ios")

Controls whether iOS should automatically adjust the scroll indicator insets. See Apple's [documentation on the property](https://developer.apple.com/documentation/uikit/uiscrollview/3198043-automaticallyadjustsscrollindica).

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `bounces`iOS[​](#bounces-ios "Direct link to bounces-ios")

When true, the scroll view bounces when it reaches the end of the content if the content is larger than the scroll view along the axis of the scroll direction. When `false`, it disables all bouncing even if the `alwaysBounce*` props are `true`.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `bouncesZoom`iOS[​](#bounceszoom-ios "Direct link to bounceszoom-ios")

When `true`, gestures can drive zoom past min/max and the zoom will animate to the min/max value at gesture end, otherwise the zoom will not exceed the limits.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `canCancelContentTouches`iOS[​](#cancancelcontenttouches-ios "Direct link to cancancelcontenttouches-ios")

When `false`, once tracking starts, won't try to drag if the touch moves.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `centerContent`iOS[​](#centercontent-ios "Direct link to centercontent-ios")

When `true`, the scroll view automatically centers the content when the content is smaller than the scroll view bounds; when the content is larger than the scroll view, this property has no effect.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `contentContainerStyle`[​](#contentcontainerstyle "Direct link to contentcontainerstyle")

These styles will be applied to the scroll view content container which wraps all of the child views. Example:

```
return (

  <ScrollView contentContainerStyle={styles.contentContainer}>

  </ScrollView>

);

...

const styles = StyleSheet.create({

  contentContainer: {

    paddingVertical: 20

  }

});
```

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

***

### `contentInset`iOS[​](#contentinset-ios "Direct link to contentinset-ios")

The amount by which the scroll view content is inset from the edges of the scroll view.

| Type                                                                 | Default                                  |
| -------------------------------------------------------------------- | ---------------------------------------- |
| object: `{top: number, left: number, bottom: number, right: number}` | `{top: 0, left: 0, bottom: 0, right: 0}` |

***

### `contentInsetAdjustmentBehavior`iOS[​](#contentinsetadjustmentbehavior-ios "Direct link to contentinsetadjustmentbehavior-ios")

This property specifies how the safe area insets are used to modify the content area of the scroll view. Available on iOS 11 and later.

| Type                                                           | Default   |
| -------------------------------------------------------------- | --------- |
| enum(`'automatic'`, `'scrollableAxes'`, `'never'`, `'always'`) | `'never'` |

***

### `contentOffset`[​](#contentoffset "Direct link to contentoffset")

Used to manually set the starting scroll offset.

| Type  | Default        |
| ----- | -------------- |
| Point | `{x: 0, y: 0}` |

***

### `decelerationRate`[​](#decelerationrate "Direct link to decelerationrate")

A floating-point number that determines how quickly the scroll view decelerates after the user lifts their finger. You may also use string shortcuts `"normal"` and `"fast"` which match the underlying iOS settings for `UIScrollViewDecelerationRateNormal` and `UIScrollViewDecelerationRateFast` respectively.

* `'normal'` 0.998 on iOS, 0.985 on Android.
* `'fast'`, 0.99 on iOS, 0.9 on Android.

| Type                               | Default    |
| ---------------------------------- | ---------- |
| enum(`'fast'`, `'normal'`), number | `'normal'` |

***

### `directionalLockEnabled`iOS[​](#directionallockenabled-ios "Direct link to directionallockenabled-ios")

When true, the ScrollView will try to lock to only vertical or horizontal scrolling while dragging.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `disableIntervalMomentum`[​](#disableintervalmomentum "Direct link to disableintervalmomentum")

When true, the scroll view stops on the next index (in relation to scroll position at release) regardless of how fast the gesture is. This can be used for pagination when the page is less than the width of the horizontal ScrollView or the height of the vertical ScrollView.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `disableScrollViewPanResponder`[​](#disablescrollviewpanresponder "Direct link to disablescrollviewpanresponder")

When true, the default JS pan responder on the ScrollView is disabled, and full control over touches inside the ScrollView is left to its child components. This is particularly useful if `snapToInterval` is enabled, since it does not follow typical touch patterns. Do not use this on regular ScrollView use cases without `snapToInterval` as it may cause unexpected touches to occur while scrolling.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `endFillColor`Android[​](#endfillcolor-android "Direct link to endfillcolor-android")

Sometimes a scrollview takes up more space than its content fills. When this is the case, this prop will fill the rest of the scrollview with a color to avoid setting a background and creating unnecessary overdraw. This is an advanced optimization that is not needed in the general case.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `fadingEdgeLength`Android[​](#fadingedgelength-android "Direct link to fadingedgelength-android")

Fades out the edges of the scroll content.

If the value is greater than `0`, the fading edges will be set accordingly to the current scroll direction and position, indicating if there is more content to show.

| Type                                            | Default |
| ----------------------------------------------- | ------- |
| number***object: `{start: number, end: number}` | `0`     |

***

### `horizontal`[​](#horizontal "Direct link to horizontal")

When `true`, the scroll view's children are arranged horizontally in a row instead of vertically in a column.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `indicatorStyle`iOS[​](#indicatorstyle-ios "Direct link to indicatorstyle-ios")

The style of the scroll indicators.

* `'default'` same as `black`.
* `'black'`, scroll indicator is `black`. This style is good against a light background.
* `'white'`, scroll indicator is `white`. This style is good against a dark background.

| Type                                    | Default     |
| --------------------------------------- | ----------- |
| enum(`'default'`, `'black'`, `'white'`) | `'default'` |

***

### `invertStickyHeaders`[​](#invertstickyheaders "Direct link to invertstickyheaders")

If sticky headers should stick at the bottom instead of the top of the ScrollView. This is usually used with inverted ScrollViews.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `keyboardDismissMode`[​](#keyboarddismissmode "Direct link to keyboarddismissmode")

Determines whether the keyboard gets dismissed in response to a drag.

* `'none'`, drags do not dismiss the keyboard.
* `'on-drag'`, the keyboard is dismissed when a drag begins.

**iOS Only**

* `'interactive'`, the keyboard is dismissed interactively with the drag and moves in synchrony with the touch, dragging upwards cancels the dismissal. On Android this is not supported and it will have the same behavior as `'none'`.

| Type                                                                                 | Default  |
| ------------------------------------------------------------------------------------ | -------- |
| enum(`'none'`, `'on-drag'`)Android***enum(`'none'`, `'on-drag'`, `'interactive'`)iOS | `'none'` |

***

### `keyboardShouldPersistTaps`[​](#keyboardshouldpersisttaps "Direct link to keyboardshouldpersisttaps")

Determines when the keyboard should stay visible after a tap.

* `'never'` tapping outside of the focused text input when the keyboard is up dismisses the keyboard. When this happens, children won't receive the tap.
* `'always'`, the keyboard will not dismiss automatically, and the scroll view will not catch taps, but children of the scroll view can catch taps.
* `'handled'`, the keyboard will not dismiss automatically when the tap was handled by children of the scroll view (or captured by an ancestor).

| Type                                     | Default   |
| ---------------------------------------- | --------- |
| enum(`'always'`, `'never'`, `'handled'`) | `'never'` |

***

### `maintainVisibleContentPosition`[​](#maintainvisiblecontentposition "Direct link to maintainvisiblecontentposition")

When set, the scroll view will adjust the scroll position so that the first child that is currently visible and at or beyond `minIndexForVisible` will not change position. This is useful for lists that are loading content in both directions, e.g. a chat thread, where new messages coming in might otherwise cause the scroll position to jump. A value of 0 is common, but other values such as 1 can be used to skip loading spinners or other content that should not maintain position.

The optional `autoscrollToTopThreshold` can be used to make the content automatically scroll to the top after making the adjustment if the user was within the threshold of the top before the adjustment was made. This is also useful for chat-like applications where you want to see new messages scroll into place, but not if the user has scrolled up a ways and it would be disruptive to scroll a bunch.

Caveat 1: Reordering elements in the scrollview with this enabled will probably cause jumpiness and jank. It can be fixed, but there are currently no plans to do so. For now, don't re-order the content of any ScrollViews or Lists that use this feature.

Caveat 2: This uses `contentOffset` and `frame.origin` in native code to compute visibility. Occlusion, transforms, and other complexity won't be taken into account as to whether content is "visible" or not.

| Type                                                                     |
| ------------------------------------------------------------------------ |
| object: `{minIndexForVisible: number, autoscrollToTopThreshold: number}` |

***

### `maximumZoomScale`iOS[​](#maximumzoomscale-ios "Direct link to maximumzoomscale-ios")

The maximum allowed zoom scale.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

### `minimumZoomScale`iOS[​](#minimumzoomscale-ios "Direct link to minimumzoomscale-ios")

The minimum allowed zoom scale.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

### `nestedScrollEnabled`Android[​](#nestedscrollenabled-android "Direct link to nestedscrollenabled-android")

Enables nested scrolling for Android API level 21+.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `onContentSizeChange`[​](#oncontentsizechange "Direct link to oncontentsizechange")

Called when scrollable content view of the ScrollView changes.

The handler function will receive two parameters: the content width and content height `(contentWidth, contentHeight)`.

It's implemented using onLayout handler attached to the content container which this ScrollView renders.

| Type     |
| -------- |
| function |

***

### `onMomentumScrollBegin`[​](#onmomentumscrollbegin "Direct link to onmomentumscrollbegin")

Called when the momentum scroll starts (scroll which occurs as the ScrollView starts gliding).

| Type     |
| -------- |
| function |

***

### `onMomentumScrollEnd`[​](#onmomentumscrollend "Direct link to onmomentumscrollend")

Called when the momentum scroll ends (scroll which occurs as the ScrollView glides to a stop).

| Type     |
| -------- |
| function |

***

### `onScroll`[​](#onscroll "Direct link to onscroll")

Fires at most once per frame during scrolling. The event has the following shape (all values with unspecified type are numbers):

JavaScript

```
{

  nativeEvent: {

    contentInset: {bottom, left, right, top},

    contentOffset: {x, y},

    contentSize: {height, width},

    layoutMeasurement: {height, width},

    velocity: {x, y},

    responderIgnoreScroll: boolean,

    zoomScale,

    // iOS only

    targetContentOffset: {x, y}

  }

}
```

| Type     |
| -------- |
| function |

***

### `onScrollBeginDrag`[​](#onscrollbegindrag "Direct link to onscrollbegindrag")

Called when the user begins to drag the scroll view.

| Type     |
| -------- |
| function |

***

### `onScrollEndDrag`[​](#onscrollenddrag "Direct link to onscrollenddrag")

Called when the user stops dragging the scroll view and it either stops or begins to glide.

| Type     |
| -------- |
| function |

***

### `onScrollToTop`iOS[​](#onscrolltotop-ios "Direct link to onscrolltotop-ios")

Fires when the scroll view scrolls to top after the status bar has been tapped.

| Type     |
| -------- |
| function |

***

### `overScrollMode`Android[​](#overscrollmode-android "Direct link to overscrollmode-android")

Used to override default value of overScroll mode.

Possible values:

* `'auto'` - Allow a user to over-scroll this view only if the content is large enough to meaningfully scroll.
* `'always'` - Always allow a user to over-scroll this view.
* `'never'` - Never allow a user to over-scroll this view.

| Type                                  | Default  |
| ------------------------------------- | -------- |
| enum(`'auto'`, `'always'`, `'never'`) | `'auto'` |

***

### `pagingEnabled`[​](#pagingenabled "Direct link to pagingenabled")

When true, the scroll view stops on multiples of the scroll view's size when scrolling. This can be used for horizontal pagination.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `persistentScrollbar`Android[​](#persistentscrollbar-android "Direct link to persistentscrollbar-android")

Causes the scrollbars not to turn transparent when they are not in use.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `pinchGestureEnabled`iOS[​](#pinchgestureenabled-ios "Direct link to pinchgestureenabled-ios")

When true, ScrollView allows use of pinch gestures to zoom in and out.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `refreshControl`[​](#refreshcontrol "Direct link to refreshcontrol")

A RefreshControl component, used to provide pull-to-refresh functionality for the ScrollView. Only works for vertical ScrollViews (`horizontal` prop must be `false`).

See [RefreshControl](/docs/refreshcontrol).

| Type    |
| ------- |
| element |

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

warning

Using this property may lead to bugs (missing content) in some circumstances - use at your own risk.

When `true`, offscreen child views are removed from their native backing superview when offscreen. This may improve scroll performance for large lists. On Android the default value is `true`.

| Type    |
| ------- |
| boolean |

***

### `scrollEnabled`[​](#scrollenabled "Direct link to scrollenabled")

When false, the view cannot be scrolled via touch interaction.

Note that the view can always be scrolled by calling `scrollTo`.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `scrollEventThrottle`[​](#scrolleventthrottle "Direct link to scrolleventthrottle")

Limits how often scroll events will be fired while scrolling, specified as a time interval in ms. This may be useful when expensive work is performed in response to scrolling. Values ≤ `16` will disable throttling, regardless of the refresh rate of the device.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

***

### `scrollIndicatorInsets`iOS[​](#scrollindicatorinsets-ios "Direct link to scrollindicatorinsets-ios")

The amount by which the scroll view indicators are inset from the edges of the scroll view. This should normally be set to the same value as the `contentInset`.

| Type                                                                 | Default                                  |
| -------------------------------------------------------------------- | ---------------------------------------- |
| object: `{top: number, left: number, bottom: number, right: number}` | `{top: 0, left: 0, bottom: 0, right: 0}` |

***

### `scrollPerfTag`Android[​](#scrollperftag-android "Direct link to scrollperftag-android")

Tag used to log scroll performance on this scroll view. Will force momentum events to be turned on (see sendMomentumEvents). This doesn't do anything out of the box and you need to implement a custom native FpsListener for it to be useful.

| Type   |
| ------ |
| string |

***

### `scrollsChildToFocus`Android[​](#scrollschildtofocus-android "Direct link to scrollschildtofocus-android")

When `true`, the ScrollView automatically scrolls to bring a focused child into view. Set to `false` to disable this behavior and take manual control of scroll position when focus changes.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `scrollToOverflowEnabled`iOS[​](#scrolltooverflowenabled-ios "Direct link to scrolltooverflowenabled-ios")

When `true`, the scroll view can be programmatically scrolled beyond its content size.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `scrollsToTop`iOS[​](#scrollstotop-ios "Direct link to scrollstotop-ios")

When `true`, the scroll view scrolls to top when the status bar is tapped.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `showsHorizontalScrollIndicator`[​](#showshorizontalscrollindicator "Direct link to showshorizontalscrollindicator")

When `true`, shows a horizontal scroll indicator.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `showsVerticalScrollIndicator`[​](#showsverticalscrollindicator "Direct link to showsverticalscrollindicator")

When `true`, shows a vertical scroll indicator.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `snapToAlignment`[​](#snaptoalignment "Direct link to snaptoalignment")

When `snapToInterval` is set, `snapToAlignment` will define the relationship of the snapping to the scroll view.

Possible values:

* `'start'` will align the snap at the left (horizontal) or top (vertical).
* `'center'` will align the snap in the center.
* `'end'` will align the snap at the right (horizontal) or bottom (vertical).

| Type                                 | Default   |
| ------------------------------------ | --------- |
| enum(`'start'`, `'center'`, `'end'`) | `'start'` |

***

### `snapToEnd`[​](#snaptoend "Direct link to snaptoend")

Use in conjunction with `snapToOffsets`. By default, the end of the list counts as a snap offset. Set `snapToEnd` to false to disable this behavior and allow the list to scroll freely between its end and the last `snapToOffsets` offset.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `snapToInterval`[​](#snaptointerval "Direct link to snaptointerval")

When set, causes the scroll view to stop at multiples of the value of `snapToInterval`. This can be used for paginating through children that have lengths smaller than the scroll view. Typically used in combination with `snapToAlignment` and `decelerationRate="fast"`. Overrides less configurable `pagingEnabled` prop.

| Type   |
| ------ |
| number |

***

### `snapToOffsets`[​](#snaptooffsets "Direct link to snaptooffsets")

When set, causes the scroll view to stop at the defined offsets. This can be used for paginating through variously sized children that have lengths smaller than the scroll view. Typically used in combination with `decelerationRate="fast"`. Overrides less configurable `pagingEnabled` and `snapToInterval` props.

| Type            |
| --------------- |
| array of number |

***

### `snapToStart`[​](#snaptostart "Direct link to snaptostart")

Use in conjunction with `snapToOffsets`. By default, the beginning of the list counts as a snap offset. Set `snapToStart` to `false` to disable this behavior and allow the list to scroll freely between its start and the first `snapToOffsets` offset.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `stickyHeaderHiddenOnScroll`[​](#stickyheaderhiddenonscroll "Direct link to stickyheaderhiddenonscroll")

When set to `true`, sticky header will be hidden when scrolling down the list, and it will dock at the top of the list when scrolling up.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `stickyHeaderIndices`[​](#stickyheaderindices "Direct link to stickyheaderindices")

An array of child indices determining which children get docked to the top of the screen when scrolling. For example, passing `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the top of the scroll view. You can also use like \[x,y,z] to make multiple items sticky when they are at the top. This property is not supported in conjunction with `horizontal={true}`.

| Type            |
| --------------- |
| array of number |

***

### `zoomScale`iOS[​](#zoomscale-ios "Direct link to zoomscale-ios")

The current scale of the scroll view content.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

## Methods[​](#methods "Direct link to Methods")

### `flashScrollIndicators()`[​](#flashscrollindicators "Direct link to flashscrollindicators")

React TSX

```
flashScrollIndicators();
```

Displays the scroll indicators momentarily.

***

### `scrollTo()`[​](#scrollto "Direct link to scrollto")

React TSX

```
scrollTo(

  options?: {x?: number, y?: number, animated?: boolean} | number,

  deprecatedX?: number,

  deprecatedAnimated?: boolean,

);
```

Scrolls to a given x, y offset, either immediately, with a smooth animation.

**Example:**

`scrollTo({x: 0, y: 0, animated: true})`

note

The weird function signature is due to the fact that, for historical reasons, the function also accepts separate arguments as an alternative to the options object. This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.

***

### `scrollToEnd()`[​](#scrolltoend "Direct link to scrolltoend")

React TSX

```
scrollToEnd(options?: {animated?: boolean});
```

    [iOS](#alwaysbouncehorizontal-ios)
  * [`alwaysBounceVertical`](#alwaysbouncevertical-ios)

    [iOS](#alwaysbouncevertical-ios)
  * [`automaticallyAdjustContentInsets`](#automaticallyadjustcontentinsets-ios)

    [iOS](#automaticallyadjustcontentinsets-ios)
  * [`automaticallyAdjustKeyboardInsets`](#automaticallyadjustkeyboardinsets-ios)

    [iOS](#automaticallyadjustkeyboardinsets-ios)
  * [`automaticallyAdjustsScrollIndicatorInsets`](#automaticallyadjustsscrollindicatorinsets-ios)

    [iOS](#automaticallyadjustsscrollindicatorinsets-ios)
  * [`bounces`](#bounces-ios)

    [iOS](#bounces-ios)
  * [`bouncesZoom`](#bounceszoom-ios)

    [iOS](#bounceszoom-ios)
  * [`canCancelContentTouches`](#cancancelcontenttouches-ios)

    [iOS](#cancancelcontenttouches-ios)
  * [`centerContent`](#centercontent-ios)

    [iOS](#centercontent-ios)
  * [`contentContainerStyle`](#contentcontainerstyle)
  * [`contentInset`](#contentinset-ios)

    [iOS](#contentinset-ios)
  * [`contentInsetAdjustmentBehavior`](#contentinsetadjustmentbehavior-ios)

    [iOS](#contentinsetadjustmentbehavior-ios)
  * [`contentOffset`](#contentoffset)
  * [`decelerationRate`](#decelerationrate)
  * [`directionalLockEnabled`](#directionallockenabled-ios)

    [iOS](#directionallockenabled-ios)
  * [`disableIntervalMomentum`](#disableintervalmomentum)
  * [`disableScrollViewPanResponder`](#disablescrollviewpanresponder)
  * [`endFillColor`](#endfillcolor-android)

    [Android](#endfillcolor-android)
  * [`fadingEdgeLength`](#fadingedgelength-android)

    [Android](#fadingedgelength-android)
  * [`horizontal`](#horizontal)
  * [`indicatorStyle`](#indicatorstyle-ios)

    [iOS](#indicatorstyle-ios)
  * [`invertStickyHeaders`](#invertstickyheaders)
  * [`keyboardDismissMode`](#keyboarddismissmode)
  * [`keyboardShouldPersistTaps`](#keyboardshouldpersisttaps)
  * [`maintainVisibleContentPosition`](#maintainvisiblecontentposition)
  * [`maximumZoomScale`](#maximumzoomscale-ios)

    [iOS](#maximumzoomscale-ios)
  * [`minimumZoomScale`](#minimumzoomscale-ios)

    [iOS](#minimumzoomscale-ios)
  * [`nestedScrollEnabled`](#nestedscrollenabled-android)

    [Android](#nestedscrollenabled-android)

    [iOS](#onscrolltotop-ios)
  * [`overScrollMode`](#overscrollmode-android)

    [Android](#overscrollmode-android)
  * [`pagingEnabled`](#pagingenabled)
  * [`persistentScrollbar`](#persistentscrollbar-android)

    [Android](#persistentscrollbar-android)
  * [`pinchGestureEnabled`](#pinchgestureenabled-ios)

    [iOS](#pinchgestureenabled-ios)
  * [`refreshControl`](#refreshcontrol)
  * [`removeClippedSubviews`](#removeclippedsubviews)
  * [`scrollEnabled`](#scrollenabled)
  * [`scrollEventThrottle`](#scrolleventthrottle)
  * [`scrollIndicatorInsets`](#scrollindicatorinsets-ios)

    [iOS](#scrollindicatorinsets-ios)
  * [`scrollPerfTag`](#scrollperftag-android)

    [Android](#scrollperftag-android)
  * [`scrollsChildToFocus`](#scrollschildtofocus-android)

    [Android](#scrollschildtofocus-android)
  * [`scrollToOverflowEnabled`](#scrolltooverflowenabled-ios)

    [iOS](#scrolltooverflowenabled-ios)
  * [`scrollsToTop`](#scrollstotop-ios)

    [iOS](#scrollstotop-ios)

    [iOS](#zoomscale-ios)

* [Methods](#methods)

  * [`flashScrollIndicators()`](#flashscrollindicators)
  * [`scrollTo()`](#scrollto)
  * [`scrollToEnd()`](#scrolltoend)

----
url: https://reactnative.dev/docs/next/global-URL
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-URL)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/URL) for more information.

The global `URL` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/the-new-architecture/advanced-topics-components
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/advanced-topics-components)** (0.87).

Version: Next

This document contains a set of advanced topics to implement more complex functionalities of Native Components. It is recommended to first read the [Codegen](/docs/the-new-architecture/what-is-codegen) section and the guides on [Native Components](/docs/fabric-native-components-introduction).

This guide will cover the following topics:

* [Direct Manipulation](/docs/the-new-architecture/direct-manipulation-new-architecture)
* [Measuring the Layout](/docs/the-new-architecture/layout-measurements)
* [Invoking native functions on your native component](/docs/next/the-new-architecture/fabric-component-native-commands)

----
url: https://reactnative.dev/docs/set-up-your-environment
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

In this guide, you'll learn how to set up your environment, so that you can run your project with Android Studio and Xcode. This will allow you to develop with Android emulators and iOS simulators, build your app locally, and more.

info

This guide requires Android Studio or Xcode. If you already have one of these programs installed, you should be able to get up and running within a few minutes. If they are not installed, you should expect to spend about an hour installing and configuring them.

Is setting up my environment required?

Setting up your environment is not required if you're using a [Framework](/architecture/glossary#react-native-framework). With a React Native Framework, you don't need to set up Android Studio or Xcode as it will take care of building the native app for you

If you have constraints that prevent you from using a Framework, or you'd like to write your own Framework, then setting up your local environment is a requirement. After your environment is set up, learn how to [get started without a framework](/docs/getting-started-without-a-framework).

```
brew install node

brew install watchman
```

If you have already installed Node on your system, make sure it is Node 22.11.0 or newer.

[Watchman](https://facebook.github.io/watchman) is a tool by Facebook for watching changes in the filesystem. It is highly recommended you install it for better performance.

### Java Development Kit

We recommend installing the OpenJDK distribution called Azul **Zulu** using [Homebrew](https://brew.sh/). Run the following commands in a Terminal after installing Homebrew:

```
brew install --cask zulu@17



# Get path to where cask was installed to find the JDK installer

brew info --cask zulu@17



# ==> zulu@17: <version number>

# https://www.azul.com/downloads/

# Installed

# /opt/homebrew/Caskroom/zulu@17/<version number> (185.8MB) (note that the path is /usr/local/Caskroom on non-Apple Silicon Macs)

# Installed using the formulae.brew.sh API on 2024-06-06 at 10:00:00



# Navigate to the folder

open /opt/homebrew/Caskroom/zulu@17/<version number> # or /usr/local/Caskroom/zulu@17/<version number>
```

After opening Finder, double click the `Double-Click to Install Azul Zulu JDK 17.pkg` package to install the JDK.

After the JDK installation, add or update your `JAVA_HOME` environment variable in `~/.zshrc` (or in `~/.bash_profile`).

If you used above steps, JDK will likely be located at `/Library/Java/JavaVirtualMachines/zulu-17.jdk/Contents/Home`:

```
export JAVA_HOME=/Library/Java/JavaVirtualMachines/zulu-17.jdk/Contents/Home
```

```
export ANDROID_HOME=$HOME/Library/Android/sdk

export PATH=$PATH:$ANDROID_HOME/emulator

export PATH=$PATH:$ANDROID_HOME/platform-tools
```

If you have a physical Android device, you can use it for development in place of an AVD by plugging it in to your computer using a USB cable and following the instructions [here](/docs/running-on-device).

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/getting-started).

## Installing dependencies[​](#installing-dependencies "Direct link to Installing dependencies")

You will need Node, Watchman, the React Native command line interface, Xcode and CocoaPods.

While you can use any editor of your choice to develop your app, you will need to install Xcode in order to set up the necessary tooling to build your React Native app for iOS.

### Node & Watchman[​](#node--watchman "Direct link to Node & Watchman")

We recommend installing Node and Watchman using [Homebrew](https://brew.sh/). Run the following commands in a Terminal after installing Homebrew:

```
brew install node

brew install watchman
```

```
export NVM_DIR="$HOME/.nvm"

[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
```

You might also want to ensure that all "shell script build phase" of your Xcode project, is using `/bin/zsh` as its shell.

### That's it!

Congratulations! You successfully set up your development environment.

## Now what?

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/getting-started).

```
choco install -y nodejs-lts microsoft-openjdk17
```

```
%LOCALAPPDATA%\Android\Sdk
```

```
%LOCALAPPDATA%\Android\Sdk\platform-tools
```

## Preparing the Android device

You will need an Android device to run your React Native Android app. This can be either a physical Android device, or more commonly, you can use an Android Virtual Device which allows you to emulate an Android device on your computer.

Either way, you will need to prepare the device to run Android apps for development.

### Using a physical device

If you have a physical Android device, you can use it for development in place of an AVD by plugging it in to your computer using a USB cable and following the instructions [here](/docs/running-on-device).

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/getting-started).

## Unsupported[​](#unsupported "Direct link to Unsupported")

info

A Mac is required to build projects with native code for iOS. You can use [Expo Go](https://expo.dev/go) from [Expo](/docs/environment-setup#start-a-new-react-native-project-with-expo) to develop your app on your iOS device.

```
export ANDROID_HOME=$HOME/Android/Sdk

export PATH=$PATH:$ANDROID_HOME/emulator

export PATH=$PATH:$ANDROID_HOME/platform-tools
```

If you have a physical Android device, you can use it for development in place of an AVD by plugging it in to your computer using a USB cable and following the instructions [here](/docs/running-on-device).

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/getting-started).

## Unsupported[​](#unsupported-1 "Direct link to Unsupported")

info

A Mac is required to build projects with native code for iOS. You can use [Expo Go](https://expo.dev/go) from [Expo](/docs/environment-setup#start-a-new-react-native-project-with-expo) to develop your app on your iOS device.

----
url: https://reactnative.dev/docs/troubleshooting
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

These are some common issues you may run into while setting up React Native. If you encounter something that is not listed here, try [searching for the issue in GitHub](https://github.com/react/react-native/issues/).

### Port already in use[​](#port-already-in-use "Direct link to Port already in use")

The [Metro bundler](https://metrobundler.dev/) runs on port 8081. If another process is already using that port, you can either terminate that process, or change the port that the bundler uses.

#### Terminating a process on port 8081[​](#terminating-a-process-on-port-8081 "Direct link to Terminating a process on port 8081")

Run the following command to find the id for the process that is listening on port 8081:

```
sudo lsof -i :8081
```

Then run the following to terminate the process:

```
kill -9 <PID>
```

On Windows you can find the process using port 8081 using [Resource Monitor](https://stackoverflow.com/questions/48198/how-can-you-find-out-which-process-is-listening-on-a-port-on-windows) and stop it using Task Manager.

#### Using a port other than 8081[​](#using-a-port-other-than-8081 "Direct link to Using a port other than 8081")

You can configure the bundler to use a port other than 8081 by using the `port` parameter, from the root of your project run:

* npm
* Yarn

```
npm start -- --port=8088
```

```
yarn start --port 8088
```

You will also need to update your applications to load the JavaScript bundle from the new port. If running on device from Xcode, you can do this by updating occurrences of `8081` to your chosen port in the `ios/__App_Name__.xcodeproj/project.pbxproj` file.

### NPM locking error[​](#npm-locking-error "Direct link to NPM locking error")

If you encounter an error such as `npm WARN locking Error: EACCES` while using the React Native CLI, try running the following:

```
sudo chown -R $USER ~/.npm

sudo chown -R $USER /usr/local/lib/node_modules
```

### Missing libraries for React[​](#missing-libraries-for-react "Direct link to Missing libraries for React")

If you added React Native manually to your project, make sure you have included all the relevant dependencies that you are using, like `RCTText.xcodeproj`, `RCTImage.xcodeproj`. Next, the binaries built by these dependencies have to be linked to your app binary. Use the `Linked Frameworks and Binaries` section in the Xcode project settings. More detailed steps are here: [Linking Libraries](/docs/linking-libraries-ios).

If you are using CocoaPods, verify that you have added React along with the subspecs to the `Podfile`. For example, if you were using the `<Text />`, `<Image />` and `fetch()` APIs, you would need to add these in your `Podfile`:

```
pod 'React', :path => '../node_modules/react-native', :subspecs => [

  'RCTText',

  'RCTImage',

  'RCTNetwork',

  'RCTWebSocket',

]
```

```
import Firebase from 'firebase';
```

## Shell Command Unresponsive Exception[​](#shell-command-unresponsive-exception "Direct link to Shell Command Unresponsive Exception")

If you encounter a ShellCommandUnresponsiveException exception such as:

```
Execution failed for task ':app:installDebug'.

  com.android.builder.testing.api.DeviceException: com.android.ddmlib.ShellCommandUnresponsiveException
```

Restart the ADB server by running the following commands in your terminal:

```
adb kill-server

adb start-server
```

## Unable to start react-native package manager (on Linux)[​](#unable-to-start-react-native-package-manager-on-linux "Direct link to Unable to start react-native package manager (on Linux)")

### Case 1: Error "code":"ENOSPC","errno":"ENOSPC"[​](#case-1-error-codeenospcerrnoenospc "Direct link to Case 1: Error \"code\":\"ENOSPC\",\"errno\":\"ENOSPC\"")

Issue caused by the number of directories [inotify](https://github.com/guard/listen/blob/master/README.md#increasing-the-amount-of-inotify-watchers) (used by watchman on Linux) can monitor. To solve it, run this command in your terminal window

```
echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
```

----
url: https://reactnative.dev/docs/next/headless-js-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/headless-js-android)** (0.87).

Version: Next

Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.

## The JS API[​](#the-js-api "Direct link to The JS API")

A task is an async function that you register on `AppRegistry`, similar to registering React applications:

React TSX

```
import {AppRegistry} from 'react-native';

AppRegistry.registerHeadlessTask('SomeTaskName', () =>

  require('SomeTaskName'),

);
```

Then, in `SomeTaskName.js`:

React TSX

```
module.exports = async taskData => {

  // do stuff

};
```

You can do anything in your task such as network requests, timers and so on, as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved), React Native will go into "paused" mode (unless there are other tasks running, or there is a foreground app).

## The Platform API[​](#the-platform-api "Direct link to The Platform API")

Yes, this does still require some native code, but it's pretty thin. You need to extend `HeadlessJsTaskService` and override `getTaskConfig`, e.g.:

* Java
* Kotlin

Java

```
package com.your_application_name;



import android.content.Intent;

import android.os.Bundle;

import com.facebook.react.HeadlessJsTaskService;

import com.facebook.react.bridge.Arguments;

import com.facebook.react.jstasks.HeadlessJsTaskConfig;

import javax.annotation.Nullable;



public class MyTaskService extends HeadlessJsTaskService {



  @Override

  protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {

    Bundle extras = intent.getExtras();

    if (extras != null) {

      return new HeadlessJsTaskConfig(

          "SomeTaskName",

          Arguments.fromBundle(extras),

          5000, // timeout in milliseconds for the task

          false // optional: defines whether or not the task is allowed in foreground. Default is false

        );

    }

    return null;

  }

}
```

Kotlin

```
package com.your_application_name;



import android.content.Intent

import com.facebook.react.HeadlessJsTaskService

import com.facebook.react.bridge.Arguments

import com.facebook.react.jstasks.HeadlessJsTaskConfig



class MyTaskService : HeadlessJsTaskService() {

    override fun getTaskConfig(intent: Intent?): HeadlessJsTaskConfig? {

        return intent.extras?.let {

            HeadlessJsTaskConfig(

                "SomeTaskName",

                Arguments.fromBundle(it),

                5000, // timeout for the task

                false // optional: defines whether or not the task is allowed in foreground.

                // Default is false

            )

        }

    }

}
```

Then add the service to your `AndroidManifest.xml` file inside the `application` tag:

XML

```
<service android:name="com.example.MyTaskService" />
```

Now, whenever you [start your service](https://developer.android.com/reference/android/content/Context.html#startService\(android.content.Intent\)), e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down.

Example:

* Java
* Kotlin

Java

```
Intent service = new Intent(getApplicationContext(), MyTaskService.class);

Bundle bundle = new Bundle();



bundle.putString("foo", "bar");

service.putExtras(bundle);



getApplicationContext().startForegroundService(service);
```

Kotlin

```
val service = Intent(applicationContext, MyTaskService::class.java)

val bundle = Bundle()



bundle.putString("foo", "bar")



service.putExtras(bundle)



applicationContext.startForegroundService(service)
```

## Retries[​](#retries "Direct link to Retries")

By default, the headless JS task will not perform any retries. In order to do so, you need to create a `HeadlessJsRetryPolicy` and throw a specific `Error`.

`LinearCountingRetryPolicy` is an implementation of `HeadlessJsRetryPolicy` that allows you to specify a maximum number of retries with a fixed delay between each attempt. If that does not suit your needs then you can implement your own `HeadlessJsRetryPolicy`. These policies can be passed as an extra argument to the `HeadlessJsTaskConfig` constructor, e.g.

* Java
* Kotlin

Java

```
HeadlessJsRetryPolicy retryPolicy = new LinearCountingRetryPolicy(

  3, // Max number of retry attempts

  1000 // Delay between each retry attempt

);



return new HeadlessJsTaskConfig(

  'SomeTaskName',

  Arguments.fromBundle(extras),

  5000,

  false,

  retryPolicy

);
```

Kotlin

```
val retryPolicy: HeadlessJsTaskRetryPolicy =

    LinearCountingRetryPolicy(

        3, // Max number of retry attempts

        1000 // Delay between each retry attempt

    )



return HeadlessJsTaskConfig("SomeTaskName", Arguments.fromBundle(extras), 5000, false, retryPolicy)
```

A retry attempt will only be made when a specific `Error` is thrown. Inside a headless JS task, you can import the error and throw it when a retry attempt is required.

Example:

React TSX

```
import {HeadlessJsTaskError} from 'HeadlessJsTask';



module.exports = async taskData => {

  const condition = ...;

  if (!condition) {

    throw new HeadlessJsTaskError();

  }

};
```

```
<receiver android:name=".NetworkChangeReceiver" >

  <intent-filter>

    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

  </intent-filter>

</receiver>
```

Broadcast receiver then handles intent that was broadcasted in onReceive function. This is a great place to check whether your app is on foreground or not. If app is not on foreground we can prepare our intent to be started, with no information or additional information bundled using `putExtra` (keep in mind bundle can handle only parcelable values). In the end service is started and wakelock is acquired.

* Java
* Kotlin

Java

```
import android.app.ActivityManager;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.net.ConnectivityManager;

import android.net.Network;

import android.net.NetworkCapabilities;

import android.net.NetworkInfo;

import android.os.Build;



import com.facebook.react.HeadlessJsTaskService;



public class NetworkChangeReceiver extends BroadcastReceiver {



    @Override

    public void onReceive(final Context context, final Intent intent) {

        /**

         This part will be called every time network connection is changed

         e.g. Connected -> Not Connected

         **/

        if (!isAppOnForeground((context))) {

            /**

             We will start our service and send extra info about

             network connections

             **/

            boolean hasInternet = isNetworkAvailable(context);

            Intent serviceIntent = new Intent(context, MyTaskService.class);

            serviceIntent.putExtra("hasInternet", hasInternet);

            context.startForegroundService(serviceIntent);

            HeadlessJsTaskService.acquireWakeLockNow(context);

        }

    }



    private boolean isAppOnForeground(Context context) {

        /**

         We need to check if app is in foreground otherwise the app will crash.

         https://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not

         **/

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningAppProcessInfo> appProcesses =

                activityManager.getRunningAppProcesses();

        if (appProcesses == null) {

            return false;

        }

        final String packageName = context.getPackageName();

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {

            if (appProcess.importance ==

                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&

                    appProcess.processName.equals(packageName)) {

                return true;

            }

        }

        return false;

    }



    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager cm = (ConnectivityManager)

                context.getSystemService(Context.CONNECTIVITY_SERVICE);



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            Network networkCapabilities = cm.getActiveNetwork();



            if(networkCapabilities == null) {

                return false;

            }



            NetworkCapabilities actNw = cm.getNetworkCapabilities(networkCapabilities);



            if(actNw == null) {

                return false;

            }



            if(actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {

                return true;

            }



            return false;

        }



        // deprecated in API level 29

        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        return (netInfo != null && netInfo.isConnected());

    }

}
```

Kotlin

```
import android.app.ActivityManager

import android.app.ActivityManager.RunningAppProcessInfo

import android.content.BroadcastReceiver

import android.content.Context

import android.content.Intent

import android.net.ConnectivityManager

import android.net.NetworkCapabilities

import android.os.Build

import com.facebook.react.HeadlessJsTaskService



class NetworkChangeReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent?) {

        /**

         * This part will be called every time network connection is changed e.g. Connected -> Not

         * Connected

         */

        if (!isAppOnForeground(context)) {

            /** We will start our service and send extra info about network connections */

            val hasInternet = isNetworkAvailable(context)

            val serviceIntent = Intent(context, MyTaskService::class.java)

            serviceIntent.putExtra("hasInternet", hasInternet)

            context.startForegroundService(serviceIntent)

            HeadlessJsTaskService.acquireWakeLockNow(context)

        }

    }



    private fun isAppOnForeground(context: Context): Boolean {

        /**

         * We need to check if app is in foreground otherwise the app will crash.

         * https://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not

         */

        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

        val appProcesses = activityManager.runningAppProcesses ?: return false

        val packageName: String = context.getPackageName()

        for (appProcess in appProcesses) {

            if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&

                    appProcess.processName == packageName

            ) {

                return true

            }

        }

        return false

    }



    companion object {

        fun isNetworkAvailable(context: Context): Boolean {

            val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

            var result = false



            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                val networkCapabilities = cm.activeNetwork ?: return false



                val actNw = cm.getNetworkCapabilities(networkCapabilities) ?: return false



                result =

                    when {

                        actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true

                        actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true

                        actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true

                        else -> false

                    }



                return result

            } else {

                cm.run {

                    // deprecated in API level 29

                    cm.activeNetworkInfo?.run {

                        result =

                            when (type) {

                                ConnectivityManager.TYPE_WIFI -> true

                                ConnectivityManager.TYPE_MOBILE -> true

                                ConnectivityManager.TYPE_ETHERNET -> true

                                else -> false

                            }

                    }

                }

            }

            return result

        }

    }

}
```

* [The JS API](#the-js-api)
* [The Platform API](#the-platform-api)
* [Retries](#retries)
* [Caveats](#caveats)
* [Example Usage](#example-usage)

----
url: https://reactnative.dev/docs/dropshadowvalue
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The `DropShadowValue` object is taken by the [`filter`](/docs/view-style-props#filter) style prop for the `dropShadow` function. It is comprised of 2 or 3 lengths and an optional color. These values collectively define the drop shadow's color, position, and blurriness.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

  offsetX: 10,

  offsetY: -3,

  standardDeviation: '15px',

  color: 'blue',

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `offsetX`[​](#offsetx "Direct link to offsetx")

The offset on the x-axis. This can be positive or negative. A positive value indicates right and negative indicates left.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | No       |

### `offsetY`[​](#offsety "Direct link to offsety")

The offset on the y-axis. This can be positive or negative. A positive value indicates up and negative indicates down.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | No       |

### `standardDeviation`[​](#standarddeviation "Direct link to standarddeviation")

Represents the standard deviation used in the [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) algorithm. The larger the value the blurrier the shadow is. Only non-negative values are valid. The default is 0.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | Yes      |

### `color`[​](#color "Direct link to color")

The color of the shadow. The default is `black`.

| Type                  | Optional |
| --------------------- | -------- |
| [color](/docs/colors) | Yes      |

## Used by[​](#used-by "Direct link to Used by")

* [`filter`](/docs/view-style-props#filter)

----
url: https://reactnative.dev/docs/layout-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

info

More detailed examples about those properties can be found on the [Layout with Flexbox](/docs/flexbox) page.

### Example[​](#example "Direct link to Example")

The following example shows how different properties can affect or shape a React Native layout. You can try for example to add or remove squares from the UI while changing the values of the property `flexWrap`.

* TypeScript
* JavaScript

***

# Reference

## Props[​](#props "Direct link to Props")

### `alignContent`[​](#aligncontent "Direct link to aligncontent")

`alignContent` controls how rows align in the cross direction, overriding the `alignContent` of the parent.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content) for more details.

| Type                                                                                                 | Required |
| ---------------------------------------------------------------------------------------------------- | -------- |
| enum('flex-start', 'flex-end', 'center', 'stretch', 'space-between', 'space-around', 'space-evenly') | No       |

***

### `alignItems`[​](#alignitems "Direct link to alignitems")

`alignItems` aligns children in the cross direction. For example, if children are flowing vertically, `alignItems` controls how they align horizontally. It works like `align-items` in CSS (default: stretch).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items) for more details.

| Type                                                            | Required |
| --------------------------------------------------------------- | -------- |
| enum('flex-start', 'flex-end', 'center', 'stretch', 'baseline') | No       |

***

### `alignSelf`[​](#alignself "Direct link to alignself")

`alignSelf` controls how a child aligns in the cross direction, overriding the `alignItems` of the parent. It works like `align-self` in CSS (default: auto).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self) for more details.

| Type                                                                    | Required |
| ----------------------------------------------------------------------- | -------- |
| enum('auto', 'flex-start', 'flex-end', 'center', 'stretch', 'baseline') | No       |

***

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `borderBottomWidth`[​](#borderbottomwidth "Direct link to borderbottomwidth")

`borderBottomWidth` works like `border-bottom-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderEndWidth`[​](#borderendwidth "Direct link to borderendwidth")

When direction is `ltr`, `borderEndWidth` is equivalent to `borderRightWidth`. When direction is `rtl`, `borderEndWidth` is equivalent to `borderLeftWidth`.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderLeftWidth`[​](#borderleftwidth "Direct link to borderleftwidth")

`borderLeftWidth` works like `border-left-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderRightWidth`[​](#borderrightwidth "Direct link to borderrightwidth")

`borderRightWidth` works like `border-right-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderStartWidth`[​](#borderstartwidth "Direct link to borderstartwidth")

When direction is `ltr`, `borderStartWidth` is equivalent to `borderLeftWidth`. When direction is `rtl`, `borderStartWidth` is equivalent to `borderRightWidth`.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderTopWidth`[​](#bordertopwidth "Direct link to bordertopwidth")

`borderTopWidth` works like `border-top-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `borderWidth`[​](#borderwidth "Direct link to borderwidth")

`borderWidth` works like `border-width` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/border-width) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `bottom`[​](#bottom "Direct link to bottom")

`bottom` is the number of logical pixels to offset the bottom edge of this component.

It works similarly to `bottom` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/bottom) for more details of how `bottom` affects layout.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `boxSizing`[​](#boxsizing "Direct link to boxsizing")

`boxSizing` defines how the element's various sizing props (`width`, `height`, `minWidth`, `minHeight`, etc.) are computed. If `boxSizing` is `border-box`, these sizes apply to the border box of the element. If it is `content-box`, they apply to the content box of the element. The default value is `border-box`. The [web documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) is a good source of information if you wish to learn more about how this prop works.

| Type                              | Required |
| --------------------------------- | -------- |
| enum('border-box', 'content-box') | No       |

***

### `columnGap`[​](#columngap "Direct link to columngap")

`columnGap` works like `column-gap` in CSS. It accepts numbers (in points) or percentage strings (e.g. `'10%'`). Percentage values are supported on the [New Architecture](/architecture/landing-page).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/column-gap) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `direction`[​](#direction "Direct link to direction")

`direction` specifies the directional flow of the user interface. The default is `inherit`, except for root node which will have value based on the current locale.

See [MDN CSS Reference](https://www.yogalayout.dev/docs/styling/layout-direction) for more details.

| Type                          | Required |
| ----------------------------- | -------- |
| enum('inherit', 'ltr', 'rtl') | No       |

***

### `display`[​](#display "Direct link to display")

`display` sets the display type of this component.

It works similarly to `display` in CSS but only supports the values 'flex', 'none', and 'contents'. The default is `flex`.

| Type                             | Required |
| -------------------------------- | -------- |
| enum('none', 'flex', 'contents') | No       |

***

### `end`[​](#end "Direct link to end")

When the direction is `ltr`, `end` is equivalent to `right`. When the direction is `rtl`, `end` is equivalent to `left`.

This style takes precedence over the `left` and `right` styles.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `flex`[​](#flex "Direct link to flex")

In React Native `flex` does not work the same way that it does in CSS. `flex` is a number rather than a string, and it works according to the [Yoga](https://github.com/facebook/yoga) layout engine.

When `flex` is a positive number, it makes the component flexible, and it will be sized proportional to its flex value. So a component with `flex` set to `2` will take twice the space as a component with `flex` set to 1. `flex: <positive number>` equates to `flexGrow: <positive number>, flexShrink: 1, flexBasis: 0`.

When `flex` is `0`, the component is sized according to `width` and `height`, and it is inflexible.

When `flex` is `-1`, the component is normally sized according to `width` and `height`. However, if there's not enough space, the component will shrink to its `minWidth` and `minHeight`.

`flexGrow`, `flexShrink`, and `flexBasis` work the same as in CSS.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `flexBasis`[​](#flexbasis "Direct link to flexbasis")

`flexBasis` is an axis-independent way of providing the default size of an item along the main axis. Setting the `flexBasis` of a child is similar to setting the `width` of that child if its parent is a container with `flexDirection: row` or setting the `height` of a child if its parent is a container with `flexDirection: column`. The `flexBasis` of an item is the default size of that item, the size of the item before any `flexGrow` and `flexShrink` calculations are performed.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `flexDirection`[​](#flexdirection "Direct link to flexdirection")

`flexDirection` controls which directions children of a container go. `row` goes left to right, `column` goes top to bottom, and you may be able to guess what the other two do. It works like `flex-direction` in CSS, except the default is `column`.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction) for more details.

| Type                                                   | Required |
| ------------------------------------------------------ | -------- |
| enum('row', 'row-reverse', 'column', 'column-reverse') | No       |

***

### `flexGrow`[​](#flexgrow "Direct link to flexgrow")

`flexGrow` describes how any space within a container should be distributed among its children along the main axis. After laying out its children, a container will distribute any remaining space according to the flex grow values specified by its children.

`flexGrow` accepts any floating point value >= 0, with 0 being the default value. A container will distribute any remaining space among its children weighted by the children’s `flexGrow` values.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `flexShrink`[​](#flexshrink "Direct link to flexshrink")

[`flexShrink`](/docs/layout-props#flexshrink) describes how to shrink children along the main axis in the case in which the total size of the children overflows the size of the container on the main axis. `flexShrink` is very similar to `flexGrow` and can be thought of in the same way if any overflowing size is considered to be negative remaining space. These two properties also work well together by allowing children to grow and shrink as needed.

`flexShrink` accepts any floating point value >= 0, with 0 being the default value. A container will shrink its children weighted by the children’s `flexShrink` values.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `flexWrap`[​](#flexwrap "Direct link to flexwrap")

`flexWrap` controls whether children can wrap around after they hit the end of a flex container. It works like `flex-wrap` in CSS (default: nowrap).

Note it does not work anymore with `alignItems: stretch` (the default), so you may want to use `alignItems: flex-start` for example (breaking change details: <https://github.com/react/react-native/releases/tag/v0.28.0>).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap) for more details.

| Type                                   | Required |
| -------------------------------------- | -------- |
| enum('wrap', 'nowrap', 'wrap-reverse') | No       |

***

### `gap`[​](#gap "Direct link to gap")

`gap` works like `gap` in CSS. It is a shorthand for `rowGap` and `columnGap`. It accepts numbers (in points) or percentage strings (e.g. `'10%'`). Percentage values are supported on the [New Architecture](/architecture/landing-page).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/gap) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `height`[​](#height "Direct link to height")

`height` sets the height of this component.

It works similarly to `height` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/height) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `inset`[​](#inset "Direct link to inset")

note

`inset` is only available on the [New Architecture](/architecture/landing-page)

Setting `inset` has the same effect as setting each of `top`, `bottom`, `right` and `left` props.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/inset) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetBlock`[​](#insetblock "Direct link to insetblock")

note

`insetBlock` is only available on the [New Architecture](/architecture/landing-page)

Equivalent to [`top`](/docs/layout-props#top) and [`bottom`](/docs/layout-props#bottom).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetBlockEnd`[​](#insetblockend "Direct link to insetblockend")

note

`insetBlockEnd` is only available on the [New Architecture](/architecture/landing-page)

Equivalent to [`bottom`](/docs/layout-props#bottom).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetBlockStart`[​](#insetblockstart "Direct link to insetblockstart")

note

`insetBlockStart` is only available on the [New Architecture](/architecture/landing-page)

Equivalent to [`top`](/docs/layout-props#top).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetInline`[​](#insetinline "Direct link to insetinline")

note

`insetInline` is only available on the [New Architecture](/architecture/landing-page)

Equivalent to [`right`](/docs/layout-props#right) and [`left`](/docs/layout-props#left).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetInlineEnd`[​](#insetinlineend "Direct link to insetinlineend")

note

`insetInlineEnd` is only available on the [New Architecture](/architecture/landing-page)

When direction is `ltr`, `insetInlineEnd` is equivalent to [`right`](/docs/layout-props#right). When direction is `rtl`, `insetInlineEnd` is equivalent to [`left`](/docs/layout-props#left).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `insetInlineStart`[​](#insetinlinestart "Direct link to insetinlinestart")

note

`insetInlineStart` is only available on the [New Architecture](/architecture/landing-page)

When direction is `ltr`, `insetInlineStart` is equivalent to [`left`](/docs/layout-props#left). When direction is `rtl`, `insetInlineStart` is equivalent to [`right`](/docs/layout-props#right).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

| Type                    | Required |
| ----------------------- | -------- |
| enum('auto', 'isolate') | No       |

***

### `justifyContent`[​](#justifycontent "Direct link to justifycontent")

`justifyContent` aligns children in the main direction. For example, if children are flowing vertically, `justifyContent` controls how they align vertically. It works like `justify-content` in CSS (default: flex-start).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) for more details.

| Type                                                                                      | Required |
| ----------------------------------------------------------------------------------------- | -------- |
| enum('flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly') | No       |

***

### `left`[​](#left "Direct link to left")

`left` is the number of logical pixels to offset the left edge of this component.

It works similarly to `left` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/left) for more details of how `left` affects layout.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `margin`[​](#margin "Direct link to margin")

Setting `margin` has the same effect as setting each of `marginTop`, `marginLeft`, `marginBottom`, and `marginRight`.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginBottom`[​](#marginbottom "Direct link to marginbottom")

`marginBottom` works like `margin-bottom` in CSS. See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginBlock`[​](#marginblock "Direct link to marginblock")

Equivalent to [`marginVertical`](/docs/layout-props#marginvertical).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-block) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginBlockEnd`[​](#marginblockend "Direct link to marginblockend")

Equivalent to [`marginBottom`](/docs/layout-props#marginbottom).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-block-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginBlockStart`[​](#marginblockstart "Direct link to marginblockstart")

Equivalent to [`marginTop`](/docs/layout-props#margintop).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-block-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginEnd`[​](#marginend "Direct link to marginend")

When direction is `ltr`, `marginEnd` is equivalent to `marginRight`. When direction is `rtl`, `marginEnd` is equivalent to `marginLeft`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginHorizontal`[​](#marginhorizontal "Direct link to marginhorizontal")

Setting `marginHorizontal` has the same effect as setting both `marginLeft` and `marginRight`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginInline`[​](#margininline "Direct link to margininline")

Equivalent to [`marginHorizontal`](/docs/layout-props#marginhorizontal).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-inline) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginInlineEnd`[​](#margininlineend "Direct link to margininlineend")

When direction is `ltr`, `marginInlineEnd` is equivalent to [`marginEnd`](/docs/layout-props#marginend) (i.e. `marginRight`). When direction is `rtl`, `marginInlineEnd` is equivalent to [`marginEnd`](/docs/layout-props#marginend) (i.e. `marginLeft`).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-inline-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginInlineStart`[​](#margininlinestart "Direct link to margininlinestart")

When direction is `ltr`, `marginInlineStart` is equivalent to [`marginStart`](/docs/layout-props#marginstart) (i.e. `marginLeft`). When direction is `rtl`, `marginInlineStart` is equivalent to [`marginStart`](/docs/layout-props#marginstart) (i.e. `marginRight`).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/margin-inline-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginLeft`[​](#marginleft "Direct link to marginleft")

`marginLeft` works like `margin-left` in CSS. See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginRight`[​](#marginright "Direct link to marginright")

`marginRight` works like `margin-right` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginStart`[​](#marginstart "Direct link to marginstart")

When direction is `ltr`, `marginStart` is equivalent to `marginLeft`. When direction is `rtl`, `marginStart` is equivalent to `marginRight`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginTop`[​](#margintop "Direct link to margintop")

`marginTop` works like `margin-top` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/margin-top) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `marginVertical`[​](#marginvertical "Direct link to marginvertical")

Setting `marginVertical` has the same effect as setting both `marginTop` and `marginBottom`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `maxHeight`[​](#maxheight "Direct link to maxheight")

`maxHeight` is the maximum height for this component, in logical pixels.

It works similarly to `max-height` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-height) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `maxWidth`[​](#maxwidth "Direct link to maxwidth")

`maxWidth` is the maximum width for this component, in logical pixels.

It works similarly to `max-width` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/max-width) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `minHeight`[​](#minheight "Direct link to minheight")

`minHeight` is the minimum height for this component, in logical pixels.

It works similarly to `min-height` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-height) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `minWidth`[​](#minwidth "Direct link to minwidth")

`minWidth` is the minimum width for this component, in logical pixels.

It works similarly to `min-width` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/min-width) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `overflow`[​](#overflow "Direct link to overflow")

`overflow` controls how children are measured and displayed. `overflow: hidden` causes views to be clipped while `overflow: scroll` causes views to be measured independently of their parents' main axis. It works like `overflow` in CSS (default: visible).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) for more details.

| Type                                | Required |
| ----------------------------------- | -------- |
| enum('visible', 'hidden', 'scroll') | No       |

***

### `padding`[​](#padding "Direct link to padding")

Setting `padding` has the same effect as setting each of `paddingTop`, `paddingBottom`, `paddingLeft`, and `paddingRight`.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingBottom`[​](#paddingbottom "Direct link to paddingbottom")

`paddingBottom` works like `padding-bottom` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-bottom) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingBlock`[​](#paddingblock "Direct link to paddingblock")

Equivalent to [`paddingVertical`](/docs/layout-props#paddingvertical).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-block) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingBlockEnd`[​](#paddingblockend "Direct link to paddingblockend")

Equivalent to [`paddingBottom`](/docs/layout-props#paddingbottom).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-block-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingBlockStart`[​](#paddingblockstart "Direct link to paddingblockstart")

Equivalent to [`paddingTop`](/docs/layout-props#paddingtop).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-block-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingEnd`[​](#paddingend "Direct link to paddingend")

When direction is `ltr`, `paddingEnd` is equivalent to `paddingRight`. When direction is `rtl`, `paddingEnd` is equivalent to `paddingLeft`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingHorizontal`[​](#paddinghorizontal "Direct link to paddinghorizontal")

Setting `paddingHorizontal` is like setting both of `paddingLeft` and `paddingRight`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingInline`[​](#paddinginline "Direct link to paddinginline")

Equivalent to [`paddingHorizontal`](/docs/layout-props#paddinghorizontal).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-inline) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingInlineEnd`[​](#paddinginlineend "Direct link to paddinginlineend")

When direction is `ltr`, `paddingInlineEnd` is equivalent to [`paddingEnd`](/docs/layout-props#paddingend) (i.e. `paddingRight`). When direction is `rtl`, `paddingInlineEnd` is equivalent to [`paddingEnd`](/docs/layout-props#paddingend) (i.e. `paddingLeft`).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-inline-end) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingInlineStart`[​](#paddinginlinestart "Direct link to paddinginlinestart")

When direction is `ltr`, `paddingInlineStart` is equivalent to [`paddingStart`](/docs/layout-props#paddingstart) (i.e. `paddingLeft`). When direction is `rtl`, `paddingInlineStart` is equivalent to [`paddingStart`](/docs/layout-props#paddingstart) (i.e. `paddingRight`).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/padding-inline-start) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingLeft`[​](#paddingleft "Direct link to paddingleft")

`paddingLeft` works like `padding-left` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-left) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingRight`[​](#paddingright "Direct link to paddingright")

`paddingRight` works like `padding-right` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-right) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingStart`[​](#paddingstart "Direct link to paddingstart")

When direction is `ltr`, `paddingStart` is equivalent to `paddingLeft`. When direction is `rtl`, `paddingStart` is equivalent to `paddingRight`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingTop`[​](#paddingtop "Direct link to paddingtop")

`paddingTop` works like `padding-top` in CSS.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/padding-top) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `paddingVertical`[​](#paddingvertical "Direct link to paddingvertical")

Setting `paddingVertical` is like setting both of `paddingTop` and `paddingBottom`.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `position`[​](#position "Direct link to position")

`position` in React Native is similar to [regular CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/position), but everything is set to `relative` by default.

`relative` will position an element according to the normal flow of the layout. Insets (`top`, `bottom`, `left`, `right`) will offset relative to this layout.

`absolute` takes the element out of the normal flow of the layout. Insets will offset relative to its [containing block](/docs/flexbox#the-containing-block).

`static` will position an element according to the normal flow of the layout. Insets will have no effect. `static` elements do not form a containing block for absolute descendants.

For more information, see the [Layout with Flexbox docs](/docs/flexbox#position). Also, [the Yoga documentation](https://www.yogalayout.dev/docs/styling/position) has more details on how `position` differs between React Native and CSS.

| Type                                   | Required |
| -------------------------------------- | -------- |
| enum('absolute', 'relative', 'static') | No       |

***

### `right`[​](#right "Direct link to right")

`right` is the number of logical pixels to offset the right edge of this component.

It works similarly to `right` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/right) for more details of how `right` affects layout.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `rowGap`[​](#rowgap "Direct link to rowgap")

`rowGap` works like `row-gap` in CSS. It accepts numbers (in points) or percentage strings (e.g. `'10%'`). Percentage values are supported on the [New Architecture](/architecture/landing-page).

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/row-gap) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `start`[​](#start "Direct link to start")

When the direction is `ltr`, `start` is equivalent to `left`. When the direction is `rtl`, `start` is equivalent to `right`.

This style takes precedence over the `left`, `right`, and `end` styles.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `top`[​](#top "Direct link to top")

`top` is the number of logical pixels to offset the top edge of this component.

It works similarly to `top` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/top) for more details of how `top` affects layout.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `width`[​](#width "Direct link to width")

`width` sets the width of this component.

It works similarly to `width` in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/width) for more details.

| Type           | Required |
| -------------- | -------- |
| number, string | No       |

***

### `zIndex`[​](#zindex "Direct link to zindex")

`zIndex` controls which components display on top of others. Normally, you don't use `zIndex`. Components render according to their order in the document tree, so later components draw over earlier ones. `zIndex` may be useful if you have animations or custom modal interfaces where you don't want this behavior.

It works like the CSS `z-index` property - components with a larger `zIndex` will render on top. Think of the z-direction like it's pointing from the phone into your eyeball.

On iOS, `zIndex` may require `View`s to be siblings of each other for it to work as expected.

See [MDN CSS Reference](https://developer.mozilla.org/en-US/docs/Web/CSS/z-index) for more details.

| Type   | Required |
| ------ | -------- |
| number | No       |

----
url: https://reactnative.dev/docs/profiling
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Profiling is the process of analyzing an app's performance, resource usage, and behavior to identify potential bottlenecks or inefficiencies. It's worth making use of profiling tools to ensure your app works smoothly across different devices and conditions.

For iOS, Instruments is an invaluable tool, and on Android you should learn to use the [Android Studio Profiler](/docs/profiling#profiling-android-ui-performance-with-system-tracing).

But first, [**make sure that Development Mode is OFF!**](/docs/performance#running-in-development-mode-devtrue).

----
url: https://reactnative.dev/docs/accessibilityinfo
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Sometimes it's useful to know whether or not the device has a screen reader that is currently active. The `AccessibilityInfo` API is designed for this purpose. You can use it to query the current state of the screen reader as well as to register to be notified when the state of the screen reader changes.

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `addEventListener()`[​](#addeventlistener "Direct link to addeventlistener")

React TSX

```
static addEventListener(

  eventName: AccessibilityChangeEventName | AccessibilityAnnouncementEventName,

  handler: (

    event: AccessibilityChangeEvent | AccessibilityAnnouncementFinishedEvent,

  ) => void,

): EventSubscription;
```

Add an event handler. Supported events:

| Event name                            | Description                                                                                                                                                                                                                                                                        |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accessibilityServiceChanged` Android | Fires when some services such as TalkBack, other Android assistive technologies, and third-party accessibility services are enabled. The argument to the event handler is a boolean. The boolean is `true` when a some accessibility services is enabled and `false` otherwise.    |
| `announcementFinished` iOS            | Fires when the screen reader has finished making an announcement. The argument to the event handler is a dictionary with these keys:- `announcement`: The string announced by the screen reader.
- `success`: A boolean indicating whether the announcement was successfully made. |
| `boldTextChanged` iOS                 | Fires when the state of the bold text toggle changes. The argument to the event handler is a boolean. The boolean is `true` when bold text is enabled and `false` otherwise.                                                                                                       |
| `grayscaleChanged` iOS                | Fires when the state of the gray scale toggle changes. The argument to the event handler is a boolean. The boolean is `true` when a gray scale is enabled and `false` otherwise.                                                                                                   |
| `invertColorsChanged` iOS             | Fires when the state of the invert colors toggle changes. The argument to the event handler is a boolean. The boolean is `true` when invert colors is enabled and `false` otherwise.                                                                                               |
| `reduceMotionChanged`                 | Fires when the state of the reduce motion toggle changes. The argument to the event handler is a boolean. The boolean is `true` when a reduce motion is enabled (or when "Transition Animation Scale" in "Developer options" is "Animation off") and `false` otherwise.            |
| `reduceTransparencyChanged` iOS       | Fires when the state of the reduce transparency toggle changes. The argument to the event handler is a boolean. The boolean is `true` when reduce transparency is enabled and `false` otherwise.                                                                                   |
| `screenReaderChanged`                 | Fires when the state of the screen reader changes. The argument to the event handler is a boolean. The boolean is `true` when a screen reader is enabled and `false` otherwise.                                                                                                    |

***

### `announceForAccessibility()`[​](#announceforaccessibility "Direct link to announceforaccessibility")

React TSX

```
static announceForAccessibility(announcement: string);
```

Post a string to be announced by the screen reader.

***

### `announceForAccessibilityWithOptions()`[​](#announceforaccessibilitywithoptions "Direct link to announceforaccessibilitywithoptions")

React TSX

```
static announceForAccessibilityWithOptions(

  announcement: string,

  options: {

    queue?: boolean;

    priority?: 'low' | 'default' | 'high';

  },

);
```

Post a string to be announced by the screen reader with modification options. By default announcements will interrupt any existing speech, but on iOS they can be queued behind existing speech by setting `queue` to `true` in the options object. An optional `priority` can also be specified on iOS.

**Parameters:**

| Name                 | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| -------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| announcementRequired | string | The string to be announced                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| optionsRequired      | object | Options object with the following keys:- `queue`: Queue the announcement behind existing speech.

  iOS
- `priority`: The priority of the announcement (`'low'`, `'default'`, or `'high'`). High priority announcements will interrupt any ongoing speech and cannot be interrupted. Default priority announcements will interrupt any ongoing speech but can be interrupted. Low priority announcements will not interrupt ongoing speech and can be interrupted.

  iOS |

***

### `getRecommendedTimeoutMillis()`Android[​](#getrecommendedtimeoutmillis-android "Direct link to getrecommendedtimeoutmillis-android")

React TSX

```
static getRecommendedTimeoutMillis(originalTimeout: number): Promise<number>;
```

Gets the timeout in millisecond that the user needs. This value is set in "Time to take action (Accessibility timeout)" of "Accessibility" settings.

**Parameters:**

| Name                    | Type   | Description                                                                           |
| ----------------------- | ------ | ------------------------------------------------------------------------------------- |
| originalTimeoutRequired | number | The timeout to return if "Accessibility timeout" is not set. Specify in milliseconds. |

***

### `isAccessibilityServiceEnabled()`Android[​](#isaccessibilityserviceenabled-android "Direct link to isaccessibilityserviceenabled-android")

React TSX

```
static isAccessibilityServiceEnabled(): Promise<boolean>;
```

Check whether any accessibility service is enabled. This includes TalkBack but also any third-party accessibility app that may be installed. To only check whether TalkBack is enabled, use [isScreenReaderEnabled](#isscreenreaderenabled). Returns a promise which resolves to a boolean. The result is `true` when some accessibility services is enabled and `false` otherwise.

note

Please use [`isScreenReaderEnabled`](#isscreenreaderenabled) if you only want to check the status of TalkBack.

***

### `isBoldTextEnabled()`iOS[​](#isboldtextenabled-ios "Direct link to isboldtextenabled-ios")

React TSX

```
static isBoldTextEnabled(): Promise<boolean>:
```

Query whether a bold text is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when bold text is enabled and `false` otherwise.

***

### `isGrayscaleEnabled()`iOS[​](#isgrayscaleenabled-ios "Direct link to isgrayscaleenabled-ios")

React TSX

```
static isGrayscaleEnabled(): Promise<boolean>;
```

Query whether grayscale is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when grayscale is enabled and `false` otherwise.

***

### `isInvertColorsEnabled()`iOS[​](#isinvertcolorsenabled-ios "Direct link to isinvertcolorsenabled-ios")

React TSX

```
static isInvertColorsEnabled(): Promise<boolean>;
```

Query whether invert colors is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when invert colors is enabled and `false` otherwise.

***

### `isReduceMotionEnabled()`[​](#isreducemotionenabled "Direct link to isreducemotionenabled")

React TSX

```
static isReduceMotionEnabled(): Promise<boolean>;
```

Query whether reduce motion is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when reduce motion is enabled and `false` otherwise.

***

### `isReduceTransparencyEnabled()`iOS[​](#isreducetransparencyenabled-ios "Direct link to isreducetransparencyenabled-ios")

React TSX

```
static isReduceTransparencyEnabled(): Promise<boolean>;
```

Query whether reduce transparency is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when a reduce transparency is enabled and `false` otherwise.

***

### `isScreenReaderEnabled()`[​](#isscreenreaderenabled "Direct link to isscreenreaderenabled")

React TSX

```
static isScreenReaderEnabled(): Promise<boolean>;
```

Query whether a screen reader is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when a screen reader is enabled and `false` otherwise.

***

### `isHighTextContrastEnabled()`Android[​](#ishightextcontrastenabled-android "Direct link to ishightextcontrastenabled-android")

React TSX

```
static isHighTextContrastEnabled(): Promise<boolean>
```

Query whether high text contrast is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when high text contrast is enabled and `false` otherwise.

***

### `isDarkerSystemColorsEnabled()`iOS[​](#isdarkersystemcolorsenabled-ios "Direct link to isdarkersystemcolorsenabled-ios")

React TSX

```
static isDarkerSystemColorsEnabled(): Promise<boolean>
```

Query whether dark system colors is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when dark system colors is enabled and `false` otherwise.

***

### `prefersCrossFadeTransitions()`iOS[​](#preferscrossfadetransitions-ios "Direct link to preferscrossfadetransitions-ios")

React TSX

```
static prefersCrossFadeTransitions(): Promise<boolean>;
```

Query whether reduce motion and prefer cross-fade transitions settings are currently enabled. Returns a promise which resolves to a boolean. The result is `true` when prefer cross-fade transitions is enabled and `false` otherwise.

***

### 🗑️ `setAccessibilityFocus()`[​](#️-setaccessibilityfocus "Direct link to ️-setaccessibilityfocus")

Deprecated

Prefer using `sendAccessibilityEvent` with eventType `focus` instead.

React TSX

```
static setAccessibilityFocus(reactTag: number);
```

Set accessibility focus to a React component.

On Android, this calls `UIManager.sendAccessibilityEvent` method with passed `reactTag` and `UIManager.AccessibilityEventTypes.typeViewFocused` arguments.

note

Make sure that any `View` you want to receive the accessibility focus has `accessible={true}`.

***

### `sendAccessibilityEvent()`[​](#sendaccessibilityevent "Direct link to sendaccessibilityevent")

React TSX

```
static sendAccessibilityEvent(host: HostInstance, eventType: AccessibilityEventTypes);
```

Imperatively trigger an accessibility event on a React component, like changing the focused element for a screen reader.

note

Make sure that any `View` you want to receive the accessibility focus has `accessible={true}`.

| Name              | Type                    | Description                                                                                                            |
| ----------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| hostRequired      | HostInstance            | The component ref to send the event to.                                                                                |
| eventTypeRequired | AccessibilityEventTypes | One of `'click'` (Android only), `'focus'`, `'viewHoverEnter'` (Android only), or `'windowStateChange'` (Android only) |

* [Example](#example)

* [Methods](#methods)

  * [`addEventListener()`](#addeventlistener)
  * [`announceForAccessibility()`](#announceforaccessibility)
  * [`announceForAccessibilityWithOptions()`](#announceforaccessibilitywithoptions)
  * [`getRecommendedTimeoutMillis()`](#getrecommendedtimeoutmillis-android)

    [Android](#getrecommendedtimeoutmillis-android)
  * [`isAccessibilityServiceEnabled()`](#isaccessibilityserviceenabled-android)

    [Android](#isaccessibilityserviceenabled-android)
  * [`isBoldTextEnabled()`](#isboldtextenabled-ios)

    [iOS](#isboldtextenabled-ios)
  * [`isGrayscaleEnabled()`](#isgrayscaleenabled-ios)

    [iOS](#isgrayscaleenabled-ios)
  * [`isInvertColorsEnabled()`](#isinvertcolorsenabled-ios)

    [iOS](#isinvertcolorsenabled-ios)
  * [`isReduceMotionEnabled()`](#isreducemotionenabled)
  * [`isReduceTransparencyEnabled()`](#isreducetransparencyenabled-ios)

    [iOS](#isreducetransparencyenabled-ios)
  * [`isScreenReaderEnabled()`](#isscreenreaderenabled)
  * [`isHighTextContrastEnabled()`](#ishightextcontrastenabled-android)

    [Android](#ishightextcontrastenabled-android)
  * [`isDarkerSystemColorsEnabled()`](#isdarkersystemcolorsenabled-ios)

    [iOS](#isdarkersystemcolorsenabled-ios)
  * [`prefersCrossFadeTransitions()`](#preferscrossfadetransitions-ios)

    [iOS](#preferscrossfadetransitions-ios)
  * [🗑️ `setAccessibilityFocus()`](#️-setaccessibilityfocus)
  * [`sendAccessibilityEvent()`](#sendaccessibilityevent)

----
url: https://reactnative.dev/docs/next/clipboard
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/clipboard)** (0.87).

Version: Next

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=clipboard) instead.

----
url: https://reactnative.dev/docs/next/state
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/state)** (0.87).

Version: Next

State works the same way as it does in React, so for more details on handling state, you can look at the [React.Component API](https://react.dev/reference/react/Component#setstate). At this point, you may have noticed that most of our examples use the default text color. To customize the text color, you will have to [learn about Style](/docs/next/style).

----
url: https://reactnative.dev/docs/colors
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Components in React Native are [styled using JavaScript](/docs/style). Color properties usually match how [CSS works on the web](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). General guides on the color usage on each platform could be found below:

* [Android](https://material.io/design/color/color-usage.html)
* [iOS](https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/color/)

## Color APIs[​](#color-apis "Direct link to Color APIs")

React Native has several color APIs designed to allow you to take full advantage of your platform's design and user preferences.

* [PlatformColor](/docs/platformcolor) lets you reference the platform's color system.
* [DynamicColorIOS](/docs/dynamiccolorios) is iOS specific and allows you to specify which colors should be used in light or Dark Mode.

----
url: https://reactnative.dev/docs/global-clearInterval
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearInterval) for more information.

The global `clearInterval` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/colors
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/colors)** (0.87).

Version: Next

Components in React Native are [styled using JavaScript](/docs/next/style). Color properties usually match how [CSS works on the web](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). General guides on the color usage on each platform could be found below:

* [Android](https://material.io/design/color/color-usage.html)
* [iOS](https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/color/)

## Color APIs[​](#color-apis "Direct link to Color APIs")

React Native has several color APIs designed to allow you to take full advantage of your platform's design and user preferences.

* [PlatformColor](/docs/next/platformcolor) lets you reference the platform's color system.
* [DynamicColorIOS](/docs/next/dynamiccolorios) is iOS specific and allows you to specify which colors should be used in light or Dark Mode.

----
url: https://reactnative.dev/docs/next/network
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/network)** (0.87).

Version: Next

Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may need to fetch a chunk of static content from another server.

## Using Fetch[​](#using-fetch "Direct link to Using Fetch")

React Native provides the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for your networking needs. Fetch will seem familiar if you have used `XMLHttpRequest` or other networking APIs before. You may refer to MDN's guide on [Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) for additional information.

### Making requests[​](#making-requests "Direct link to Making requests")

In order to fetch content from an arbitrary URL, you can pass the URL to fetch:

TypeScript

```
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:

TypeScript

```
fetch('https://mywebsite.com/endpoint/', {

  method: 'POST',

  headers: {

    Accept: 'application/json',

    'Content-Type': 'application/json',

  },

  body: JSON.stringify({

    firstParam: 'yourValue',

    secondParam: 'yourOtherValue',

  }),

});
```

Take a look at the [Fetch Request docs](https://developer.mozilla.org/en-US/docs/Web/API/Request) for a full list of properties.

### Handling the response[​](#handling-the-response "Direct link to Handling the response")

The above examples show how you can make a request. In many cases, you will want to do something with the response.

Networking is an inherently asynchronous operation. Fetch method will return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that makes it straightforward to write code that works in an asynchronous manner:

TypeScript

```
const getMoviesFromApi = () => {

  return fetch('https://reactnative.dev/movies.json')

    .then(response => response.json())

    .then(json => {

      return json.movies;

    })

    .catch(error => {

      console.error(error);

    });

};
```

You can also use the `async` / `await` syntax in a React Native app:

TypeScript

```
const getMoviesFromApiAsync = async () => {

  try {

    const response = await fetch(

      'https://reactnative.dev/movies.json',

    );

    const json = await response.json();

    return json.movies;

  } catch (error) {

    console.error(error);

  }

};
```

```
const request = new XMLHttpRequest();

request.onreadystatechange = e => {

  if (request.readyState !== 4) {

    return;

  }



  if (request.status === 200) {

    console.log('success', request.responseText);

  } else {

    console.warn('error');

  }

};



request.open('GET', 'https://mywebsite.com/endpoint/');

request.send();
```

Caution

The security model for XMLHttpRequest is different than on web as there is no concept of [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) in native apps.

## WebSocket Support[​](#websocket-support "Direct link to WebSocket Support")

React Native also supports [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), a protocol which provides full-duplex communication channels over a single TCP connection.

TypeScript

```
const ws = new WebSocket('ws://host.com/path');



ws.onopen = () => {

  // connection opened

  ws.send('something'); // send a message

};



ws.onmessage = e => {

  // a message was received

  console.log(e.data);

};



ws.onerror = e => {

  // an error occurred

  console.log(e.message);

};



ws.onclose = e => {

  // connection closed

  console.log(e.code, e.reason);

};
```

```
#import <React/RCTHTTPRequestHandler.h>
```

`RCTSetCustomNSURLSessionConfigurationProvider` should be called early in the application life cycle such that it is readily available when needed by React.

For apps using the UIScene lifecycle, call it from `scene:willConnectToSession:options:` before starting React Native:

Objective-C

```
- (void)scene:(UIScene *)scene

    willConnectToSession:(UISceneSession *)session

                 options:(UISceneConnectionOptions *)connectionOptions

{

  RCTSetCustomNSURLSessionConfigurationProvider(^NSURLSessionConfiguration *{

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    // configure the session

    return configuration;

  });



  // set up React Native

}
```

For apps without the UIScene lifecycle, call it from `application:didFinishLaunchingWithOptions:` before starting React Native:

Objective-C

```
-(void)application:(__unused UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {



  // set RCTSetCustomNSURLSessionConfigurationProvider

  RCTSetCustomNSURLSessionConfigurationProvider(^NSURLSessionConfiguration *{

     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

     // configure the session

     return configuration;

  });



  // set up React

  _bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];

}
```

----
url: https://reactnative.dev/docs/next/strict-typescript-api
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/strict-typescript-api)** (0.87).

Version: Next

```
  {

    "extends": "@react-native/typescript-config",

    "compilerOptions": {

      ...

+     "customConditions": ["react-native", "react-native-legacy-deep-imports"]

    }

  }
```

Issues / Feedback?

The 0.87 rollout of the Strict API by default is an ecosystem-wide change, and one we need to make in order to have stable API guarantees for React Native in future.

Design choices about which APIs are exported at root, and intentional updates to type names/shapes have been worked on with the community and partners since the original 0.80 preview.

We believe we've ironed out all rough edges, but there may still be edge cases. If you're choosing to opt out of the Strict API in 0.87 or later, we'd love to know why: [**discussion thread**](https://github.com/react-native-community/discussions-and-proposals/discussions/1015).

***

## Migration guide[​](#migration-guide "Direct link to Migration guide")

tip

Use the [**/migrate-to-strict-api**](https://www.skills.sh/react-native-community/skills/migrate-to-strict-api) skill to migrate your codebase via an agent.

```
npx skills add react-native-community/skills --skill migrate-to-strict-api
```

```
{

  "compilerOptions": {

    "paths": {

      "some-library/jest/mock": ["./untyped-module.d.ts"]

    }

  }

}
```

untyped-module.d.ts

```
declare const anyExport: unknown;

export default anyExport;
```

```
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

import type {

  Int32,

  WithDefault,

} from 'react-native/Libraries/Types/CodegenTypes';



interface NativeProps extends ViewProps {

  enabled?: WithDefault<boolean, true>;

  size?: Int32;

}



export default codegenNativeComponent<NativeProps>(

  'RNCustomComponent',

);
```

```
import {CodegenTypes, codegenNativeComponent} from 'react-native';



interface NativeProps extends ViewProps {

  enabled?: CodegenTypes.WithDefault<boolean, true>;

  size?: CodegenTypes.Int32;

}



export default codegenNativeComponent<NativeProps>(

  'RNCustomComponent',

);
```

### Refs now use `*Instance` typesSince 0.87[​](#refs-now-use-instance-types-since-087 "Direct link to refs-now-use-instance-types-since-087")

Each built-in component now has a dedicated `*Instance` type for use with refs — for example, `ViewInstance`, `TextInputInstance`, `ScrollViewInstance`. These are the **recommended way to type refs** under the Strict TypeScript API.

Previously, `useRef<View>` worked because `View` and other components were typed as a class. Under the Strict API, built-in components are typed as functions, so `View` refers to the function itself — **component type names no longer work as ref types**.

* Before
* After

```
import {useRef} from 'react';

import {View, TextInput} from 'react-native';



function MyComponent() {

  const viewRef = useRef<View>(null);

  const inputRef = useRef<TextInput>(null);



  return (

    <>

      <View ref={viewRef} />

      <TextInput ref={inputRef} />

    </>

  );

}
```

```
import {useRef} from 'react';

import type {

  TextInput,

  TextInputInstance,

  View,

  ViewInstance,

} from 'react-native';



function MyComponent() {

  const viewRef = useRef<ViewInstance>(null);

  const inputRef = useRef<TextInputInstance>(null);



  return (

    <>

      <View ref={viewRef} />

      <TextInput ref={inputRef} />

    </>

  );

}
```

`*Instance` types also work transparently with `Animated` variants — no separate type is needed:

```
const viewRef = useRef<ViewInstance>(null);



<View ref={viewRef} />

<Animated.View ref={viewRef} />
```

This also replaces the removed `Animated.LegacyRef` type. Code using `ref={ref as React.Ref<Animated.LegacyRef<View>>}` can be simplified to `ref={ref}` with a `ViewInstance`-typed ref.

**Available instance types**

| Component                 | Instance type                     |
| ------------------------- | --------------------------------- |
| `ActivityIndicator`       | `ActivityIndicatorInstance`       |
| `Button`                  | `ButtonInstance`                  |
| `DrawerLayoutAndroid`     | `DrawerLayoutAndroidInstance`     |
| `FlatList`                | `FlatListInstance`                |
| `Image`                   | `ImageInstance`                   |
| `ImageBackground`         | `ImageBackgroundInstance`         |
| `KeyboardAvoidingView`    | `KeyboardAvoidingViewInstance`    |
| `Modal`                   | `ModalInstance`                   |
| `Pressable`               | `PressableInstance`               |
| `ProgressBarAndroid`      | `ProgressBarAndroidInstance`      |
| `RefreshControl`          | `RefreshControlInstance`          |
| `SafeAreaView`            | `SafeAreaViewInstance`            |
| `ScrollView`              | `ScrollViewInstance`              |
| `SectionList`             | `SectionListInstance`             |
| `StatusBar`               | `StatusBarInstance`               |
| `Switch`                  | `SwitchInstance`                  |
| `Text`                    | `TextInstance`                    |
| `TextInput`               | `TextInputInstance`               |
| `TouchableHighlight`      | `TouchableHighlightInstance`      |
| `TouchableNativeFeedback` | `TouchableNativeFeedbackInstance` |
| `TouchableOpacity`        | `TouchableOpacityInstance`        |
| `View`                    | `ViewInstance`                    |
| `VirtualizedList`         | `VirtualizedListInstance`         |
| `VirtualizedSectionList`  | `VirtualizedSectionListInstance`  |

Components without ref support (`InputAccessoryView`, `TouchableWithoutFeedback`, `experimental_LayoutConformance`) do not have instance types.

**Migration**

| Before                                                  | After                        |
| ------------------------------------------------------- | ---------------------------- |
| `useRef<View>(null)`                                    | `useRef<ViewInstance>(null)` |
| `useRef<React.ComponentRef<typeof View>>(null)`         | `useRef<ViewInstance>(null)` |
| `useRef<HostInstance>(null)` (for a specific component) | `useRef<ViewInstance>(null)` |
| `Ref<Animated.LegacyRef<View>>`                         | `Ref<ViewInstance>`          |

note

`React.ComponentRef<typeof View>` remains valid and produces the same type as `ViewInstance`. The `*Instance` types are convenient aliases — both approaches work.

### Removal of `*Static` types[​](#removal-of-static-types "Direct link to removal-of-static-types")

#### Migration[​](#migration-1 "Direct link to Migration")

* Before
* After

```
import {Linking, LinkingStatic} from 'react-native';



function foo(linking: LinkingStatic) {}

foo(Linking);
```

```
import {Linking} from 'react-native';



function foo(linking: Linking) {}

foo(Linking);
```

```
// @ts-expect-error - React Native internal, untyped under the Strict API

import NativeAppState from 'react-native/Libraries/AppState/NativeAppState';
```

Separately, if your Jest setup imports `react-native/Libraries/Core/InitializeCore`, update it — see [`InitializeCore` is now `react-native/setup-env`](#initializecore-is-now-react-nativesetup-env-since-087).

## Other breaking changes[​](#other-breaking-changes "Direct link to Other breaking changes")

### `InitializeCore` is now `react-native/setup-env`Since 0.87[​](#initializecore-is-now-react-nativesetup-env-since-087 "Direct link to initializecore-is-now-react-nativesetup-env-since-087")

Unlike other deep imports, this module is a side-effect entry point with no root `react-native` equivalent. `InitializeCore` is deprecated since 0.87.

```
- import 'react-native/Libraries/Core/InitializeCore';

+ import 'react-native/setup-env';
```

For the full list of aliases, see [`DeprecatedPropertiesAlias.d.ts`](https://github.com/react/react-native/blob/main/packages/react-native/types/public/DeprecatedPropertiesAlias.d.ts).

****

    [Since 0.87](#refs-now-use-instance-types-since-087)
  * [Removal of `*Static` types](#removal-of-static-types)
  * [Updating test mocks](#updating-test-mocks)

* [Other breaking changes](#other-breaking-changes)

  * [`InitializeCore` is now `react-native/setup-env`](#initializecore-is-now-react-nativesetup-env-since-087)

    [Since 0.87](#initializecore-is-now-react-nativesetup-env-since-087)
  * [Changes to Animated types](#changes-to-animated-types)
  * [Unified types for optional props](#unified-types-for-optional-props)
  * [Removal of some deprecated types](#removal-of-some-deprecated-types)
  * [Removal of leftover component props](#removal-of-leftover-component-props)
  * [Removal of internal-only helper types](#removal-of-internal-only-helper-types)

* [FAQs](#faqs)

----
url: https://reactnative.dev/docs/next/turbo-native-modules-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/turbo-native-modules-android)** (0.87).

Version: Next

Now it's time to write some Android platform code to make sure `localStorage` survives after the application is closed.

The first step is to implement the generated `NativeLocalStorageSpec` interface:

* Java
* Kotlin

android/app/src/main/java/com/nativelocalstorage/NativeLocalStorageModule.java

```
package com.nativelocalstorage;



import android.content.Context;

import android.content.SharedPreferences;

import com.nativelocalstorage.NativeLocalStorageSpec;

import com.facebook.react.bridge.ReactApplicationContext;



public class NativeLocalStorageModule extends NativeLocalStorageSpec {



  public static final String NAME = "NativeLocalStorage";



  public NativeLocalStorageModule(ReactApplicationContext reactContext) {

    super(reactContext);

  }



  @Override

  public String getName() {

    return NAME;

  }



  @Override

  public void setItem(String value, String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();

    editor.putString(key, value);

    editor.apply();

  }



  @Override

  public String getItem(String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    String username = sharedPref.getString(key, null);

    return username;

  }



  @Override

  public void removeItem(String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    sharedPref.edit().remove(key).apply();

  }



  @Override

  public void clear() {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    sharedPref.edit().clear().apply();

  }

}
```

android/app/src/main/java/com/nativelocalstorage/NativeLocalStorageModule.kt

```
package com.nativelocalstorage



import android.content.Context

import android.content.SharedPreferences

import com.nativelocalstorage.NativeLocalStorageSpec

import com.facebook.react.bridge.ReactApplicationContext



class NativeLocalStorageModule(reactContext: ReactApplicationContext) : NativeLocalStorageSpec(reactContext) {



  override fun getName() = NAME



  override fun setItem(value: String, key: String) {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.putString(key, value)

    editor.apply()

  }



  override fun getItem(key: String): String? {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val username = sharedPref.getString(key, null)

    return username.toString()

  }



  override fun removeItem(key: String) {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.remove(key)

    editor.apply()

  }



  override fun clear() {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.clear()

    editor.apply()

  }



  companion object {

    const val NAME = "NativeLocalStorage"

  }

}
```

Next we need to create `NativeLocalStoragePackage`. It provides an object to register our Module in the React Native runtime, by wrapping it as a Base Native Package:

* Java
* Kotlin

android/app/src/main/java/com/nativelocalstorage/NativeLocalStoragePackage.java

```
package com.nativelocalstorage;



import com.facebook.react.BaseReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.model.ReactModuleInfo;

import com.facebook.react.module.model.ReactModuleInfoProvider;



import java.util.HashMap;

import java.util.Map;



public class NativeLocalStoragePackage extends BaseReactPackage {



  @Override

  public NativeModule getModule(String name, ReactApplicationContext reactContext) {

    if (name.equals(NativeLocalStorageModule.NAME)) {

      return new NativeLocalStorageModule(reactContext);

    } else {

      return null;

    }

  }



  @Override

  public ReactModuleInfoProvider getReactModuleInfoProvider() {

    return new ReactModuleInfoProvider() {

      @Override

      public Map<String, ReactModuleInfo> getReactModuleInfos() {

        Map<String, ReactModuleInfo> map = new HashMap<>();

        map.put(NativeLocalStorageModule.NAME, new ReactModuleInfo(

          NativeLocalStorageModule.NAME,       // name

          NativeLocalStorageModule.NAME,       // className

          false, // canOverrideExistingModule

          false, // needsEagerInit

          false, // isCXXModule

          true   // isTurboModule

        ));

        return map;

      }

    };

  }

}
```

android/app/src/main/java/com/nativelocalstorage/NativeLocalStoragePackage.kt

```
package com.nativelocalstorage



import com.facebook.react.BaseReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.module.model.ReactModuleInfo

import com.facebook.react.module.model.ReactModuleInfoProvider



class NativeLocalStoragePackage : BaseReactPackage() {



  override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =

    if (name == NativeLocalStorageModule.NAME) {

      NativeLocalStorageModule(reactContext)

    } else {

      null

    }



  override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {

    mapOf(

      NativeLocalStorageModule.NAME to ReactModuleInfo(

        name = NativeLocalStorageModule.NAME,

        className = NativeLocalStorageModule.NAME,

        canOverrideExistingModule = false,

        needsEagerInit = false,

        isCxxModule = false,

        isTurboModule = true

      )

    )

  }

}
```

```
package com.inappmodule;



import android.app.Application;

import com.facebook.react.PackageList;

import com.facebook.react.ReactApplication;

import com.facebook.react.ReactHost;

import com.facebook.react.ReactNativeHost;

import com.facebook.react.ReactPackage;

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;

import com.facebook.react.defaults.DefaultReactHost;

import com.facebook.react.defaults.DefaultReactNativeHost;

import com.facebook.soloader.SoLoader;

import com.nativelocalstorage.NativeLocalStoragePackage;



import java.util.ArrayList;

import java.util.List;



public class MainApplication extends Application implements ReactApplication {



  private final ReactNativeHost reactNativeHost = new DefaultReactNativeHost(this) {

    @Override

    public List<ReactPackage> getPackages() {

      List<ReactPackage> packages = new PackageList(this).getPackages();

      // Packages that cannot be autolinked yet can be added manually here, for example:

      // packages.add(new MyReactNativePackage());

      packages.add(new NativeLocalStoragePackage());

      return packages;

    }



    @Override

    public String getJSMainModuleName() {

      return "index";

    }



    @Override

    public boolean getUseDeveloperSupport() {

      return BuildConfig.DEBUG;

    }



    @Override

    public boolean isNewArchEnabled() {

      return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;

    }



    @Override

    public boolean isHermesEnabled() {

      return BuildConfig.IS_HERMES_ENABLED;

    }

  };



  @Override

  public ReactHost getReactHost() {

    return DefaultReactHost.getDefaultReactHost(getApplicationContext(), reactNativeHost);

  }



  @Override

  public void onCreate() {

    super.onCreate();

    SoLoader.init(this, false);

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      // If you opted-in for the New Architecture, we load the native entry point for this app.

      DefaultNewArchitectureEntryPoint.load();

    }

  }

}
```

android/app/src/main/java/com/turobmoduleexample/MainApplication.kt

```
package com.inappmodule



import android.app.Application

import com.facebook.react.PackageList

import com.facebook.react.ReactApplication

import com.facebook.react.ReactHost

import com.facebook.react.ReactNativeHost

import com.facebook.react.ReactPackage

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

import com.facebook.react.defaults.DefaultReactNativeHost

import com.facebook.soloader.SoLoader

import com.nativelocalstorage.NativeLocalStoragePackage



class MainApplication : Application(), ReactApplication {



  override val reactNativeHost: ReactNativeHost =

      object : DefaultReactNativeHost(this) {

        override fun getPackages(): List<ReactPackage> =

            PackageList(this).packages.apply {

              // Packages that cannot be autolinked yet can be added manually here, for example:

              // add(MyReactNativePackage())

              add(NativeLocalStoragePackage())

            }



        override fun getJSMainModuleName(): String = "index"



        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG



        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

      }



  override val reactHost: ReactHost

    get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

    SoLoader.init(this, false)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      // If you opted-in for the New Architecture, we load the native entry point for this app.

      load()

    }

  }

}
```

You can now build and run your code on an emulator:

* npm
* Yarn

```
npm run android
```

```
yarn run android
```

----
url: https://reactnative.dev/docs/global-WebSocket
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) for more information.

The global `WebSocket` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/usewindowdimensions
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/usewindowdimensions)** (0.87).

Version: Next

React 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:

React TSX

```
const {height, width} = useWindowDimensions();
```

## Example[​](#example "Direct link to Example")

## Properties[​](#properties "Direct link to Properties")

### `fontScale`[​](#fontscale "Direct link to fontscale")

React TSX

```
useWindowDimensions().fontScale;
```

The scale of the font currently used. Some operating systems allow users to scale their font sizes larger or smaller for reading comfort. This property will let you know what is in effect.

note

Changing the font size percentage can be leveraged to dynamically adjust the sizes of UI elements, such as padding, margins, and container heights, to ensure a consistent and accessible user experience. By using the fontScale property, developers can make their applications more adaptable to users' preferences for larger or smaller text, enhancing readability and usability.

***

### `height`[​](#height "Direct link to height")

React TSX

```
useWindowDimensions().height;
```

The height in pixels of the window or screen your app occupies.

***

### `scale`[​](#scale "Direct link to scale")

React TSX

```
useWindowDimensions().scale;
```

The pixel ratio of the device your app is running on. The values can be:

* `1` which indicates that one point equals one pixel (usually PPI/DPI of 96, 76 on some platforms).
* `2` or `3` which indicates a Retina or high DPI display.

***

### `width`[​](#width "Direct link to width")

React TSX

```
useWindowDimensions().width;
```

----
url: https://reactnative.dev/docs/legacy/native-components-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

There are tons of native UI widgets out there ready to be used in the latest apps - some of them are part of the platform, others are available as third-party libraries, and still more might be in use in your very own portfolio. React Native has several of the most critical platform components already wrapped, like `ScrollView` and `TextInput`, but not all of them, and certainly not ones you might have written yourself for a previous app. Fortunately, we can wrap up these existing components for seamless integration with your React Native application.

Like the native module guide, this too is a more advanced guide that assumes you are somewhat familiar with Android SDK programming. This guide will show you how to build a native UI component, walking you through the implementation of a subset of the existing `ImageView` component available in the core React Native library.

info

You can also setup local library containing native component with one command. Read the guide to [Local libraries setup](/docs/legacy/local-library-setup) for more details.

```
class ReactImageManager(

    private val callerContext: ReactApplicationContext

) : SimpleViewManager<ReactImageView>() {



  override fun getName() = REACT_CLASS



  companion object {

    const val REACT_CLASS = "RCTImageView"

  }

}
```

Java

```
public class ReactImageManager extends SimpleViewManager<ReactImageView> {



  public static final String REACT_CLASS = "RCTImageView";

  ReactApplicationContext mCallerContext;



  public ReactImageManager(ReactApplicationContext reactContext) {

    mCallerContext = reactContext;

  }



  @Override

  public String getName() {

    return REACT_CLASS;

  }

}
```

### 2. Implement method `createViewInstance`[​](#2-implement-method-createviewinstance "Direct link to 2-implement-method-createviewinstance")

Views are created in the `createViewInstance` method, the view should initialize itself in its default state, any properties will be set via a follow up call to `updateView.`

* Java
* Kotlin

Kotlin

```
  override fun createViewInstance(context: ThemedReactContext) =

      ReactImageView(context, Fresco.newDraweeControllerBuilder(), null, callerContext)
```

Java

```
  @Override

  public ReactImageView createViewInstance(ThemedReactContext context) {

    return new ReactImageView(context, Fresco.newDraweeControllerBuilder(), null, mCallerContext);

  }
```

```
  @ReactProp(name = "src")

  fun setSrc(view: ReactImageView, sources: ReadableArray?) {

    view.setSource(sources)

  }



  @ReactProp(name = "borderRadius", defaultFloat = 0f)

  override fun setBorderRadius(view: ReactImageView, borderRadius: Float) {

    view.setBorderRadius(borderRadius)

  }



  @ReactProp(name = ViewProps.RESIZE_MODE)

  fun setResizeMode(view: ReactImageView, resizeMode: String?) {

    view.setScaleType(ImageResizeMode.toScaleType(resizeMode))

  }
```

Java

```
  @ReactProp(name = "src")

  public void setSrc(ReactImageView view, @Nullable ReadableArray sources) {

    view.setSource(sources);

  }



  @ReactProp(name = "borderRadius", defaultFloat = 0f)

  public void setBorderRadius(ReactImageView view, float borderRadius) {

    view.setBorderRadius(borderRadius);

  }



  @ReactProp(name = ViewProps.RESIZE_MODE)

  public void setResizeMode(ReactImageView view, @Nullable String resizeMode) {

    view.setScaleType(ImageResizeMode.toScaleType(resizeMode));

  }
```

### 4. Register the `ViewManager`[​](#4-register-the-viewmanager "Direct link to 4-register-the-viewmanager")

The final step is to register the ViewManager to the application, this happens in a similar way to [Native Modules](/docs/legacy/native-modules-android), via the applications package member function `createViewManagers`.

* Java
* Kotlin

Kotlin

```
  override fun createViewManagers(

      reactContext: ReactApplicationContext

  ) = listOf(ReactImageManager(reactContext))
```

Java

```
  @Override

  public List<ViewManager> createViewManagers(

                            ReactApplicationContext reactContext) {

    return Arrays.<ViewManager>asList(

      new ReactImageManager(reactContext)

    );

  }
```

### 5. Implement the JavaScript module[​](#5-implement-the-javascript-module "Direct link to 5. Implement the JavaScript module")

The very final step is to create the JavaScript module that defines the interface layer between Java/Kotlin and JavaScript for the users of your new view. It is recommended for you to document the component interface in this module (e.g. using TypeScript, Flow, or plain old comments).

ImageView\.tsx

```
import {requireNativeComponent} from 'react-native';



/**

 * Composes `View`.

 *

 * - src: Array<{url: string}>

 * - borderRadius: number

 * - resizeMode: 'cover' | 'contain' | 'stretch'

 */

export default requireNativeComponent('RCTImageView');
```

The `requireNativeComponent` function takes the name of the native view. Note that if your component needs to do anything more sophisticated (e.g. custom event handling), you should wrap the native component in another React component. This is illustrated in the `MyCustomView` example below.

## Events[​](#events "Direct link to Events")

So now we know how to expose native view components that we can control freely from JS, but how do we deal with events from the user, like pinch-zooms or panning? When a native event occurs the native code should issue an event to the JavaScript representation of the View, and the two views are linked with the value returned from the `getId()` method.

* Java
* Kotlin

Kotlin

```
class MyCustomView(context: Context) : View(context) {

  ...

  fun onReceiveNativeEvent() {

    val event = Arguments.createMap().apply {

      putString("message", "MyMessage")

    }

    val reactContext = context as ReactContext

    reactContext

        .getJSModule(RCTEventEmitter::class.java)

        .receiveEvent(id, "topChange", event)

  }

}
```

Java

```
class MyCustomView extends View {

   ...

   public void onReceiveNativeEvent() {

      WritableMap event = Arguments.createMap();

      event.putString("message", "MyMessage");

      ReactContext reactContext = (ReactContext)getContext();

      reactContext

          .getJSModule(RCTEventEmitter.class)

          .receiveEvent(getId(), "topChange", event);

    }

}
```

To map the `topChange` event name to the `onChange` callback prop in JavaScript, register it by overriding the `getExportedCustomBubblingEventTypeConstants` method in your `ViewManager`:

* Java
* Kotlin

Kotlin

```
class ReactImageManager : SimpleViewManager<MyCustomView>() {

  ...

  override fun getExportedCustomBubblingEventTypeConstants(): Map<String, Any> {

    return mapOf(

      "topChange" to mapOf(

        "phasedRegistrationNames" to mapOf(

          "bubbled" to "onChange"

        )

      )

    )

  }

}
```

Java

```
public class ReactImageManager extends SimpleViewManager<MyCustomView> {

    ...

    public Map getExportedCustomBubblingEventTypeConstants() {

        return MapBuilder.builder().put(

            "topChange",

            MapBuilder.of(

                "phasedRegistrationNames",

                MapBuilder.of("bubbled", "onChange")

            )

        ).build();

    }

}
```

This callback is invoked with the raw event, which we typically process in the wrapper component to make a simpler API:

MyCustomView\.tsx

```
import {useCallback} from 'react';

import {requireNativeComponent} from 'react-native';



const RCTMyCustomView = requireNativeComponent('RCTMyCustomView');



export default function MyCustomView(props: {

  // ...

  /**

   * Callback that is called continuously when the user is dragging the map.

   */

  onChangeMessage: (message: string) => unknown;

}) {

  const onChange = useCallback(

    event => {

      props.onChangeMessage?.(event.nativeEvent.message);

    },

    [props.onChangeMessage],

  );



  return <RCTMyCustomView {...props} onChange={onChange} />;

}
```

```
// replace with your package

package com.mypackage



import android.content.Context

import android.graphics.Color

import android.widget.FrameLayout

import android.widget.TextView



class CustomView(context: Context) : FrameLayout(context) {

  init {

    // set padding and background color

    setPadding(16,16,16,16)

    setBackgroundColor(Color.parseColor("#5FD3F3"))



    // add default text view

    addView(TextView(context).apply {

      text = "Welcome to Android Fragments with React Native."

    })

  }

}
```

CustomView\.java

```
// replace with your package

package com.mypackage;



import android.content.Context;

import android.graphics.Color;

import android.widget.FrameLayout;

import android.widget.ImageView;

import android.widget.TextView;



import androidx.annotation.NonNull;



public class CustomView extends FrameLayout {

  public CustomView(@NonNull Context context) {

    super(context);

    // set padding and background color

    this.setPadding(16,16,16,16);

    this.setBackgroundColor(Color.parseColor("#5FD3F3"));



    // add default text view

    TextView text = new TextView(context);

    text.setText("Welcome to Android Fragments with React Native.");

    this.addView(text);

  }

}
```

### 2. Create a `Fragment`[​](#2-create-a-fragment "Direct link to 2-create-a-fragment")

* Java
* Kotlin

MyFragment.kt

```
// replace with your package

package com.mypackage



import android.os.Bundle

import android.view.LayoutInflater

import android.view.View

import android.view.ViewGroup

import androidx.fragment.app.Fragment



// replace with your view's import

import com.mypackage.CustomView



class MyFragment : Fragment() {

  private lateinit var customView: CustomView



  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {

    super.onCreateView(inflater, container, savedInstanceState)

    customView = CustomView(requireNotNull(context))

    return customView // this CustomView could be any view that you want to render

  }



  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    super.onViewCreated(view, savedInstanceState)

    // do any logic that should happen in an `onCreate` method, e.g:

    // customView.onCreate(savedInstanceState);

  }



  override fun onPause() {

    super.onPause()

    // do any logic that should happen in an `onPause` method

    // e.g.: customView.onPause();

  }



  override fun onResume() {

    super.onResume()

    // do any logic that should happen in an `onResume` method

    // e.g.: customView.onResume();

  }



  override fun onDestroy() {

    super.onDestroy()

    // do any logic that should happen in an `onDestroy` method

    // e.g.: customView.onDestroy();

  }

}
```

MyFragment.java

```
// replace with your package

package com.mypackage;



import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import androidx.fragment.app.Fragment;



// replace with your view's import

import com.mypackage.CustomView;



public class MyFragment extends Fragment {

    CustomView customView;



    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {

        super.onCreateView(inflater, parent, savedInstanceState);

        customView = new CustomView(this.getContext());

        return customView; // this CustomView could be any view that you want to render

    }



    @Override

    public void onViewCreated(View view, Bundle savedInstanceState) {

        super.onViewCreated(view, savedInstanceState);

        // do any logic that should happen in an `onCreate` method, e.g:

        // customView.onCreate(savedInstanceState);

    }



    @Override

    public void onPause() {

        super.onPause();

        // do any logic that should happen in an `onPause` method

        // e.g.: customView.onPause();

    }



    @Override

    public void onResume() {

        super.onResume();

       // do any logic that should happen in an `onResume` method

       // e.g.: customView.onResume();

    }



    @Override

    public void onDestroy() {

        super.onDestroy();

        // do any logic that should happen in an `onDestroy` method

        // e.g.: customView.onDestroy();

    }

}
```

### 3. Create the `ViewManager` subclass[​](#3-create-the-viewmanager-subclass "Direct link to 3-create-the-viewmanager-subclass")

* Java
* Kotlin

MyViewManager.kt

```
// replace with your package

package com.mypackage



import android.view.Choreographer

import android.view.View

import android.view.ViewGroup

import android.widget.FrameLayout

import androidx.fragment.app.FragmentActivity

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.bridge.ReadableArray

import com.facebook.react.uimanager.ThemedReactContext

import com.facebook.react.uimanager.ViewGroupManager

import com.facebook.react.uimanager.annotations.ReactPropGroup



class MyViewManager(

    private val reactContext: ReactApplicationContext

) : ViewGroupManager<FrameLayout>() {

  private var propWidth: Int? = null

  private var propHeight: Int? = null



  override fun getName() = REACT_CLASS



  /**

   * Return a FrameLayout which will later hold the Fragment

   */

  override fun createViewInstance(reactContext: ThemedReactContext) =

      FrameLayout(reactContext)



  /**

   * Map the "create" command to an integer

   */

  override fun getCommandsMap() = mapOf("create" to COMMAND_CREATE)



  /**

   * Handle "create" command (called from JS) and call createFragment method

   */

  override fun receiveCommand(

      root: FrameLayout,

      commandId: String,

      args: ReadableArray?

  ) {

    super.receiveCommand(root, commandId, args)

    val reactNativeViewId = requireNotNull(args).getInt(0)



    when (commandId.toInt()) {

      COMMAND_CREATE -> createFragment(root, reactNativeViewId)

    }

  }



  @ReactPropGroup(names = ["width", "height"], customType = "Style")

  fun setStyle(view: FrameLayout, index: Int, value: Int) {

    if (index == 0) propWidth = value

    if (index == 1) propHeight = value

  }



  /**

   * Replace your React Native view with a custom fragment

   */

  fun createFragment(root: FrameLayout, reactNativeViewId: Int) {

    val parentView = root.findViewById<ViewGroup>(reactNativeViewId)

    setupLayout(parentView)



    val myFragment = MyFragment()

    val activity = reactContext.currentActivity as FragmentActivity

    activity.supportFragmentManager

        .beginTransaction()

        .replace(reactNativeViewId, myFragment, reactNativeViewId.toString())

        .commit()

  }



  fun setupLayout(view: View) {

    Choreographer.getInstance().postFrameCallback(object: Choreographer.FrameCallback {

      override fun doFrame(frameTimeNanos: Long) {

        manuallyLayoutChildren(view)

        view.viewTreeObserver.dispatchOnGlobalLayout()

        Choreographer.getInstance().postFrameCallback(this)

      }

    })

  }



  /**

   * Layout all children properly

   */

  private fun manuallyLayoutChildren(view: View) {

    // propWidth and propHeight coming from react-native props

    val width = requireNotNull(propWidth)

    val height = requireNotNull(propHeight)



    view.measure(

        View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),

        View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY))



    view.layout(0, 0, width, height)

  }



  companion object {

    private const val REACT_CLASS = "MyViewManager"

    private const val COMMAND_CREATE = 1

  }

}
```

MyViewManager.java

```
// replace with your package

package com.mypackage;



import android.view.Choreographer;

import android.view.View;

import android.view.ViewGroup;

import android.widget.FrameLayout;



import androidx.annotation.NonNull;

import androidx.annotation.Nullable;

import androidx.fragment.app.FragmentActivity;



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.bridge.ReadableArray;

import com.facebook.react.common.MapBuilder;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.uimanager.annotations.ReactPropGroup;

import com.facebook.react.uimanager.ViewGroupManager;

import com.facebook.react.uimanager.ThemedReactContext;



import java.util.Map;



public class MyViewManager extends ViewGroupManager<FrameLayout> {



  public static final String REACT_CLASS = "MyViewManager";

  public final int COMMAND_CREATE = 1;

  private int propWidth;

  private int propHeight;



  ReactApplicationContext reactContext;



  public MyViewManager(ReactApplicationContext reactContext) {

    this.reactContext = reactContext;

  }



  @Override

  public String getName() {

    return REACT_CLASS;

  }



  /**

   * Return a FrameLayout which will later hold the Fragment

   */

  @Override

  public FrameLayout createViewInstance(ThemedReactContext reactContext) {

    return new FrameLayout(reactContext);

  }



  /**

   * Map the "create" command to an integer

   */

  @Nullable

  @Override

  public Map<String, Integer> getCommandsMap() {

    return MapBuilder.of("create", COMMAND_CREATE);

  }



  /**

   * Handle "create" command (called from JS) and call createFragment method

   */

  @Override

  public void receiveCommand(

    @NonNull FrameLayout root,

    String commandId,

    @Nullable ReadableArray args

  ) {

    super.receiveCommand(root, commandId, args);

    int reactNativeViewId = args.getInt(0);

    int commandIdInt = Integer.parseInt(commandId);



    switch (commandIdInt) {

      case COMMAND_CREATE:

        createFragment(root, reactNativeViewId);

        break;

      default: {}

    }

  }



  @ReactPropGroup(names = {"width", "height"}, customType = "Style")

  public void setStyle(FrameLayout view, int index, Integer value) {

    if (index == 0) {

      propWidth = value;

    }



    if (index == 1) {

      propHeight = value;

    }

  }



  /**

   * Replace your React Native view with a custom fragment

   */

  public void createFragment(FrameLayout root, int reactNativeViewId) {

    ViewGroup parentView = (ViewGroup) root.findViewById(reactNativeViewId);

    setupLayout(parentView);



    final MyFragment myFragment = new MyFragment();

    FragmentActivity activity = (FragmentActivity) reactContext.getCurrentActivity();

    activity.getSupportFragmentManager()

            .beginTransaction()

            .replace(reactNativeViewId, myFragment, String.valueOf(reactNativeViewId))

            .commit();

  }



  public void setupLayout(View view) {

    Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {

      @Override

      public void doFrame(long frameTimeNanos) {

        manuallyLayoutChildren(view);

        view.getViewTreeObserver().dispatchOnGlobalLayout();

        Choreographer.getInstance().postFrameCallback(this);

      }

    });

  }



  /**

   * Layout all children properly

   */

  public void manuallyLayoutChildren(View view) {

      // propWidth and propHeight coming from react-native props

      int width = propWidth;

      int height = propHeight;



      view.measure(

              View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),

              View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));



      view.layout(0, 0, width, height);

  }

}
```

### 4. Register the `ViewManager`[​](#4-register-the-viewmanager-1 "Direct link to 4-register-the-viewmanager-1")

* Java
* Kotlin

MyPackage.kt

```
// replace with your package

package com.mypackage



import com.facebook.react.ReactPackage

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.uimanager.ViewManager



class MyPackage : ReactPackage {

  ...

  override fun createViewManagers(

      reactContext: ReactApplicationContext

  ) = listOf(MyViewManager(reactContext))

}
```

MyPackage.java

```
// replace with your package

package com.mypackage;



import com.facebook.react.ReactPackage;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.uimanager.ViewManager;



import java.util.Arrays;

import java.util.List;



public class MyPackage implements ReactPackage {



   @Override

   public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {

       return Arrays.<ViewManager>asList(

            new MyViewManager(reactContext)

       );

   }



}
```

### 5. Register the `Package`[​](#5-register-the-package "Direct link to 5-register-the-package")

* Java
* Kotlin

MainApplication.kt

```
override fun getPackages(): List<ReactPackage> =

    PackageList(this).packages.apply {

        // Packages that cannot be autolinked yet can be added manually here, for example:

        // add(MyReactNativePackage())

        add(MyAppPackage())

    }
```

MainApplication.java

```
@Override

protected List<ReactPackage> getPackages() {

    List<ReactPackage> packages = new PackageList(this).getPackages();

    // Packages that cannot be autolinked yet can be added manually here, for example:

    // packages.add(new MyReactNativePackage());

    packages.add(new MyAppPackage());

    return packages;

}
```

### 6. Implement the JavaScript module[​](#6-implement-the-javascript-module "Direct link to 6. Implement the JavaScript module")

I. Start with custom View manager:

MyViewManager.tsx

```
import {requireNativeComponent} from 'react-native';



export const MyViewManager =

  requireNativeComponent('MyViewManager');
```

II. Then implement custom View calling the `create` method:

MyView\.tsx

```
import {useEffect, useRef} from 'react';

import {

  PixelRatio,

  UIManager,

  findNodeHandle,

} from 'react-native';



import {MyViewManager} from './my-view-manager';



const createFragment = viewId =>

  UIManager.dispatchViewManagerCommand(

    viewId,

    // we are calling the 'create' command

    UIManager.MyViewManager.Commands.create.toString(),

    [viewId],

  );



export const MyView = () => {

  const ref = useRef(null);



  useEffect(() => {

    const viewId = findNodeHandle(ref.current);

    createFragment(viewId);

  }, []);



  return (

    <MyViewManager

      style={{

        // converts dpi to px, provide desired height

        height: PixelRatio.getPixelSizeForLayoutSize(200),

        // converts dpi to px, provide desired width

        width: PixelRatio.getPixelSizeForLayoutSize(200),

      }}

      ref={ref}

    />

  );

};
```

----
url: https://reactnative.dev/docs/settings
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`Settings` serves as a wrapper for [`NSUserDefaults`](https://developer.apple.com/documentation/foundation/nsuserdefaults), a persistent key-value store available only on iOS.

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `clearWatch()`[​](#clearwatch "Direct link to clearwatch")

React TSX

```
static clearWatch(watchId: number);
```

`watchId` is the number returned by `watchKeys()` when the subscription was originally configured.

***

### `get()`[​](#get "Direct link to get")

React TSX

```
static get(key: string): any;
```

Get the current value for a given `key` in `NSUserDefaults`.

***

### `set()`[​](#set "Direct link to set")

React TSX

```
static set(settings: Record<string, any>);
```

Set one or more values in `NSUserDefaults`.

***

### `watchKeys()`[​](#watchkeys "Direct link to watchkeys")

React TSX

```
static watchKeys(keys: string | array<string>, callback: () => void): number;
```

----
url: https://reactnative.dev/docs/roottag
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
import {RootTagContext} from 'react-native';

import NativeAnalytics from 'native-analytics';

import NativeNavigation from 'native-navigation';



function ScreenA() {

  const rootTag = useContext(RootTagContext);



  const updateTitle = title => {

    NativeNavigation.setTitle(rootTag, title);

  };



  const handleOneEvent = () => {

    NativeAnalytics.logEvent(rootTag, 'one_event');

  };



  // ...

}



class ScreenB extends React.Component {

  static contextType: typeof RootTagContext = RootTagContext;



  updateTitle(title) {

    NativeNavigation.setTitle(this.context, title);

  }



  handleOneEvent() {

    NativeAnalytics.logEvent(this.context, 'one_event');

  }



  // ...

}
```

----
url: https://reactnative.dev/docs/global-performance
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`performance`](https://developer.mozilla.org/en-US/docs/Web/API/Window/performance) object, as defined in Web specifications.

***

```
get rnStartupTiming(): ReactNativeStartupTiming;
```

The `ReactNativeStartupTiming` interface provides the following fields:

| Name                                     | Type           | Description                                               |
| ---------------------------------------- | -------------- | --------------------------------------------------------- |
| `startTime`                              | number \| void | When the React Native runtime initialization was started. |
| `executeJavaScriptBundleEntryPointStart` | number \| void | When the execution of the application bundle was started. |
| `endTime`                                | number \| void | When the React Native runtime was fully initialized.      |

----
url: https://reactnative.dev/docs/next/global-requestIdleCallback
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-requestIdleCallback)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) for more information.

The global `requestIdleCallback` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-fetch
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) for more information.

The global `fetch` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/tutorial
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The first style that we find is `flex: 1`, the [`flex`](/docs/layout-props#flex) prop will define how your items are going to "fill" over the available space along your main axis. Since we only have one container, it will take all the available space of the parent component. In this case, it is the only component, so it will take all the available screen space.

The following style is [`justifyContent`](/docs/layout-props#justifycontent): "center". This aligns children of a container in the center of the container's main axis. Finally, we have [`alignItems`](/docs/layout-props#alignitems): "center", which aligns children of a container in the center of the container's cross axis.

Some of the things in here might not look like JavaScript to you. Don't panic. *This is the future*.

First of all, ES2015 (also known as ES6) is a set of improvements to JavaScript that is now part of the official standard, but not yet supported by all browsers, so often it isn't used yet in web development. React Native ships with ES2015 support, so you can use this stuff without worrying about compatibility. `import`, `export`, `const` and `from` in the example above are all ES2015 features. If you aren't familiar with ES2015, you can probably pick it up by reading through sample code like this tutorial has. If you want, [this page](https://babeljs.io/learn-es2015/) has a good overview of ES2015 features.

The other unusual thing in this code example is `<View><Text>Hello world!</Text></View>`. This is JSX - a syntax for embedding XML within JavaScript. Many frameworks use a specialized templating language which lets you embed code inside markup language. In React, this is reversed. JSX lets you write your markup language inside code. It looks like HTML on the web, except instead of web things like `<div>` or `<span>`, you use React components. In this case, `<Text>` is a [Core Component](/docs/intro-react-native-components) that displays some text and `View` is like the `<div>` or `<span>`.

The other new thing going on here is the [`View`](/docs/view) component. A [`View`](/docs/view) is useful as a container for other components, to help control style and layout.

With `props` and the basic [`Text`](/docs/text), [`Image`](/docs/image), and [`View`](/docs/view) components, you can build a wide variety of static screens. To learn how to make your app change over time, you need to [learn about State](#state).

## State[​](#state "Direct link to State")

Unlike props [that are read-only](https://react.dev/reference/react/Component#props) and should not be modified, the `state` allows React components to change their output over time in response to user actions, network responses and anything else.

#### What's the difference between state and props in React?[​](#whats-the-difference-between-state-and-props-in-react "Direct link to What's the difference between state and props in React?")

In a React component, the props are the variables that we pass from a parent component to a child component. Similarly, the state are also variables, with the difference that they are not passed as parameters, but rather that the component initializes and manages them internally.

#### Are there differences between React and React Native to handle the state?[​](#are-there-differences-between-react-and-react-native-to-handle-the-state "Direct link to Are there differences between React and React Native to handle the state?")

React TSX

```
// React Counter Example using Hooks!



import {useState} from 'react';







const App = () => {

  const [count, setCount] = useState(0);



  return (

    <div className="container">

      <p>You clicked {count} times</p>

      <button

        onClick={() => setCount(count + 1)}>

        Click me!

      </button>

    </div>

  );

};





// CSS

.container {

  display: flex;

  justify-content: center;

  align-items: center;

}
```

React TSX

```
// React Native Counter Example using Hooks!



import {useState} from 'react';

import {View, Text, Button, StyleSheet} from 'react-native';



const App = () => {

  const [count, setCount] = useState(0);



  return (

    <View style={styles.container}>

      <Text>You clicked {count} times</Text>

      <Button

        onPress={() => setCount(count + 1)}

        title="Click me!"

      />

    </View>

  );

};



// React Native Styles

const styles = StyleSheet.create({

  container: {

    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

  },

});
```

----
url: https://reactnative.dev/docs/next/permissionsandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/permissionsandroid)** (0.87).

Version: Next

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `check()`[​](#check "Direct link to check")

React TSX

```
static check(permission: Permission): Promise<boolean>;
```

Returns a promise resolving to a boolean value as to whether the specified permissions has been granted.

**Parameters:**

| Name       | Type   | Required | Description                  |
| ---------- | ------ | -------- | ---------------------------- |
| permission | string | Yes      | The permission to check for. |

***

### `request()`[​](#request "Direct link to request")

React TSX

```
static request(

  permission: Permission,

  rationale?: Rationale,

): Promise<PermissionStatus>;
```

Prompts the user to enable a permission and returns a promise resolving to a string value (see result strings above) indicating whether the user allowed or denied the request or does not want to be asked again.

If `rationale` is provided, this function checks with the OS whether it is necessary to show a dialog explaining why the permission is needed (<https://developer.android.com/training/permissions/requesting.html#explain>) and then shows the system permission dialog.

**Parameters:**

| Name       | Type   | Required | Description                |
| ---------- | ------ | -------- | -------------------------- |
| permission | string | Yes      | The permission to request. |
| rationale  | object | No       | See `rationale` below.     |

**Rationale:**

| Name           | Type   | Required | Description                      |
| -------------- | ------ | -------- | -------------------------------- |
| title          | string | Yes      | The title of the dialog.         |
| message        | string | Yes      | The message of the dialog.       |
| buttonPositive | string | Yes      | The text of the positive button. |
| buttonNegative | string | No       | The text of the negative button. |
| buttonNeutral  | string | No       | The text of the neutral button.  |

***

### `requestMultiple()`[​](#requestmultiple "Direct link to requestmultiple")

React TSX

```
static requestMultiple(

  permissions: Permission[],

): Promise<{[key in Permission]: PermissionStatus}>;
```

Prompts the user to enable multiple permissions in the same dialog and returns an object with the permissions as keys and strings as values (see result strings above) indicating whether the user allowed or denied the request or does not want to be asked again.

**Parameters:**

| Name        | Type  | Required | Description                      |
| ----------- | ----- | -------- | -------------------------------- |
| permissions | array | Yes      | Array of permissions to request. |

----
url: https://reactnative.dev/docs/running-on-device
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
$ adb devices

List of devices attached

emulator-5554 offline   # Google emulator

14ed2fcc device         # Physical device
```

```
npm run android
```

```
yarn android
```

note

If you get a "bridge configuration isn't available" error, see [Using adb reverse](/docs/running-on-device#method-1-using-adb-reverse-recommended).

```
$ adb -s <device name> reverse tcp:8081 tcp:8081
```

To find the device name, run the following adb command:

```
$ adb devices
```

You can now enable Fast Refresh from the [Dev Menu](/docs/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

### Method 2: Connect via Wi-Fi[​](#method-2-connect-via-wi-fi "Direct link to Method 2: Connect via Wi-Fi")

You can also connect to the development server over Wi-Fi. You'll first need to install the app on your device using a USB cable, but once that has been done you can debug wirelessly by following these instructions. You'll need your development machine's current IP address before proceeding.

You can find the IP address in **System Settings (or System Preferences)** → **Network**.

1. Make sure your laptop and your phone are on the **same** Wi-Fi network.
2. Open your React Native app on your device.
3. You'll see a [red screen with an error](/docs/debugging#logbox). This is OK. The following steps will fix that.
4. Open the in-app [Dev Menu](/docs/debugging#opening-the-dev-menu).
5. Go to **Dev Settings** → **Debug server host & port for device**.
6. Type in your machine's IP address and the port of the local dev server (e.g. `10.0.1.1:8081`).
7. Go back to the **Dev Menu** and select **Reload JS**.

You can now enable Fast Refresh from the [Dev Menu](/docs/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

## Building your app for production[​](#building-your-app-for-production "Direct link to Building your app for production")

You have built a great app using React Native, and you are now itching to release it in the Play Store. The process is the same as any other native Android app, with some additional considerations to take into account. Follow the guide for [generating a signed APK](/docs/signed-apk-android) to learn more.

### 1. Enable Debugging over USB[​](#1-enable-debugging-over-usb-1 "Direct link to 1. Enable Debugging over USB")

Most Android devices can only install and run apps downloaded from Google Play, by default. You will need to enable USB Debugging on your device in order to install your app during development.

To enable USB debugging on your device, you will first need to enable the "Developer options" menu by going to **Settings** → **About phone** → **Software information** and then tapping the `Build number` row at the bottom seven times. You can then go back to **Settings** → **Developer options** to enable "USB debugging".

### 2. Plug in your device via USB[​](#2-plug-in-your-device-via-usb-1 "Direct link to 2. Plug in your device via USB")

Let's now set up an Android device to run our React Native projects. Go ahead and plug in your device via USB to your development machine.

Now check that your device is properly connecting to ADB, the Android Debug Bridge, by running `adb devices`.

```
$ adb devices

List of devices attached

emulator-5554 offline   # Google emulator

14ed2fcc device         # Physical device
```

Seeing `device` in the right column means the device is connected. You must have **only one device connected** at a time.

### 3. Run your app[​](#3-run-your-app-1 "Direct link to 3. Run your app")

From the root of your project, run the following in your command prompt to install and launch your app on the device:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

```
$ adb -s <device name> reverse tcp:8081 tcp:8081
```

To find the device name, run the following adb command:

```
$ adb devices
```

You can now enable Fast Refresh from the [Dev Menu](/docs/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

### Method 2: Connect via Wi-Fi[​](#method-2-connect-via-wi-fi-1 "Direct link to Method 2: Connect via Wi-Fi")

You can also connect to the development server over Wi-Fi. You'll first need to install the app on your device using a USB cable, but once that has been done you can debug wirelessly by following these instructions. You'll need your development machine's current IP address before proceeding.

Open the command prompt and type `ipconfig` to find your machine's IP address ([more info](https://windows.microsoft.com/en-us/windows/using-command-line-tools-networking-information)).

1. Make sure your laptop and your phone are on the **same** Wi-Fi network.
2. Open your React Native app on your device.
3. You'll see a [red screen with an error](/docs/debugging#logbox). This is OK. The following steps will fix that.
4. Open the in-app [Dev Menu](/docs/debugging#opening-the-dev-menu).
5. Go to **Dev Settings** → **Debug server host & port for device**.
6. Type in your machine's IP address and the port of the local dev server (e.g. `10.0.1.1:8081`).
7. Go back to the **Dev Menu** and select **Reload JS**.

You can now enable Fast Refresh from the [Dev Menu](/docs/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

## Building your app for production[​](#building-your-app-for-production-1 "Direct link to Building your app for production")

You have built a great app using React Native, and you are now itching to release it in the Play Store. The process is the same as any other native Android app, with some additional considerations to take into account. Follow the guide for [generating a signed APK](/docs/signed-apk-android) to learn more.

### 1. Enable Debugging over USB[​](#1-enable-debugging-over-usb-2 "Direct link to 1. Enable Debugging over USB")

Most Android devices can only install and run apps downloaded from Google Play, by default. You will need to enable USB Debugging on your device in order to install your app during development.

To enable USB debugging on your device, you will first need to enable the "Developer options" menu by going to **Settings** → **About phone** → **Software information** and then tapping the `Build number` row at the bottom seven times. You can then go back to **Settings** → **Developer options** to enable "USB debugging".

### 2. Plug in your device via USB[​](#2-plug-in-your-device-via-usb-2 "Direct link to 2. Plug in your device via USB")

Let's now set up an Android device to run our React Native projects. Go ahead and plug in your device via USB to your development machine.

Next, check the manufacturer code by using `lsusb` (on mac, you must first [install lsusb](https://github.com/jlhonora/lsusb)). `lsusb` should output something like this:

```
$ lsusb

Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub

Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 001 Device 003: ID 22b8:2e76 Motorola PCS

Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub

Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub

Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
```

These lines represent the USB devices currently connected to your machine.

You want the line that represents your phone. If you're in doubt, try unplugging your phone and running the command again:

```
$ lsusb

Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub

Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub

Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub

Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
```

You'll see that after removing the phone, the line which has the phone model ("Motorola PCS" in this case) disappeared from the list. This is the line that we care about.

`Bus 001 Device 003: ID 22b8:2e76 Motorola PCS`

From the above line, you want to grab the first four digits from the device ID:

`22b8:2e76`

In this case, it's `22b8`. That's the identifier for Motorola.

You'll need to input this into your udev rules in order to get up and running:

```
echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", MODE="0666", GROUP="plugdev"' | sudo tee /etc/udev/rules.d/51-android-usb.rules
```

Make sure that you replace `22b8` with the identifier you get in the above command.

Now check that your device is properly connecting to ADB, the Android Debug Bridge, by running `adb devices`.

```
$ adb devices

List of devices attached

emulator-5554 offline   # Google emulator

14ed2fcc device         # Physical device
```

Seeing `device` in the right column means the device is connected. You must have **only one device connected** at a time.

### 3. Run your app[​](#3-run-your-app-2 "Direct link to 3. Run your app")

From the root of your project, type the following in your command prompt to install and launch your app on the device:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

note

If you get a "bridge configuration isn't available" error, see [Using adb reverse](/docs/running-on-device#method-1-using-adb-reverse-recommended).

```
$ adb -s <device name> reverse tcp:8081 tcp:8081
```

To find the device name, run the following adb command:

```
$ adb devices
```

You can now enable Fast Refresh from the [Dev Menu](/docs/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

### Method 2: Connect via Wi-Fi[​](#method-2-connect-via-wi-fi-2 "Direct link to Method 2: Connect via Wi-Fi")

You can also connect to the development server over Wi-Fi. You'll first need to install the app on your device using a USB cable, but once that has been done you can debug wirelessly by following these instructions. You'll need your development machine's current IP address before proceeding.

Open a terminal and type `/sbin/ifconfig` to find your machine's IP address.

1. Make sure your laptop and your phone are on the **same** Wi-Fi network.
2. Open your React Native app on your device.
3. You'll see a [red screen with an error](/docs/debugging#logbox). This is OK. The following steps will fix that.
4. Open the in-app [Dev Menu](/docs/debugging#opening-the-dev-menu).
5. Go to **Dev Settings** → **Debug server host & port for device**.
6. Type in your machine's IP address and the port of the local dev server (e.g. `10.0.1.1:8081`).
7. Go back to the **Dev Menu** and select **Reload JS**.

You can now enable Fast Refresh from the [Dev Menu](/docs/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

## Building your app for production[​](#building-your-app-for-production-2 "Direct link to Building your app for production")

You have built a great app using React Native, and you are now itching to release it in the Play Store. The process is the same as any other native Android app, with some additional considerations to take into account. Follow the guide for [generating a signed APK](/docs/signed-apk-android) to learn more.

You can also iterate quickly on a device using the development server. You only have to be on the same Wi-Fi network as your computer. Shake your device to open the [Dev Menu](/docs/debugging#opening-the-dev-menu), then enable Fast Refresh. Your app will reload whenever your JavaScript code has changed.

### Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting")

tip

If you have any issues, ensure that your Mac and device are on the same network and can reach each other. Many open wireless networks with captive portals are configured to prevent devices from reaching other devices on the network. You may use your device's Personal Hotspot feature in this case. You may also share your internet (Wi-Fi/Ethernet) connection from your Mac to your device via USB and connect to the bundler through this tunnel for very high transfer speeds.

When trying to connect to the development server you might get a [red screen with an error](/docs/debugging#logbox) saying:

You have built a great app using React Native, and you are now itching to release it in the App Store. The process is the same as any other native iOS app, with some additional considerations to take into account. Follow the guide for [publishing to the Apple App Store](/docs/publishing-to-app-store) to learn more.

info

A Mac is required in order to build your app for iOS devices. Alternatively, you can refer to our [environment setup guide](/docs/environment-setup) to learn how to build your app using Expo CLI, which will allow you to run your app using the Expo client app.

info

A Mac is required in order to build your app for iOS devices. Alternatively, you can refer to our [environment setup guide](/docs/environment-setup) to learn how to build your app using Expo CLI, which will allow you to run your app using the Expo client app.

----
url: https://reactnative.dev/docs/the-new-architecture/what-is-codegen
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

----
url: https://reactnative.dev/docs/next/accessibility
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/accessibility)** (0.87).

Version: Next

```
<View>

  <View accessible={true} />

  <View />

</View>
```

In the above example, accessibility focus is only available on the first child view with the `accessible` property, and not for the parent or sibling without `accessible`.

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

When a view is marked as accessible, it is a good practice to set an `accessibilityLabel` on the view, so that people who use VoiceOver or TalkBack know what element they have selected. A screen reader will verbalize this string when the associated element is selected.

To use, set the `accessibilityLabel` property to a custom string on your View, Text, or Touchable:

React TSX

```
<TouchableOpacity

  accessible={true}

  accessibilityLabel="Tap me!"

  onPress={onPress}>

  <View style={styles.button}>

    <Text style={styles.buttonText}>Press me!</Text>

  </View>

</TouchableOpacity>
```

In the above example, the `accessibilityLabel` on the TouchableOpacity element would default to "Press me!". The label is constructed by concatenating all Text node children separated by spaces.

### `accessibilityLabelledBy`Android[​](#accessibilitylabelledby-android "Direct link to accessibilitylabelledby-android")

A reference to another element [nativeID](/docs/next/view#nativeid) used to build complex forms. The value of `accessibilityLabelledBy` should match the `nativeID` of the related element:

React TSX

```
<View>

  <Text nativeID="formLabel">Label for Input Field</Text>

  <TextInput

    accessibilityLabel="input"

    accessibilityLabelledBy="formLabel"

  />

</View>
```

In the above example, the screen reader announces `Input, Edit Box for Label for Input Field` when focusing on the TextInput.

### `accessibilityHint`[​](#accessibilityhint "Direct link to accessibilityhint")

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:

React TSX

```
<TouchableOpacity

  accessible={true}

  accessibilityLabel="Go back"

  accessibilityHint="Navigates to the previous screen"

  onPress={onPress}>

  <View style={styles.button}>

    <Text style={styles.buttonText}>Back</Text>

  </View>

</TouchableOpacity>
```

```
<View

  accessible={true}

  accessibilityLabel="Pizza"

  accessibilityLanguage="it-IT">

  <Text>🍕</Text>

</View>
```

```
<TouchableWithoutFeedback onPress={addOne}>

  <View style={styles.embedded}>

    <Text>Click me</Text>

  </View>

</TouchableWithoutFeedback>

<Text accessibilityLiveRegion="polite">

  Clicked {count} times

</Text>
```

```
<View

  accessibilityShowsLargeContentViewer={true}

  accessibilityLargeContentTitle="Home Tab">

  <Text>Home</Text>

</View>
```

### `accessibilityState`[​](#accessibilitystate "Direct link to accessibilitystate")

Describes the current state of a component to the assistive technology user.

`accessibilityState` is an object. It contains the following fields:

| Name     | Description                                                                                                                           | Type               | Required |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | -------- |
| disabled | Indicates whether the element is disabled or not.                                                                                     | boolean            | No       |
| selected | Indicates whether a selectable element is currently selected or not.                                                                  | boolean            | No       |
| checked  | Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes. | boolean or 'mixed' | No       |
| busy     | Indicates whether an element is currently busy or not.                                                                                | boolean            | No       |
| expanded | Indicates whether an expandable element is currently expanded or collapsed.                                                           | boolean            | No       |

To use, set the `accessibilityState` to an object with a specific definition.

### `accessibilityValue`[​](#accessibilityvalue "Direct link to accessibilityvalue")

Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, it contains range information (minimum, current, and maximum).

`accessibilityValue` is an object. It contains the following fields:

| Name | Description                                                                                    | Type    | Required                  |
| ---- | ---------------------------------------------------------------------------------------------- | ------- | ------------------------- |
| min  | The minimum value of this component's range.                                                   | integer | Required if `now` is set. |
| max  | The maximum value of this component's range.                                                   | integer | Required if `now` is set. |
| now  | The current value of this component's range.                                                   | integer | No                        |
| text | A textual description of this component's value. Will override `min`, `now`, and `max` if set. | string  | No                        |

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-checked`[​](#aria-checked "Direct link to aria-checked")

Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

| Type             | Default |
| ---------------- | ------- |
| boolean, 'mixed' | false   |

### `aria-disabled`[​](#aria-disabled "Direct link to aria-disabled")

Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-expanded`[​](#aria-expanded "Direct link to aria-expanded")

Indicates whether an expandable element is currently expanded or collapsed.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-hidden`[​](#aria-hidden "Direct link to aria-hidden")

Indicates whether the element is hidden from assistive technologies.

For example, in a window that contains sibling views `A` and `B`, setting `aria-hidden` to `true` on view `B` causes VoiceOver to ignore the `B` element and its children.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-label`[​](#aria-label "Direct link to aria-label")

Defines a string value that can be used to name an element.

| Type   |
| ------ |
| string |

### `aria-labelledby`Android[​](#aria-labelledby-android "Direct link to aria-labelledby-android")

Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the [`nativeID`](/docs/next/view#nativeid) of the related element:

React TSX

```
<View>

  <Text nativeID="formLabel">Label for Input Field</Text>

  <TextInput aria-label="input" aria-labelledby="formLabel" />

</View>
```

| Type   |
| ------ |
| string |

### `aria-live`Android[​](#aria-live-android "Direct link to aria-live-android")

Indicates that an element will be updated and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

* **off** 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.

| Type                                     | Default |
| ---------------------------------------- | ------- |
| enum(`'assertive'`, `'off'`, `'polite'`) | `'off'` |

***

### `aria-modal`iOS[​](#aria-modal-ios "Direct link to aria-modal-ios")

Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-selected`[​](#aria-selected "Direct link to aria-selected")

Indicates whether a selectable element is currently selected or not.

| Type    |
| ------- |
| boolean |

### `experimental_accessibilityOrder`[​](#experimental_accessibilityorder "Direct link to experimental_accessibilityorder")

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

note

For the sake of brevity, layout is excluded in the following examples even though it dictates the default focus order. Assume the document order matches the layout order.

`experimental_accessibilityOrder` lets you define the order in which assistive technologies focus descendant components. It is an array of [`nativeIDs`](/docs/next/view#nativeid) that are set on the components whose order you are controlling. For example:

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View accessible={true} nativeID="C"/>

</View>
```

Assistive technologies will focus the `View` with `nativeID` of `B`, then `C`, then `A`.

`experimental_accessibilityOrder` will not “turn on” accessibility for the components it references, that still needs to be done. So if we remove `accessible={true}` on `C` above like so

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View nativeID="C"/>

</View>
```

then the new order will be `B` then `A`, even though `C` is still in `experimental_accessibilityOrder`.

`experimental_accessibilityOrder` will “turn off” accessibility of components it doesn’t reference, however.

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View accessible={true} nativeID="C"/>

  <View accessible={true} nativeID="D"/>

</View>
```

The order of the above example would be `B`, `C`, `A`. `D` will never get focused. In this sense `experimental_accessibilityOrder` is *exhaustive*.

There are still valid reasons to include an non-accessible component in `experimental_accessibilityOrder`. Consider

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View nativeID="C">

    <View accessible={true} nativeID="D"/>

    <View accessible={true} nativeID="E"/>

    <View accessible={true} nativeID="F"/>

  </View>

</View>
```

The focus order will be `B`, `D`, `E`, `F`, `A`. Even though `D`, `E`, and `F` are not directly referenced in `experimental_accessibilityOrder`, `C` is directly referenced. In this instance `C` in an *accessibility container* - it contains accessible elements, but is not accessible itself. If an accessibility container is referenced in `experimental_accessibilityOrder` then the default order of the elements it contains is applied. In this sense `experimental_accessibilityOrder` is *nestable*.

`experimental_accessibilityOrder` can also reference another component with `experimental_accessibilityOrder`

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View nativeID="C" experimental_accessibilityOrder={['F', 'E', 'D']}>

    <View accessible={true} nativeID="D"/>

    <View accessible={true} nativeID="E"/>

    <View accessible={true} nativeID="F"/>

  </View>

</View>
```

The focus order will be `B`, `F`, `E`, `D`, `A`.

A component cannot be both an accessibility container and an accessibility element (`accessible={true}`). So if we have

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View accessible={true} nativeID="C" experimental_accessibilityOrder={['F', 'E', 'D']}>

    <View accessible={true} nativeID="D"/>

    <View accessible={true} nativeID="E"/>

    <View accessible={true} nativeID="F"/>

  </View>

</View>
```

The focus order would be `B`, `C`, `A`. `D`, `E`, and `F` are no longer in a container, so the exhaustive nature of `experimental_accessibilityOrder` means they will be excluded.

### `importantForAccessibility`Android[​](#importantforaccessibility-android "Direct link to 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).

React TSX

```
<View style={styles.container}>

  <View

    style={[styles.layout, {backgroundColor: 'green'}]}

    importantForAccessibility="yes">

    <Text>First layout</Text>

  </View>

  <View

    style={[styles.layout, {backgroundColor: 'yellow'}]}

    importantForAccessibility="no-hide-descendants">

    <Text>Second layout</Text>

  </View>

</View>
```

`role` communicates the purpose of a component and has precedence over the [`accessibilityRole`](/docs/next/accessibility#accessibilityrole) prop.

| Name  | Type   | Required |
| ----- | ------ | -------- |
| name  | string | Yes      |
| label | string | No       |

```
<View

  accessible={true}

  accessibilityActions={[

    {name: 'cut', label: 'cut'},

    {name: 'copy', label: 'copy'},

    {name: 'paste', label: 'paste'},

  ]}

  onAccessibilityAction={event => {

    switch (event.nativeEvent.actionName) {

      case 'cut':

        Alert.alert('Alert', 'cut action success');

        break;

      case 'copy':

        Alert.alert('Alert', 'copy action success');

        break;

      case 'paste':

        Alert.alert('Alert', 'paste action success');

        break;

    }

  }}

/>
```

## Checking if a Screen Reader is Enabled[​](#checking-if-a-screen-reader-is-enabled "Direct link to Checking if a Screen Reader is Enabled")

The `AccessibilityInfo` API allows you to determine whether or not a screen reader is currently active. See the [AccessibilityInfo documentation](/docs/next/accessibilityinfo) for details.

## Sending Accessibility EventsAndroid[​](#sending-accessibility-events-android "Direct link to sending-accessibility-events-android")

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`.

React TSX

```
import {Platform, UIManager, findNodeHandle} from 'react-native';



if (Platform.OS === 'android') {

  UIManager.sendAccessibilityEvent(

    findNodeHandle(this),

    UIManager.AccessibilityEventTypes.typeViewFocused,

  );

}
```

## Testing TalkBack SupportAndroid[​](#testing-talkback-support-android "Direct link to testing-talkback-support-android")

To enable TalkBack, go to the Settings app on your Android device or emulator. Tap Accessibility, then TalkBack. Toggle the "Use service" switch to enable or disable it.

Android emulators don't have TalkBack installed by default. You can install TalkBack on your emulator via the Google Play Store. Make sure to choose an emulator with the Google Play store installed. These are available in Android Studio.

You can use the volume key shortcut to toggle TalkBack. To turn on the volume key shortcut, go to the Settings app, then Accessibility. At the top, turn on the volume key shortcut.

To use the volume key shortcut, press both volume keys for 3 seconds to start an accessibility tool.

Additionally, if you prefer, you can toggle TalkBack via the command line with:

```
# disable

adb shell settings put secure enabled_accessibility_services com.android.talkback/com.google.android.marvin.talkback.TalkBackService



# enable

adb shell settings put secure enabled_accessibility_services com.google.android.marvin.talkback/com.google.android.marvin.talkback.TalkBackService
```

    [Android](#accessibilitylabelledby-android)
  * [`accessibilityHint`](#accessibilityhint)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)
  * [`accessibilityIgnoresInvertColors`](#accessibilityignoresinvertcolors-ios)

    [iOS](#accessibilityignoresinvertcolors-ios)
  * [`accessibilityLiveRegion`](#accessibilityliveregion-android)

    [Android](#accessibilityliveregion-android)
  * [`accessibilityRole`](#accessibilityrole)
  * [`accessibilityShowsLargeContentViewer`](#accessibilityshowslargecontentviewer-ios)

    [iOS](#accessibilityshowslargecontentviewer-ios)
  * [`accessibilityLargeContentTitle`](#accessibilitylargecontenttitle-ios)

    [iOS](#accessibilitylargecontenttitle-ios)
  * [`accessibilityState`](#accessibilitystate)
  * [`accessibilityValue`](#accessibilityvalue)
  * [`accessibilityViewIsModal`](#accessibilityviewismodal-ios)

    [iOS](#accessibilityviewismodal-ios)
  * [`accessibilityElementsHidden`](#accessibilityelementshidden-ios)

    [iOS](#accessibilityelementshidden-ios)

    [Android](#aria-labelledby-android)
  * [`aria-live`](#aria-live-android)

    [Android](#aria-live-android)
  * [`aria-modal`](#aria-modal-ios)

    [iOS](#aria-modal-ios)
  * [`aria-selected`](#aria-selected)
  * [`experimental_accessibilityOrder`](#experimental_accessibilityorder)
  * [`importantForAccessibility`](#importantforaccessibility-android)

    [Android](#importantforaccessibility-android)
  * [`onAccessibilityEscape`](#onaccessibilityescape-ios)

    [iOS](#onaccessibilityescape-ios)
  * [`onAccessibilityTap`](#onaccessibilitytap-ios)

    [iOS](#onaccessibilitytap-ios)
  * [`onMagicTap`](#onmagictap-ios)

    [iOS](#onmagictap-ios)

----
url: https://reactnative.dev/docs/layoutevent
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`LayoutEvent` object is returned in the callback as a result of component layout change, for example `onLayout` in [View](/docs/view) component.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

    layout: {

        width: 520,

        height: 70.5,

        x: 0,

        y: 42.5

    },

    target: 1127

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `height`[​](#height "Direct link to height")

Height of the component after the layout changes.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `width`[​](#width "Direct link to width")

Width of the component after the layout changes.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `x`[​](#x "Direct link to x")

Component X coordinate inside the parent component.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `y`[​](#y "Direct link to y")

Component Y coordinate inside the parent component.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `target`[​](#target "Direct link to target")

The node id of the element receiving the LayoutEvent.

| Type                        | Optional |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

## Used by[​](#used-by "Direct link to Used by")

* [`Image`](/docs/image)
* [`Pressable`](/docs/pressable)
* [`ScrollView`](/docs/scrollview)
* [`Text`](/docs/text)
* [`TextInput`](/docs/textinput)
* [`TouchableWithoutFeedback`](/docs/touchablewithoutfeedback)
* [`View`](/docs/view)

----
url: https://reactnative.dev/docs/next/appstate
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/appstate)** (0.87).

Version: Next

***

# Reference

## Events[​](#events "Direct link to Events")

### `change`[​](#change "Direct link to change")

This event is received when the app state has changed. The listener is called with one of [the current app state values](/docs/next/appstate#app-states).

```
static addEventListener(

  type: AppStateEvent,

  listener: (state: AppStateStatus) => void,

): EventSubscription;
```

Sets up a function that will be called whenever the specified event type on AppState occurs. Valid values for `eventType` are [listed above](#events). Returns the `EventSubscription`.

## Properties[​](#properties "Direct link to Properties")

### `currentState`[​](#currentstate "Direct link to currentstate")

React TSX

```
static currentState: AppStateStatus;
```

* [App States](#app-states)

* [Basic Usage](#basic-usage)

* [Events](#events)

  * [`change`](#change)
  * [`memoryWarning`](#memorywarning-ios)

    [iOS](#memorywarning-ios)
  * [`focus`](#focus-android)

    [Android](#focus-android)
  * [`blur`](#blur-android)

    [Android](#blur-android)

* [Methods](#methods)
  * [`addEventListener()`](#addeventlistener)

* [Properties](#properties)
  * [`currentState`](#currentstate)

----
url: https://reactnative.dev/docs/next/metro
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/metro)** (0.87).

Version: Next

```
const {

  getDefaultConfig,

  mergeConfig,

} = require('@react-native/metro-config');



/**

 * Metro configuration

 * https://metrobundler.dev/docs/configuration

 *

 * @type {import('metro-config').MetroConfig}

 */

const config = {};



module.exports = mergeConfig(getDefaultConfig(__dirname), config);
```

Metro options you wish to customize can be done so within the `config` object.

### Advanced: Using a config function[​](#advanced-using-a-config-function "Direct link to Advanced: Using a config function")

Exporting a config function is an opt-in to managing the final config yourself — **Metro will not apply any internal defaults**. This pattern can be useful when needing to read the base default config object from Metro or to set options dynamically.

info

**From `@react-native/metro-config` 0.72.1**, it is no longer necessary to use a config function to access the complete default config. See the **Tip** section below.

JavaScript

```
const {

  getDefaultConfig,

  mergeConfig,

} = require('@react-native/metro-config');



module.exports = function (baseConfig) {

  const defaultConfig = mergeConfig(

    baseConfig,

    getDefaultConfig(__dirname),

  );

  const {

    resolver: {assetExts, sourceExts},

  } = defaultConfig;



  return mergeConfig(defaultConfig, {

    resolver: {

      assetExts: assetExts.filter(ext => ext !== 'svg'),

      sourceExts: [...sourceExts, 'svg'],

    },

  });

};
```

tip

Using a config function is for advanced use cases. A simpler method than the above, e.g. for customising `sourceExts`, would be to read these defaults from `@react-native/metro-config`.

**Alternative**

JavaScript

```
const defaultConfig = getDefaultConfig(__dirname);



const config = {

  resolver: {

    sourceExts: [...defaultConfig.resolver.sourceExts, 'svg'],

  },

};



module.exports = mergeConfig(defaultConfig, config);
```

**However!**, we recommend copying and editing when overriding these config values — placing the source of truth in your config file.

✅ **Recommended**

JavaScript

```
const config = {

  resolver: {

    sourceExts: ['js', 'ts', 'tsx', 'svg'],

  },

};
```

## Learn more about Metro[​](#learn-more-about-metro "Direct link to Learn more about Metro")

* [Metro website](https://metrobundler.dev/)
* [Video: "Metro & React Native DevX" talk at App.js 2023](https://www.youtube.com/watch?v=c9D4pg0y9cI)

- [Configuring Metro](#configuring-metro)
  * [Advanced: Using a config function](#advanced-using-a-config-function)
- [Learn more about Metro](#learn-more-about-metro)

----
url: https://reactnative.dev/docs/animations
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Animations are very important to create a great user experience. Stationary objects must overcome inertia as they start moving. Objects in motion have momentum and rarely come to a stop immediately. Animations allow you to convey physically believable motion in your interface.

React Native provides two complementary animation systems: [`Animated`](/docs/animations#animated-api) for granular and interactive control of specific values, and [`LayoutAnimation`](/docs/animations#layoutanimation-api) for animated global layout transactions.

## `Animated` API[​](#animated-api "Direct link to animated-api")

The [`Animated`](/docs/animated) API is designed to concisely express a wide variety of interesting animation and interaction patterns in a very performant way. `Animated` focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and `start`/`stop` methods to control time-based animation execution.

`Animated` provides several animation types, the most commonly used one being [`Animated.timing()`](/docs/animated#timing). It supports animating a value over time using one of various predefined easing functions, or you can use your own. Easing functions are typically used in animation to convey gradual acceleration and deceleration of objects.

By default, `timing` will use an easeInOut curve that conveys gradual acceleration to full speed and concludes by gradually decelerating to a stop. You can specify a different easing function by passing an `easing` parameter. Custom `duration` or even a `delay` before the animation starts is also supported.

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:

React TSX

```
Animated.timing(this.state.xPosition, {

  toValue: 100,

  easing: Easing.back(),

  duration: 2000,

  useNativeDriver: true,

}).start();
```

Take a look at the [Configuring animations](/docs/animated#configuring-animations) section of the `Animated` API reference to learn more about all the config parameters supported by the built-in animations.

### Composing animations[​](#composing-animations "Direct link to Composing animations")

Animations can be combined and played in sequence or in parallel. Sequential animations can play immediately after the previous animation has finished, or they can start after a specified delay. The `Animated` API provides several methods, such as `sequence()` and `delay()`, each of which take an array of animations to execute and automatically calls `start()`/`stop()` as needed.

For example, the following animation coasts to a stop, then it springs back while twirling in parallel:

React TSX

```
Animated.sequence([

  // decay, then spring to start and twirl

  Animated.decay(position, {

    // coast to a stop

    velocity: {x: gestureState.vx, y: gestureState.vy}, // velocity from gesture release

    deceleration: 0.997,

    useNativeDriver: true,

  }),

  Animated.parallel([

    // after decay, in parallel:

    Animated.spring(position, {

      toValue: {x: 0, y: 0}, // return to start

      useNativeDriver: true,

    }),

    Animated.timing(twirl, {

      // and twirl

      toValue: 360,

      useNativeDriver: true,

    }),

  ]),

]).start(); // start the sequence group
```

If one animation is stopped or interrupted, then all other animations in the group are also stopped. `Animated.parallel` has a `stopTogether` option that can be set to `false` to disable this.

You can find a full list of composition methods in the [Composing animations](/docs/animated#composing-animations) section of the `Animated` API reference.

### Combining animated values[​](#combining-animated-values "Direct link to Combining animated values")

You can [combine two animated values](/docs/animated#combining-animated-values) via addition, multiplication, division, or modulo to make a new animated value.

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):

React TSX

```
const a = new Animated.Value(1);

const b = Animated.divide(1, a);



Animated.spring(a, {

  toValue: 2,

  useNativeDriver: true,

}).start();
```

### Interpolation[​](#interpolation "Direct link to Interpolation")

Each property can be run through an interpolation first. An interpolation maps input ranges to output ranges, typically using a linear interpolation but also supports easing functions. By default, it will extrapolate the curve beyond the ranges given, but you can also have it clamp the output value.

A basic mapping to convert a 0-1 range to a 0-100 range would be:

React TSX

```
value.interpolate({

  inputRange: [0, 1],

  outputRange: [0, 100],

});
```

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:

React TSX

```
  style={{

    opacity: this.state.fadeAnim, // Binds directly

    transform: [{

      translateY: this.state.fadeAnim.interpolate({

        inputRange: [0, 1],

        outputRange: [150, 0]  // 0 : 150, 0.5 : 75, 1 : 0

      }),

    }],

  }}
```

[`interpolate()`](/docs/animatedvalue#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:

React TSX

```
value.interpolate({

  inputRange: [-300, -100, 0, 100, 101],

  outputRange: [300, 0, 1, 0, 0],

});
```

Which would map like so:

```
Input | Output

------|-------

  -400|    450

  -300|    300

  -200|    150

  -100|      0

   -50|    0.5

     0|      1

    50|    0.5

   100|      0

   101|      0

   200|      0
```

`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:

React TSX

```
value.interpolate({

  inputRange: [0, 360],

  outputRange: ['0deg', '360deg'],

});
```

`interpolate()` also supports arbitrary easing functions, many of which are already implemented in the [`Easing`](/docs/easing) module. `interpolate()` also has configurable behavior for extrapolating the `outputRange`. You can set the extrapolation by setting the `extrapolate`, `extrapolateLeft`, or `extrapolateRight` options. The default value is `extend` but you can use `clamp` to prevent the output value from exceeding `outputRange`.

### Tracking dynamic values[​](#tracking-dynamic-values "Direct link to Tracking dynamic values")

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:

React TSX

```
Animated.spring(follower, {toValue: leader}).start();

Animated.timing(opacity, {

  toValue: pan.x.interpolate({

    inputRange: [0, 300],

    outputRange: [1, 0],

  }),

  useNativeDriver: true,

}).start();
```

The `leader` and `follower` animated values would be implemented using `Animated.ValueXY()`. `ValueXY` is a handy way to deal with 2D interactions, such as panning or dragging. It is a basic wrapper that contains two `Animated.Value` instances and some helper functions that call through to them, making `ValueXY` a drop-in replacement for `Value` in many cases. It allows us to track both x and y values in the example above.

### Tracking gestures[​](#tracking-gestures "Direct link to Tracking gestures")

Gestures, like panning or scrolling, and other events can map directly to animated values using [`Animated.event`](/docs/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`):

React TSX

```
onScroll={Animated.event(

  // scrollX = e.nativeEvent.contentOffset.x

  [{

    nativeEvent: {

      contentOffset: { x: scrollX }

    }

  }],

  {useNativeDriver: true}

)}
```

The following example implements a horizontal scrolling carousel where the scroll position indicators are animated using the `Animated.event` used in the `ScrollView`

#### ScrollView with Animated Event Example[​](#scrollview-with-animated-event-example "Direct link to ScrollView with Animated Event Example")

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`.

React TSX

```
onPanResponderMove={Animated.event(

  [null, // ignore the native event

  // extract dx and dy from gestureState

  // like 'pan.x = gestureState.dx, pan.y = gestureState.dy'

  {dx: pan.x, dy: pan.y}

])}
```

```
Animated.timing(this.state.animatedValue, {

  toValue: 1,

  duration: 500,

  useNativeDriver: true, // <-- Set this to true

}).start();
```

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.

React TSX

```
<Animated.ScrollView // <-- Use the Animated ScrollView wrapper

  onScroll={Animated.event(

    [

      {

        nativeEvent: {

          contentOffset: {y: this.state.animatedValue},

        },

      },

    ],

    {useNativeDriver: true}, // <-- Set this to true

  )}>

  {content}

</Animated.ScrollView>
```

```
<Animated.View

  style={{

    transform: [

      {scale: this.state.scale},

      {rotateY: this.state.rotateY},

      {perspective: 1000}, // without this line this Animation will not render on Android while working fine on iOS

    ],

  }}

/>
```

```
UIManager.setLayoutAnimationEnabledExperimental(true);
```

This example uses a preset value, you can customize the animations as you need, see [LayoutAnimation.js](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/LayoutAnimation/LayoutAnimation.js) for more information.

## Additional notes[​](#additional-notes "Direct link to Additional notes")

### `requestAnimationFrame`[​](#requestanimationframe "Direct link to requestanimationframe")

`requestAnimationFrame` is a polyfill from the browser that you might be familiar with. It accepts a function as its only argument and calls that function before the next repaint. It is an essential building block for animations that underlies all of the JavaScript-based animation APIs. In general, you shouldn't need to call this yourself - the animation APIs will manage frame updates for you.

### `setNativeProps`[​](#setnativeprops "Direct link to setnativeprops")

As mentioned [in the Direct Manipulation section](/docs/legacy/direct-manipulation), `setNativeProps` allows us to modify properties of native-backed components (components that are actually backed by native views, unlike composite components) directly, without having to `setState` and re-render the component hierarchy.

----
url: https://reactnative.dev/docs/global-FileReader
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) for more information.

The global `FileReader` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/legacy/native-modules-setup
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

Native modules are usually distributed as npm packages, except that on top of the usual JavaScript they will include some native code per platform. To understand more about npm packages you may find [this guide](https://docs.npmjs.com/packages-and-modules/contributing-packages-to-the-registry) useful.

To get set up with the basic project structure for a native module we will use the community tool called [create-react-native-library](https://callstack.github.io/react-native-builder-bob/create). You can go ahead further and dive deep into how that library works, but for our needs we will only execute the basic script:

```
npx create-react-native-library@latest react-native-awesome-module
```

Where `react-native-awesome-module` is the name you would like for the new module. After doing this you will navigate into `react-native-awesome-module` folder and bootstrap the example project by running:

```
yarn
```

When the bootstrap is done, you will be able to start the example app by executing one of the following commands:

```
# Android app

yarn example android

# iOS app

yarn example ios
```

When all steps above are done, you will be able to continue with [Android Native Modules](/docs/legacy/native-modules-android) or [iOS Native Modules](/docs/legacy/native-modules-ios) guides to add in some code.

----
url: https://reactnative.dev/docs/next/drawerlayoutandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/drawerlayoutandroid)** (0.87).

Version: Next

Deprecated

Use [`react-native-drawer-layout`](https://reactnavigation.org/docs/drawer-layout/) instead.

React component that wraps the platform `DrawerLayout` (Android only). The Drawer (typically used for navigation) is rendered with `renderNavigationView` and direct children are the main view (where your content goes). The navigation view is initially not visible on the screen, but can be pulled in from the side of the window specified by the `drawerPosition` prop and its width can be set by the `drawerWidth` prop.

## Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### `drawerBackgroundColor`[​](#drawerbackgroundcolor "Direct link to 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:

React TSX

```
return (

  <DrawerLayoutAndroid drawerBackgroundColor="rgba(0,0,0,0.5)" />

);
```

| Type                       | Required |
| -------------------------- | -------- |
| [color](/docs/next/colors) | No       |

***

### `drawerLockMode`[​](#drawerlockmode "Direct link to drawerlockmode")

Specifies the lock mode of the drawer. The drawer can be locked in 3 states:

* unlocked (default), meaning that the drawer will respond (open/close) to touch gestures.
* locked-closed, meaning that the drawer will stay closed and not respond to gestures.
* locked-open, meaning that the drawer will stay opened and not respond to gestures. The drawer may still be opened and closed programmatically (`openDrawer`/`closeDrawer`).

| Type                                             | Required |
| ------------------------------------------------ | -------- |
| enum('unlocked', 'locked-closed', 'locked-open') | No       |

***

### `drawerPosition`[​](#drawerposition "Direct link to drawerposition")

Specifies the side of the screen from which the drawer will slide in. By default it is set to `left`.

| Type                  | Required |
| --------------------- | -------- |
| enum('left', 'right') | No       |

***

### `drawerWidth`[​](#drawerwidth "Direct link to drawerwidth")

Specifies the width of the drawer, more precisely the width of the view that be pulled in from the edge of the window.

| Type   | Required |
| ------ | -------- |
| number | No       |

***

### `keyboardDismissMode`[​](#keyboarddismissmode "Direct link to keyboarddismissmode")

Determines whether the keyboard gets dismissed in response to a drag.

* 'none' (the default), drags do not dismiss the keyboard.
* 'on-drag', the keyboard is dismissed when a drag begins.

| Type                    | Required |
| ----------------------- | -------- |
| enum('none', 'on-drag') | No       |

***

### `onDrawerClose`[​](#ondrawerclose "Direct link to ondrawerclose")

Function called whenever the navigation view has been closed.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `onDrawerOpen`[​](#ondraweropen "Direct link to ondraweropen")

Function called whenever the navigation view has been opened.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `onDrawerSlide`[​](#ondrawerslide "Direct link to ondrawerslide")

Function called whenever there is an interaction with the navigation view.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `onDrawerStateChanged`[​](#ondrawerstatechanged "Direct link to ondrawerstatechanged")

Function called when the drawer state has changed. The drawer can be in 3 states:

* idle, meaning there is no interaction with the navigation view happening at the time
* dragging, meaning there is currently an interaction with the navigation view
* settling, meaning that there was an interaction with the navigation view, and the navigation view is now finishing its closing or opening animation

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `renderNavigationView`[​](#rendernavigationview "Direct link to rendernavigationview")

The navigation view that will be rendered to the side of the screen and can be pulled in.

| Type     | Required |
| -------- | -------- |
| function | Yes      |

***

### `statusBarBackgroundColor`[​](#statusbarbackgroundcolor "Direct link to statusbarbackgroundcolor")

Make the drawer take the entire screen and draw the background of the status bar to allow it to open over the status bar. It will only have an effect on API 21+.

| Type                       | Required |
| -------------------------- | -------- |
| [color](/docs/next/colors) | No       |

## Methods[​](#methods "Direct link to Methods")

### `closeDrawer()`[​](#closedrawer "Direct link to closedrawer")

React TSX

```
closeDrawer();
```

Closes the drawer.

***

### `openDrawer()`[​](#opendrawer "Direct link to opendrawer")

React TSX

```
openDrawer();
```

----
url: https://reactnative.dev/docs/next/imagebackground
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/imagebackground)** (0.87).

Version: Next

Deprecated

Use a [`View`](/docs/next/view) with an absolutely positioned [`Image`](/docs/next/image) instead.

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 [source code](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Image/ImageBackground.js) for more insight, and create your own custom component when needed.

Note that you must specify some width and height style attributes.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [Image Props](/docs/next/image#props)[​](#image-props "Direct link to image-props")

Inherits [Image Props](/docs/next/image#props).

***

### `imageStyle`[​](#imagestyle "Direct link to imagestyle")

| Type                                        |
| ------------------------------------------- |
| [Image Style](/docs/next/image-style-props) |

***

### `imageRef`[​](#imageref "Direct link to imageref")

A ref setter that will be assigned the [element node](/docs/next/element-nodes) of the inner `Image` component when mounted.

***

### `style`[​](#style "Direct link to style")

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

* [Example](#example)

* [Props](#props)

  * [Image Props](#image-props)
  * [`imageStyle`](#imagestyle)
  * [`imageRef`](#imageref)
  * [`style`](#style)

----
url: https://reactnative.dev/docs/pixelratio
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`PixelRatio` gives you access to the device's pixel density and font scale.

## Fetching a correctly sized image[​](#fetching-a-correctly-sized-image "Direct link to Fetching a correctly sized image")

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.

React TSX

```
const image = getImage({

  width: PixelRatio.getPixelSizeForLayoutSize(200),

  height: PixelRatio.getPixelSizeForLayoutSize(100),

});

<Image source={image} style={{width: 200, height: 100}} />;
```

## Pixel grid snapping[​](#pixel-grid-snapping "Direct link to Pixel grid snapping")

In iOS, you can specify positions and dimensions for elements with arbitrary precision, for example 29.674825. But, ultimately the physical display only have a fixed number of pixels, for example 640×1136 for iPhone SE (1st generation) or 828×1792 for iPhone 11. iOS tries to be as faithful as possible to the user value by spreading one original pixel into multiple ones to trick the eye. The downside of this technique is that it makes the resulting element look blurry.

In practice, we found out that developers do not want this feature and they have to work around it by doing manual rounding in order to avoid having blurry elements. In React Native, we are rounding all the pixels automatically.

We have to be careful when to do this rounding. You never want to work with rounded and unrounded values at the same time as you're going to accumulate rounding errors. Having even one rounding error is deadly because a one pixel border may vanish or be twice as big.

In React Native, everything in JavaScript and within the layout engine works with arbitrary precision numbers. It's only when we set the position and dimensions of the native element on the main thread that we round. Also, rounding is done relative to the root rather than the parent, again to avoid accumulating rounding errors.

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `get()`[​](#get "Direct link to get")

React TSX

```
static get(): number;
```

***

### `getFontScale()`[​](#getfontscale "Direct link to getfontscale")

React TSX

```
static getFontScale(): number;
```

Returns the scaling factor for font sizes. This is the ratio that is used to calculate the absolute font size, so any elements that heavily depend on that should use this to do calculations.

* on Android value reflects the user preference set in **Settings > Display > Font size**
* on iOS value reflects the user preference set in **Settings > Display & Brightness > Text Size**, value can also be updated in **Settings > Accessibility > Display & Text Size > Larger Text**

If a font scale is not set, this returns the device pixel ratio.

***

### `getPixelSizeForLayoutSize()`[​](#getpixelsizeforlayoutsize "Direct link to getpixelsizeforlayoutsize")

React TSX

```
static getPixelSizeForLayoutSize(layoutSize: number): number;
```

Converts a layout size (dp) to pixel size (px).

Guaranteed to return an integer number.

***

### `roundToNearestPixel()`[​](#roundtonearestpixel "Direct link to roundtonearestpixel")

React TSX

```
static roundToNearestPixel(layoutSize: number): number;
```

----
url: https://reactnative.dev/docs/security
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

| **Do** use async storage when...              | **Don't** use async storage for... |
| --------------------------------------------- | ---------------------------------- |
| Persisting non-sensitive data across app runs | Token storage                      |
| Persisting Redux state                        | Secrets                            |
| Persisting GraphQL state                      |                                    |
| Storing global app-wide variables             |                                    |

----
url: https://reactnative.dev/docs/intro-react
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
import {Text} from 'react-native';
```

Your component starts as a function:

React TSX

```
const Cat = () => {};
```

You can think of components as blueprints. Whatever a function component returns is rendered as a **React element.** React elements let you describe what you want to see on the screen.

Here the `Cat` component will render a `<Text>` element:

React TSX

```
const Cat = () => {

  return <Text>Hello, I am your cat!</Text>;

};
```

You can export your function component with JavaScript’s [`export default`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) for use throughout your app like so:

React TSX

```
const Cat = () => {

  return <Text>Hello, I am your cat!</Text>;

};



export default Cat;
```

You’ve already met [React Native’s Core Components](/docs/intro-react-native-components). React lets you nest these components inside each other to create new components. These nestable, reusable components are at the heart of the React paradigm.

For example, you can nest [`Text`](/docs/text) and [`TextInput`](/docs/textinput) inside a [`View`](/docs/view) below, and React Native will render them together:

#### Developer notes[​](#developer-notes "Direct link to Developer notes")

* Android
* Web

info

If you’re familiar with web development, `<View>` and `<Text>` might remind you of HTML! You can think of them as the `<div>` and `<p>` tags of application development.

info

On Android, you usually put your views inside `LinearLayout`, `FrameLayout`, `RelativeLayout`, etc. to define how the view’s children will be arranged on the screen. In React Native, `View` uses Flexbox for its children’s layout. You can learn more in [our guide to layout with Flexbox](/docs/flexbox).

Most of React Native’s Core Components can be customized with props, too. For example, when using [`Image`](/docs/image), you pass it a prop named [`source`](/docs/image#source) to define what image it shows:

`Image` has [many different props](/docs/image#props), including [`style`](/docs/image#style), which accepts a JS object of design and layout related property-value pairs.

note

Notice the double curly braces `{{ }}` surrounding `style`‘s width and height. In JSX, JavaScript values are referenced with `{}`. This is handy if you are passing something other than a string as props, like an array or number: `<Cat food={["fish", "kibble"]} age={2} />`. However, JS objects are ***also*** denoted with curly braces: `{width: 200, height: 200}`. Therefore, to pass a JS object in JSX, you must wrap the object in **another pair** of curly braces: `{{width: 200, height: 200}}`

You can build many things with props and the Core Components [`Text`](/docs/text), [`Image`](/docs/image), and [`View`](/docs/view)! But to build something interactive, you’ll need state.

```
import {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:

React TSX

```
const Cat = (props: CatProps) => {

  const [isHungry, setIsHungry] = useState(true);

  // ...

};
```

tip

You can use `useState` to track any kind of data: strings, numbers, Booleans, arrays, objects. For example, you can track the number of times a cat has been petted with `const [timesPetted, setTimesPetted] = useState(0)`!

Calling `useState` does two things:

* it creates a “state variable” with an initial value—in this case the state variable is `isHungry` and its initial value is `true`
* it creates a function to set that state variable’s value—`setIsHungry`

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`](/docs/button) Core Component and give it an `onPress` prop:

React TSX

```
<Button

  onPress={() => {

    setIsHungry(false);

  }}

  //..

/>
```

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:

React TSX

```
<Button

  //..

  disabled={!isHungry}

  title={isHungry ? 'Give me some food, please!' : 'Thank you!'}

/>
```

info

You might’ve noticed that although `isHungry` is a [const](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/const), it is seemingly reassignable! The `const` keyword here does not mean that the state itself is immutable. Rather, it means that the reference to the object, that contains the state and the function to update it, will not change. 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:

React TSX

```
const Cafe = () => {

  return (

    <>

      <Cat name="Munkustrap" />

      <Cat name="Spot" />

    </>

  );

};
```

info

See the `<>` and `</>` above? These bits of JSX are [fragments](https://react.dev/reference/react/Fragment). Adjacent JSX elements must be wrapped in an enclosing tag. Fragments let you do that without nesting an extra, unnecessary wrapping element like `View`.

***

Now that you’ve covered both React and React Native’s Core Components, let’s dive deeper on some of these core components by looking at [handling `<TextInput>`](/docs/handling-text-input).

* [Your first component](#your-first-component)
* [JSX](#jsx)
* [Custom Components](#custom-components)
* [Props](#props)
* [State](#state)

----
url: https://reactnative.dev/docs/next/image-style-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/image-style-props)** (0.87).

Version: Next

| Type                          | Default     |
| ----------------------------- | ----------- |
| enum(`'visible'`, `'hidden'`) | `'visible'` |

***

### `backgroundColor`[​](#backgroundcolor "Direct link to backgroundcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderBottomLeftRadius`[​](#borderbottomleftradius "Direct link to borderbottomleftradius")

| Type   |
| ------ |
| number |

***

### `borderBottomRightRadius`[​](#borderbottomrightradius "Direct link to borderbottomrightradius")

| Type   |
| ------ |
| number |

***

### `borderColor`[​](#bordercolor "Direct link to bordercolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `borderRadius`[​](#borderradius "Direct link to borderradius")

| Type   |
| ------ |
| number |

***

### `borderTopLeftRadius`[​](#bordertopleftradius "Direct link to bordertopleftradius")

| Type   |
| ------ |
| number |

***

### `borderTopRightRadius`[​](#bordertoprightradius "Direct link to bordertoprightradius")

| Type   |
| ------ |
| number |

***

### `borderWidth`[​](#borderwidth "Direct link to borderwidth")

| Type   |
| ------ |
| number |

***

### `opacity`[​](#opacity "Direct link to opacity")

Set an opacity value for the image. The number should be in the range from `0.0` to `1.0`.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

### `overflow`[​](#overflow "Direct link to overflow")

| Type                          | Default     |
| ----------------------------- | ----------- |
| enum(`'visible'`, `'hidden'`) | `'visible'` |

***

### `overlayColor`Android[​](#overlaycolor-android "Direct link to overlaycolor-android")

When the image has rounded corners, specifying an overlayColor will cause the remaining space in the corners to be filled with a solid color. This is useful in cases which are not supported by the Android implementation of rounded corners:

* Certain resize modes, such as `'contain'`
* Animated GIFs

A typical way to use this prop is with images displayed on a solid background and setting the `overlayColor` to the same color as the background.

For details of how this works under the hood, see [Fresco documentation](https://frescolib.org/docs/rounded-corners-and-circles.html).

| Type   |
| ------ |
| string |

***

| Type                                                              | Default   |
| ----------------------------------------------------------------- | --------- |
| enum(`'cover'`, `'contain'`, `'stretch'`, `'repeat'`, `'center'`) | `'cover'` |

***

### `objectFit`[​](#objectfit "Direct link to objectfit")

Determines how to resize the image when the frame doesn't match the raw image dimensions.

| Type                                                   | Default   |
| ------------------------------------------------------ | --------- |
| enum(`'cover'`, `'contain'`, `'fill'`, `'scale-down'`) | `'cover'` |

***

### `tintColor`[​](#tintcolor "Direct link to tintcolor")

Changes the color of all the non-transparent pixels to the tintColor.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

    [Android](#overlaycolor-android)
  * [`resizeMode`](#resizemode)
  * [`objectFit`](#objectfit)
  * [`tintColor`](#tintcolor)

----
url: https://reactnative.dev/docs/global-requestAnimationFrame
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame) for more information.

The global `requestAnimationFrame` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-EventCounts
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`EventCounts`](https://developer.mozilla.org/en-US/docs/Web/API/EventCounts) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/nodes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

----
url: https://reactnative.dev/docs/legacy/native-components-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
#import <MapKit/MapKit.h>



#import <React/RCTViewManager.h>



@interface RNTMapManager : RCTViewManager

@end



@implementation RNTMapManager



RCT_EXPORT_MODULE(RNTMap)



- (UIView *)view

{

  return [[MKMapView alloc] init];

}



@end
```

note

Do not attempt to set the `frame` or `backgroundColor` properties on the `UIView` instance that you expose through the `-view` method. React Native will overwrite the values set by your custom class in order to match your JavaScript component's layout props. If you need this granularity of control it might be better to wrap the `UIView` instance you want to style in another `UIView` and return the wrapper `UIView` instead. See [Issue 2948](https://github.com/react/react-native/issues/2948) for more context.

info

In the example above, we prefixed our class name with `RNT`. Prefixes are used to avoid name collisions with other frameworks. Apple frameworks use two-letter prefixes, and React Native uses `RCT` as a prefix. In order to avoid name collisions, we recommend using a three-letter prefix other than `RCT` in your own classes.

Then you need a little bit of JavaScript to make this a usable React component:

MapView\.tsx

```
import {requireNativeComponent} from 'react-native';



export default requireNativeComponent('RNTMap');
```

The `requireNativeComponent` function automatically resolves `RNTMap` to `RNTMapManager` and exports our native view for use in JavaScript.

MyApp.tsx

```
import MapView from './MapView.tsx';



export default function MyApp() {

  return <MapView style={{flex: 1}} />;

}
```

note

When rendering, don't forget to stretch the view, otherwise you'll be staring at a blank screen.

This is now a fully-functioning native map view component in JavaScript, complete with pinch-zoom and other native gesture support. We can't really control it from JavaScript yet, though.

## Properties[​](#properties "Direct link to Properties")

The first thing we can do to make this component more usable is to bridge over some native properties. Let's say we want to be able to disable zooming and specify the visible region. Disabling zoom is a boolean, so we add this one line:

RNTMapManager.m

```
RCT_EXPORT_VIEW_PROPERTY(zoomEnabled, BOOL)
```

Note that we explicitly specify the type as `BOOL` - React Native uses `RCTConvert` under the hood to convert all sorts of different data types when talking over the bridge, and bad values will show convenient "RedBox" errors to let you know there is an issue ASAP. When things are straightforward like this, the whole implementation is taken care of for you by this macro.

Now to actually disable zooming, we set the property in JavaScript:

MyApp.tsx

```
import MapView from './MapView.tsx';



export default function MyApp() {

  return <MapView zoomEnabled={false} style={{flex: 1}} />;

}
```

To document the properties (and which values they accept) of our MapView component we'll add a wrapper component and document the interface with TypeScript:

MapView\.tsx

```
import {requireNativeComponent} from 'react-native';



const RNTMap = requireNativeComponent('RNTMap');



export default function MapView(props: {

  /**

   * Whether the user may use pinch gestures to zoom in and out.

   */

  zoomEnabled?: boolean;

}) {

  return <RNTMap {...props} />;

}
```

Now we have a nicely documented wrapper component to work with.

Next, let's add the more complex `region` prop. We start by adding the native code:

RNTMapManager.m

```
RCT_CUSTOM_VIEW_PROPERTY(region, MKCoordinateRegion, MKMapView)

{

  [view setRegion:json ? [RCTConvert MKCoordinateRegion:json] : defaultView.region animated:YES];

}
```

Ok, this is more complicated than the `BOOL` case we had before. Now we have a `MKCoordinateRegion` type that needs a conversion function, and we have custom code so that the view will animate when we set the region from JS. Within the function body that we provide, `json` refers to the raw value that has been passed from JS. There is also a `view` variable which gives us access to the manager's view instance, and a `defaultView` that we use to reset the property back to the default value if JS sends us a null sentinel.

You could write any conversion function you want for your view - here is the implementation for `MKCoordinateRegion` via a category on `RCTConvert`. It uses an already existing category of ReactNative `RCTConvert+CoreLocation`:

RNTMapManager.m

```
#import "RCTConvert+Mapkit.h"
```

RCTConvert+Mapkit.h

```
#import <MapKit/MapKit.h>

#import <React/RCTConvert.h>

#import <CoreLocation/CoreLocation.h>

#import <React/RCTConvert+CoreLocation.h>



@interface RCTConvert (Mapkit)



+ (MKCoordinateSpan)MKCoordinateSpan:(id)json;

+ (MKCoordinateRegion)MKCoordinateRegion:(id)json;



@end



@implementation RCTConvert(MapKit)



+ (MKCoordinateSpan)MKCoordinateSpan:(id)json

{

  json = [self NSDictionary:json];

  return (MKCoordinateSpan){

    [self CLLocationDegrees:json[@"latitudeDelta"]],

    [self CLLocationDegrees:json[@"longitudeDelta"]]

  };

}



+ (MKCoordinateRegion)MKCoordinateRegion:(id)json

{

  return (MKCoordinateRegion){

    [self CLLocationCoordinate2D:json],

    [self MKCoordinateSpan:json]

  };

}



@end
```

These conversion functions are designed to safely process any JSON that the JS might throw at them by displaying "RedBox" errors and returning standard initialization values when missing keys or other developer errors are encountered.

To finish up support for the `region` prop, we can document it with TypeScript:

MapView\.tsx

```
import {requireNativeComponent} from 'react-native';



const RNTMap = requireNativeComponent('RNTMap');



export default function MapView(props: {

  /**

   * The region to be displayed by the map.

   *

   * The region is defined by the center coordinates and the span of

   * coordinates to display.

   */

  region?: {

    /**

     * Coordinates for the center of the map.

     */

    latitude: number;

    longitude: number;



    /**

     * Distance between the minimum and the maximum latitude/longitude

     * to be displayed.

     */

    latitudeDelta: number;

    longitudeDelta: number;

  };

  /**

   * Whether the user may use pinch gestures to zoom in and out.

   */

  zoomEnabled?: boolean;

}) {

  return <RNTMap {...props} />;

}
```

We can now supply the `region` prop to `MapView`:

MyApp.tsx

```
import MapView from './MapView.tsx';



export default function MyApp() {

  const region = {

    latitude: 37.48,

    longitude: -122.16,

    latitudeDelta: 0.1,

    longitudeDelta: 0.1,

  };

  return (

    <MapView

      region={region}

      zoomEnabled={false}

      style={{flex: 1}}

    />

  );

}
```

## Events[​](#events "Direct link to Events")

So now we have a native map component that we can control freely from JS, but how do we deal with events from the user, like pinch-zooms or panning to change the visible region?

Until now we've only returned a `MKMapView` instance from our manager's `-(UIView *)view` method. We can't add new properties to `MKMapView` so we have to create a new subclass from `MKMapView` which we use for our View. We can then add a `onRegionChange` callback on this subclass:

RNTMapView\.h

```
#import <MapKit/MapKit.h>



#import <React/RCTComponent.h>



@interface RNTMapView: MKMapView



@property (nonatomic, copy) RCTBubblingEventBlock onRegionChange;



@end
```

RNTMapView\.m

```
#import "RNTMapView.h"



@implementation RNTMapView



@end
```

Note that all `RCTBubblingEventBlock` must be prefixed with `on`. Next, declare an event handler property on `RNTMapManager`, make it a delegate for all the views it exposes, and forward events to JS by calling the event handler block from the native view.

RNTMapManager.m

```
#import <MapKit/MapKit.h>

#import <React/RCTViewManager.h>



#import "RNTMapView.h"

#import "RCTConvert+Mapkit.h"



@interface RNTMapManager : RCTViewManager <MKMapViewDelegate>

@end



@implementation RNTMapManager



RCT_EXPORT_MODULE()



RCT_EXPORT_VIEW_PROPERTY(zoomEnabled, BOOL)

RCT_EXPORT_VIEW_PROPERTY(onRegionChange, RCTBubblingEventBlock)



RCT_CUSTOM_VIEW_PROPERTY(region, MKCoordinateRegion, MKMapView)

{

  [view setRegion:json ? [RCTConvert MKCoordinateRegion:json] : defaultView.region animated:YES];

}



- (UIView *)view

{

  RNTMapView *map = [RNTMapView new];

  map.delegate = self;

  return map;

}



#pragma mark MKMapViewDelegate



- (void)mapView:(RNTMapView *)mapView regionDidChangeAnimated:(BOOL)animated

{

  if (!mapView.onRegionChange) {

    return;

  }



  MKCoordinateRegion region = mapView.region;

  mapView.onRegionChange(@{

    @"region": @{

      @"latitude": @(region.center.latitude),

      @"longitude": @(region.center.longitude),

      @"latitudeDelta": @(region.span.latitudeDelta),

      @"longitudeDelta": @(region.span.longitudeDelta),

    }

  });

}

@end
```

In the delegate method `-mapView:regionDidChangeAnimated:` the event handler block is called on the corresponding view with the region data. Calling the `onRegionChange` event handler block results in calling the same callback prop in JavaScript. This callback is invoked with the raw event, which we typically process in the wrapper component to simplify the API:

MapView\.tsx

```
// ...



type RegionChangeEvent = {

  nativeEvent: {

    latitude: number;

    longitude: number;

    latitudeDelta: number;

    longitudeDelta: number;

  };

};



export default function MapView(props: {

  // ...

  /**

   * Callback that is called continuously when the user is dragging the map.

   */

  onRegionChange: (event: RegionChangeEvent) => unknown;

}) {

  return <RNTMap {...props} onRegionChange={onRegionChange} />;

}
```

MyApp.tsx

```
import MapView from './MapView.tsx';



export default function MyApp() {

  // ...



  const onRegionChange = useCallback(event => {

    const {region} = event.nativeEvent;

    // Do something with `region.latitude`, etc.

  });



  return (

    <MapView

      // ...

      onRegionChange={onRegionChange}

    />

  );

}
```

## Handling multiple native views[​](#handling-multiple-native-views "Direct link to Handling multiple native views")

A React Native view can have more than one child view in the view tree eg.

React TSX

```
<View>

  <MyNativeView />

  <MyNativeView />

  <Button />

</View>
```

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:

React TSX

```
<View>

  <MyNativeView ref={this.myNativeReference} />

  <MyNativeView ref={this.myNativeReference2} />

  <Button

    onPress={() => {

      this.myNativeReference.callNativeMethod();

    }}

  />

</View>
```

Now the above component has a reference to a particular `MyNativeView` which allows us to use a specific instance of `MyNativeView`. Now the button can control which `MyNativeView` should change its `backgroundColor`. In this example let's assume that `callNativeMethod` changes `backgroundColor`.

MyNativeView\.ios.tsx

```
class MyNativeView extends React.Component {

  callNativeMethod = () => {

    UIManager.dispatchViewManagerCommand(

      ReactNative.findNodeHandle(this),

      UIManager.getViewManagerConfig('RNCMyNativeView').Commands

        .callNativeMethod,

      [],

    );

  };



  render() {

    return <NativeComponent ref={NATIVE_COMPONENT_REF} />;

  }

}
```

`callNativeMethod` is our custom iOS method which for example changes the `backgroundColor` which is exposed through `MyNativeView`. This method uses `UIManager.dispatchViewManagerCommand` which needs 3 parameters:

* `(nonnull NSNumber \*)reactTag`  -  id of react view.
* `commandID:(NSInteger)commandID`  -  Id of the native method that should be called
* `commandArgs:(NSArray<id> \*)commandArgs`  -  Args of the native method that we can pass from JS to native.

RNCMyNativeViewManager.m

```
#import <React/RCTViewManager.h>

#import <React/RCTUIManager.h>

#import <React/RCTLog.h>



RCT_EXPORT_METHOD(callNativeMethod:(nonnull NSNumber*) reactTag) {

    [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *,UIView *> *viewRegistry) {

        NativeView *view = viewRegistry[reactTag];

        if (!view || ![view isKindOfClass:[NativeView class]]) {

            RCTLogError(@"Cannot find NativeView with tag #%@", reactTag);

            return;

        }

        [view callNativeMethod];

    }];



}
```

Here the `callNativeMethod` is defined in the `RNCMyNativeViewManager.m` file and contains only one parameter which is `(nonnull NSNumber*) reactTag`. This exported function will find a particular view using `addUIBlock` which contains the `viewRegistry` parameter and returns the component based on `reactTag` allowing it to call the method on the correct component.

## Styles[​](#styles "Direct link to Styles")

Since all our native react views are subclasses of `UIView`, most style attributes will work like you would expect out of the box. Some components will want a default style, however, for example `UIDatePicker` which is a fixed size. This default style is important for the layout algorithm to work as expected, but we also want to be able to override the default style when using the component. `DatePickerIOS` does this by wrapping the native component in an extra view, which has flexible styling, and using a fixed style (which is generated with constants passed in from native) on the inner native component:

DatePickerIOS.ios.tsx

```
import {UIManager} from 'react-native';

const RCTDatePickerIOSConsts = UIManager.RCTDatePicker.Constants;

...

  render: function() {

    return (

      <View style={this.props.style}>

        <RCTDatePickerIOS

          ref={DATEPICKER}

          style={styles.rkDatePickerIOS}

          ...

        />

      </View>

    );

  }

});



const styles = StyleSheet.create({

  rkDatePickerIOS: {

    height: RCTDatePickerIOSConsts.ComponentHeight,

    width: RCTDatePickerIOSConsts.ComponentWidth,

  },

});
```

The `RCTDatePickerIOSConsts` constants are exported from native by grabbing the actual frame of the native component like so:

RCTDatePickerManager.m

```
- (NSDictionary *)constantsToExport

{

  UIDatePicker *dp = [[UIDatePicker alloc] init];

  [dp layoutIfNeeded];



  return @{

    @"ComponentHeight": @(CGRectGetHeight(dp.frame)),

    @"ComponentWidth": @(CGRectGetWidth(dp.frame)),

    @"DatePickerModes": @{

      @"time": @(UIDatePickerModeTime),

      @"date": @(UIDatePickerModeDate),

      @"datetime": @(UIDatePickerModeDateAndTime),

    }

  };

}
```

This guide covered many of the aspects of bridging over custom native components, but there is even more you might need to consider, such as custom hooks for inserting and laying out subviews. If you want to go even deeper, check out the [source code](https://github.com/react/react-native/tree/main/packages/react-native/React/Views) of some of the implemented components.

* [iOS MapView example](#ios-mapview-example)
* [Properties](#properties)
* [Events](#events)
* [Handling multiple native views](#handling-multiple-native-views)
* [Styles](#styles)

----
url: https://reactnative.dev/docs/next/global-intersectionobserver
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-intersectionobserver)** (0.87).

Version: Next

Canary 🧪

**This API is currently only available in React Native’s Canary and Experimental channels.**

If you want to try it out, please [enable the Canary Channel](/docs/next/release-levels) in your app.

The global [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) interface, as defined in Web specifications. It provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

***

# Reference

## Constructor[​](#constructor "Direct link to Constructor")

### `IntersectionObserver()`[​](#intersectionobserver "Direct link to intersectionobserver")

See [documentation in MDN](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver).

Creates a new `IntersectionObserver` object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more `threshold` or `rnRootThreshold` values.

TypeScript

```
new IntersectionObserver(callback, options?)
```

#### Parameters[​](#parameters "Direct link to Parameters")

**`callback`**

A function which is called when the percentage of the target element is visible crosses a threshold. The callback receives two parameters:

* `entries`: An array of [`IntersectionObserverEntry`](/docs/next/global-intersectionobserverentry) objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.
* `observer`: The `IntersectionObserver` instance which invoked the callback.

**`options`** (optional)

An optional object with the following properties:

| Name                 | Type                                        | Description                                                                                                                                                                                                       |
| -------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `root`               | [Element](/docs/next/element-nodes) \| null | An element that is an ancestor of the target, whose bounding rectangle will be considered the viewport. Defaults to the root viewport if not specified or if `null`.                                              |
| `rootMargin`         | string                                      | A string which specifies a set of offsets to add to the root's bounding box when calculating intersections. Defaults to `"0px 0px 0px 0px"`.                                                                      |
| `threshold`          | number \| number\[]                         | Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target. Defaults to `[0]` if `rnRootThreshold` is not set. |
| `rnRootThreshold` ⚠️ | number \| number\[]                         | **React Native specific.** Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to the total root area.                                                     |

```
get rnRootThresholds(): ReadonlyArray<number> | null;
```

----
url: https://reactnative.dev/docs/next/textinput
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/textinput)** (0.87).

Version: Next

A foundational component for inputting text into the app via a keyboard. Props provide configurability for several features, such as auto-correction, auto-capitalization, placeholder text, and different keyboard types, such as a numeric keypad.

The most basic use case is to plop down a `TextInput` and subscribe to the `onChangeText` events to read the user input. There are also other events, such as `onSubmitEditing` and `onFocus` that can be subscribed to. A minimal example:

Two methods exposed via the native element are `.focus()` and `.blur()` that will focus or blur the TextInput programmatically.

Note that some props are only available with `multiline={true/false}`:

`TextInput` has a border at the bottom of its view by default. This border has its padding set by the background image provided by the system, and it cannot be changed. Solutions to avoid this are to either not set height explicitly, in which case the system will take care of displaying the border in the correct position, or to not display the border by setting `underlineColorAndroid` to transparent.

Note that on Android performing text selection in an input can change the app's activity `windowSoftInputMode` param to `adjustResize`. This may cause issues with components that have position: 'absolute' while the keyboard is active. To avoid this behavior either specify `windowSoftInputMode` in AndroidManifest.xml ( <https://developer.android.com/guide/topics/manifest/activity-element.html> ) or control this param programmatically with native code.

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### `allowFontScaling`[​](#allowfontscaling "Direct link to allowfontscaling")

Specifies whether fonts should scale to respect Text Size accessibility settings. The default is `true`.

| Type |
| ---- |
| bool |

***

### `autoCapitalize`[​](#autocapitalize "Direct link to autocapitalize")

Tells `TextInput` to automatically capitalize certain characters. This property is not supported by some keyboard types such as `name-phone-pad`.

* `characters`: all characters.
* `words`: first letter of each word.
* `sentences`: first letter of each sentence (*default*).
* `none`: don't auto capitalize anything.

| Type                                             |
| ------------------------------------------------ |
| enum('none', 'sentences', 'words', 'characters') |

***

| Type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| enum('additional-name', 'address-line1', 'address-line2', 'birthdate-day', 'birthdate-full', 'birthdate-month', 'birthdate-year', 'cc-csc', 'cc-exp', 'cc-exp-day', 'cc-exp-month', 'cc-exp-year', 'cc-number', 'country', 'current-password', 'email', 'family-name', 'given-name', 'honorific-prefix', 'honorific-suffix', 'name', 'new-password', 'off', 'one-time-code', 'postal-code', 'street-address', 'tel', 'username', 'cc-family-name', 'cc-given-name', 'cc-middle-name', 'cc-name', 'cc-type', 'nickname', 'organization', 'organization-title', 'url', 'gender', 'name-family', 'name-given', 'name-middle', 'name-middle-initial', 'name-prefix', 'name-suffix', 'password', 'password-new', 'postal-address', 'postal-address-country', 'postal-address-extended', 'postal-address-extended-postal-code', 'postal-address-locality', 'postal-address-region', 'sms-otp', 'tel-country-code', 'tel-device', 'tel-national', 'username-new') |

***

### `autoCorrect`[​](#autocorrect "Direct link to autocorrect")

If `false`, disables auto-correct. The default value is `true`.

| Type |
| ---- |
| bool |

***

### `autoFocus`[​](#autofocus "Direct link to autofocus")

If `true`, focuses the input. The default value is `false`.

| Type |
| ---- |
| bool |

***

### 🗑️ `blurOnSubmit`[​](#️-bluronsubmit "Direct link to ️-bluronsubmit")

Deprecated

Note that `submitBehavior` now takes the place of `blurOnSubmit` and will override any behavior defined by `blurOnSubmit`. See [submitBehavior](/docs/next/textinput#submitbehavior).

If `true`, the text field will blur when submitted. The default value is true for single-line fields and false for multiline fields. Note that for multiline fields, setting `blurOnSubmit` to `true` means that pressing return will blur the field and trigger the `onSubmitEditing` event instead of inserting a newline into the field.

| Type |
| ---- |
| bool |

***

### `caretHidden`[​](#carethidden "Direct link to carethidden")

If `true`, caret is hidden. The default value is `false`.

| Type |
| ---- |
| bool |

***

### `clearButtonMode`iOS[​](#clearbuttonmode-ios "Direct link to clearbuttonmode-ios")

When the clear button should appear on the right side of the text view. This property is supported only for single-line TextInput component. The default value is `never`.

| Type                                                       |
| ---------------------------------------------------------- |
| enum('never', 'while-editing', 'unless-editing', 'always') |

***

### `clearTextOnFocus`iOS[​](#cleartextonfocus-ios "Direct link to cleartextonfocus-ios")

If `true`, clears the text field automatically when editing begins.

| Type |
| ---- |
| bool |

***

### `contextMenuHidden`[​](#contextmenuhidden "Direct link to contextmenuhidden")

If `true`, context menu is hidden. The default value is `false`.

| Type |
| ---- |
| bool |

***

| Type                                                                                                                                                     |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all'), ,array of enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all') |

***

### `defaultValue`[​](#defaultvalue "Direct link to defaultvalue")

Provides an initial value that will change when the user starts typing. Useful for use-cases where you do not want to deal with listening to events and updating the value prop to keep the controlled state in sync.

| Type   |
| ------ |
| string |

***

### `disableKeyboardShortcuts`iOS[​](#disablekeyboardshortcuts-ios "Direct link to disablekeyboardshortcuts-ios")

If `true`, the keyboard shortcuts (undo/redo and copy buttons) are disabled.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `cursorColor`Android[​](#cursorcolor-android "Direct link to cursorcolor-android")

When provided it will set the color of the cursor (or "caret") in the component. Unlike the behavior of `selectionColor` the cursor color will be set independently from the color of the text selection box.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `disableFullscreenUI`Android[​](#disablefullscreenui-android "Direct link to disablefullscreenui-android")

When `false`, if there is a small amount of space available around a text input (e.g. landscape orientation on a phone), the OS may choose to have the user edit the text inside of a full screen text input mode. When `true`, this feature is disabled and users will always edit the text directly inside of the text input. Defaults to `false`.

| Type |
| ---- |
| bool |

***

### `editable`[​](#editable "Direct link to editable")

If `false`, text is not editable. The default value is `true`.

| Type |
| ---- |
| bool |

***

### `enablesReturnKeyAutomatically`iOS[​](#enablesreturnkeyautomatically-ios "Direct link to enablesreturnkeyautomatically-ios")

If `true`, the keyboard disables the return key when there is no text and automatically enables it when there is text. The default value is `false`.

| Type |
| ---- |
| bool |

***

| Type                                                              |
| ----------------------------------------------------------------- |
| enum('enter', 'done', 'next', 'previous', 'search', 'send', 'go') |

***

| Type                                                                       |
| -------------------------------------------------------------------------- |
| enum('auto', 'no', 'noExcludeDescendants', 'yes', 'yesExcludeDescendants') |

***

### `inlineImageLeft`Android[​](#inlineimageleft-android "Direct link to inlineimageleft-android")

If defined, the provided image resource will be rendered on the left. The image resource must be inside `/android/app/src/main/res/drawable` and referenced like

```
<TextInput

 inlineImageLeft='search_icon'

/>
```

| Type   |
| ------ |
| string |

***

### `inlineImagePadding`Android[​](#inlineimagepadding-android "Direct link to inlineimagepadding-android")

Padding between the inline image, if any, and the text input itself.

| Type   |
| ------ |
| number |

***

### `inputAccessoryViewID`iOS[​](#inputaccessoryviewid-ios "Direct link to inputaccessoryviewid-ios")

An optional identifier which links a custom [InputAccessoryView](/docs/next/inputaccessoryview) to this text input. The InputAccessoryView is rendered above the keyboard when this text input is focused.

| Type   |
| ------ |
| string |

***

### `inputAccessoryViewButtonLabel`iOS[​](#inputaccessoryviewbuttonlabel-ios "Direct link to inputaccessoryviewbuttonlabel-ios")

An optional label that overrides the default [InputAccessoryView](/docs/next/inputaccessoryview) button label.

By default, the default button label is not localized. Use this property to provide a localized version.

| Type   |
| ------ |
| string |

***

| Type                                                                        |
| --------------------------------------------------------------------------- |
| enum('decimal', 'email', 'none', 'numeric', 'search', 'tel', 'text', 'url') |

***

### `keyboardAppearance`iOS[​](#keyboardappearance-ios "Direct link to keyboardappearance-ios")

Determines the color of the keyboard.

| Type                             |
| -------------------------------- |
| enum('default', 'light', 'dark') |

***

| Type                                                                                                                                                                                                    |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| enum('default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', 'visible-password') |

***

### `lineBreakStrategyIOS`iOS[​](#linebreakstrategyios-ios "Direct link to linebreakstrategyios-ios")

Set line break strategy on iOS 14+. Possible values are `none`, `standard`, `hangul-word` and `push-out`.

| Type                                                        | Default  |
| ----------------------------------------------------------- | -------- |
| enum(`'none'`, `'standard'`, `'hangul-word'`, `'push-out'`) | `'none'` |

***

### `lineBreakModeIOS`iOS[​](#linebreakmodeios-ios "Direct link to linebreakmodeios-ios")

Set line break mode on iOS. Possible values are `wordWrapping`, `char`, `clip`, `head`, `middle` and `tail`.

| Type                                                                       | Default          |
| -------------------------------------------------------------------------- | ---------------- |
| enum(`'wordWrapping'`, `'char'`, `'clip'`, `'head'`, `'middle'`, `'tail'`) | `'wordWrapping'` |

***

### `maxFontSizeMultiplier`[​](#maxfontsizemultiplier "Direct link to maxfontsizemultiplier")

Specifies largest possible scale a font can reach when `allowFontScaling` is enabled. Possible values:

* `null/undefined` (default): inherit from the parent node or the global default (0)
* `0`: no max, ignore parent/global default
* `>= 1`: sets the `maxFontSizeMultiplier` of this node to this value

| Type   |
| ------ |
| number |

***

### `maxLength`[​](#maxlength "Direct link to maxlength")

Limits the maximum number of characters that can be entered. Use this instead of implementing the logic in JS to avoid flicker.

| Type   |
| ------ |
| number |

***

### `multiline`[​](#multiline "Direct link to multiline")

If `true`, the text input can be multiple lines. The default value is `false`.

note

It is important to note that this aligns the text to the top on iOS, and centers it on Android. Use with `textAlignVertical` set to `top` for the same behavior in both platforms.

| Type |
| ---- |
| bool |

***

### `numberOfLines`[​](#numberoflines "Direct link to numberoflines")

note

`numberOfLines` on iOS is only available on the [New Architecture](/architecture/landing-page)

Sets the maximum number of lines for a `TextInput`. Use it with multiline set to `true` to be able to fill the lines.

| Type   |
| ------ |
| number |

***

### `onBlur`[​](#onblur "Direct link to onblur")

Callback that is called when the text input is blurred.

note

If you are attempting to access the `text` value from `nativeEvent` keep in mind that the resulting value you get can be `undefined` which can cause unintended errors. If you are trying to find the last value of TextInput, you can use the [`onEndEditing`](/docs/next/textinput#onendediting) event, which is fired upon completion of editing.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: TargetEvent}) => void` |

***

### `onChange`[​](#onchange "Direct link to onchange")

Callback that is called when the text input's text changes.

| Type                                                  |
| ----------------------------------------------------- |
| (`{nativeEvent: {eventCount, target, text}}`) => void |

***

### `onChangeText`[​](#onchangetext "Direct link to onchangetext")

Callback that is called when the text input's text changes. Changed text is passed as a single string argument to the callback handler.

| Type     |
| -------- |
| function |

***

### `onContentSizeChange`[​](#oncontentsizechange "Direct link to oncontentsizechange")

Callback that is called when the text input's content size changes.

Only called for multiline text inputs.

| Type                                                       |
| ---------------------------------------------------------- |
| (`{nativeEvent: {contentSize: {width, height} }}`) => void |

***

### `onEndEditing`[​](#onendediting "Direct link to onendediting")

Callback that is called when text input ends.

| Type     |
| -------- |
| function |

***

### `onPressIn`[​](#onpressin "Direct link to onpressin")

Callback that is called when a touch is engaged.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onPressOut`[​](#onpressout "Direct link to onpressout")

Callback that is called when a touch is released.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onFocus`[​](#onfocus "Direct link to onfocus")

Callback that is called when the text input is focused.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: TargetEvent}) => void` |

***

### `onKeyPress`[​](#onkeypress "Direct link to onkeypress")

Callback that is called when a key is pressed. This will be called with object where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and the typed-in character otherwise including `' '` for space. Fires before `onChange` callbacks. Note: on Android only the inputs from soft keyboard are handled, not the hardware keyboard inputs.

| Type                                        |
| ------------------------------------------- |
| (`{nativeEvent: {key: keyValue} }`) => void |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: LayoutEvent}) => void` |

***

### `onScroll`[​](#onscroll "Direct link to onscroll")

Invoked on content scroll. May also contain other properties from `ScrollEvent` but on Android `contentSize` is not provided for performance reasons.

| Type                                                |
| --------------------------------------------------- |
| (`{nativeEvent: {contentOffset: {x, y} }}`) => void |

***

### `onSelectionChange`[​](#onselectionchange "Direct link to onselectionchange")

Callback that is called when the text input selection is changed.

| Type                                                  |
| ----------------------------------------------------- |
| (`{nativeEvent: {selection: {start, end} }}`) => void |

***

### `onSubmitEditing`[​](#onsubmitediting "Direct link to onsubmitediting")

Callback that is called when the text input's submit button is pressed.

| Type                                                  |
| ----------------------------------------------------- |
| (`{nativeEvent: {text, eventCount, target}}`) => void |

Note that on iOS this method isn't called when using `keyboardType="phone-pad"`.

***

### `placeholder`[​](#placeholder "Direct link to placeholder")

The string that will be rendered before text input has been entered.

| Type   |
| ------ |
| string |

***

### `placeholderTextColor`[​](#placeholdertextcolor "Direct link to placeholdertextcolor")

The text color of the placeholder string.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `readOnly`[​](#readonly "Direct link to readonly")

If `true`, text is not editable. The default value is `false`.

| Type |
| ---- |
| bool |

***

### `returnKeyLabel`Android[​](#returnkeylabel-android "Direct link to returnkeylabel-android")

Sets the return key to the label. Use it instead of `returnKeyType`.

| Type   |
| ------ |
| string |

***

| Type                                                                                                                              |
| --------------------------------------------------------------------------------------------------------------------------------- |
| enum('done', 'go', 'next', 'search', 'send', 'none', 'previous', 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo') |

### `rejectResponderTermination`iOS[​](#rejectrespondertermination-ios "Direct link to rejectrespondertermination-ios")

If `true`, allows TextInput to pass touch events to the parent component. This allows components such as SwipeableListView to be swipeable from the TextInput on iOS, as is the case on Android by default. If `false`, TextInput always asks to handle the input (except when disabled). The default value is `true`.

| Type |
| ---- |
| bool |

***

### `rows`Android[​](#rows-android "Direct link to rows-android")

Sets the number of lines for a `TextInput`. Use it with multiline set to `true` to be able to fill the lines.

| Type   |
| ------ |
| number |

***

### `scrollEnabled`iOS[​](#scrollenabled-ios "Direct link to scrollenabled-ios")

If `false`, scrolling of the text view will be disabled. The default value is `true`. Only works with `multiline={true}`.

| Type |
| ---- |
| bool |

***

### `secureTextEntry`[​](#securetextentry "Direct link to securetextentry")

If `true`, the text input obscures the text entered so that sensitive text like passwords stay secure. The default value is `false`. Does not work with `multiline={true}`.

| Type |
| ---- |
| bool |

***

### `selection`[​](#selection "Direct link to selection")

The start and end of the text input's selection. Set start and end to the same value to position the cursor.

| Type                                  |
| ------------------------------------- |
| object: `{start: number,end: number}` |

***

### `selectionColor`[​](#selectioncolor "Direct link to selectioncolor")

The highlight, selection handle and cursor color of the text input.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `selectionHandleColor`Android[​](#selectionhandlecolor-android "Direct link to selectionhandlecolor-android")

Sets the color of the selection handle. Unlike `selectionColor`, it allows the selection handle color to be customized independently of the selection's color.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `selectTextOnFocus`[​](#selecttextonfocus "Direct link to selecttextonfocus")

If `true`, all text will automatically be selected on focus.

| Type |
| ---- |
| bool |

***

### `showSoftInputOnFocus`[​](#showsoftinputonfocus "Direct link to showsoftinputonfocus")

When `false`, it will prevent the soft keyboard from showing when the field is focused. The default value is `true`.

| Type |
| ---- |
| bool |

***

### `smartInsertDelete`iOS[​](#smartinsertdelete-ios "Direct link to smartinsertdelete-ios")

If `false`, the iOS system will not insert an extra space after a paste operation neither delete one or two spaces after a cut or delete operation.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `spellCheck`iOS[​](#spellcheck-ios "Direct link to spellcheck-ios")

If `false`, disables spell-check style (i.e. red underlines). The default value is inherited from `autoCorrect`.

| Type |
| ---- |
| bool |

***

| Type                                       |
| ------------------------------------------ |
| enum('submit', 'blurAndSubmit', 'newline') |

***

### `textAlign`[​](#textalign "Direct link to textalign")

Align the input text to the left, center, or right sides of the input field.

Possible values for `textAlign` are:

* `left`
* `center`
* `right`

| Type                            |
| ------------------------------- |
| enum('left', 'center', 'right') |

***

| Type                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| enum('none', 'addressCity', 'addressCityAndState', 'addressState', 'birthdate', 'birthdateDay', 'birthdateMonth', 'birthdateYear', 'countryName', 'creditCardExpiration', 'creditCardExpirationMonth', 'creditCardExpirationYear', 'creditCardFamilyName', 'creditCardGivenName', 'creditCardMiddleName', 'creditCardName', 'creditCardNumber', 'creditCardSecurityCode', 'creditCardType', 'emailAddress', 'familyName', 'fullStreetAddress', 'givenName', 'jobTitle', 'location', 'middleName', 'name', 'namePrefix', 'nameSuffix', 'newPassword', 'nickname', 'oneTimeCode', 'organizationName', 'password', 'postalCode', 'streetAddressLine1', 'streetAddressLine2', 'sublocality', 'telephoneNumber', 'URL', 'username') |

***

### `passwordRules`iOS[​](#passwordrules-ios "Direct link to passwordrules-ios")

When using `textContentType` as `newPassword` on iOS we can let the OS know the minimum requirements of the password so that it can generate one that will satisfy them. In order to create a valid string for `PasswordRules` take a look to the [Apple Docs](https://developer.apple.com/password-rules/).

tip

If passwords generation dialog doesn't appear please make sure that:

* AutoFill is enabled: **Settings** → **Passwords & Accounts** → toggle "On" the **AutoFill Passwords**,
* iCloud Keychain is used: **Settings** → **Apple ID** → **iCloud** → **Keychain** → toggle "On" the **iCloud Keychain**.

| Type   |
| ------ |
| string |

***

[Styles](/docs/next/style)

| Type                          |
| ----------------------------- |
| [Text](/docs/next/text#style) |

***

### `textBreakStrategy`Android[​](#textbreakstrategy-android "Direct link to textbreakstrategy-android")

Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` The default value is `highQuality`.

| Type                                      |
| ----------------------------------------- |
| enum('simple', 'highQuality', 'balanced') |

***

### `underlineColorAndroid`Android[​](#underlinecolorandroid-android "Direct link to underlinecolorandroid-android")

The color of the `TextInput` underline.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `value`[​](#value "Direct link to value")

The value to show for the text input. `TextInput` is a controlled component, which means the native value will be forced to match this value prop if provided. For most uses, this works great, but in some cases this may cause flickering - one common cause is preventing edits by keeping value the same. In addition to setting the same value, either set `editable={false}`, or set/update `maxLength` to prevent unwanted edits without flicker.

| Type   |
| ------ |
| string |

## Methods[​](#methods "Direct link to Methods")

### `.focus()`[​](#focus "Direct link to focus")

React TSX

```
focus();
```

Makes the native input request focus.

### `.blur()`[​](#blur "Direct link to blur")

React TSX

```
blur();
```

Makes the native input lose focus.

### `clear()`[​](#clear "Direct link to clear")

React TSX

```
clear();
```

Removes all text from the `TextInput`.

***

### `isFocused()`[​](#isfocused "Direct link to isfocused")

React TSX

```
isFocused(): boolean;
```

    [iOS](#clearbuttonmode-ios)
  * [`clearTextOnFocus`](#cleartextonfocus-ios)

    [iOS](#cleartextonfocus-ios)
  * [`contextMenuHidden`](#contextmenuhidden)
  * [`dataDetectorTypes`](#datadetectortypes-ios)

    [iOS](#datadetectortypes-ios)
  * [`defaultValue`](#defaultvalue)
  * [`disableKeyboardShortcuts`](#disablekeyboardshortcuts-ios)

    [iOS](#disablekeyboardshortcuts-ios)
  * [`cursorColor`](#cursorcolor-android)

    [Android](#cursorcolor-android)
  * [`disableFullscreenUI`](#disablefullscreenui-android)

    [Android](#disablefullscreenui-android)
  * [`editable`](#editable)
  * [`enablesReturnKeyAutomatically`](#enablesreturnkeyautomatically-ios)

    [iOS](#enablesreturnkeyautomatically-ios)
  * [`enterKeyHint`](#enterkeyhint)
  * [`importantForAutofill`](#importantforautofill-android)

    [Android](#importantforautofill-android)
  * [`inlineImageLeft`](#inlineimageleft-android)

    [Android](#inlineimageleft-android)
  * [`inlineImagePadding`](#inlineimagepadding-android)

    [Android](#inlineimagepadding-android)
  * [`inputAccessoryViewID`](#inputaccessoryviewid-ios)

    [iOS](#inputaccessoryviewid-ios)
  * [`inputAccessoryViewButtonLabel`](#inputaccessoryviewbuttonlabel-ios)

    [iOS](#inputaccessoryviewbuttonlabel-ios)
  * [`inputMode`](#inputmode)
  * [`keyboardAppearance`](#keyboardappearance-ios)

    [iOS](#keyboardappearance-ios)
  * [`keyboardType`](#keyboardtype)
  * [`lineBreakStrategyIOS`](#linebreakstrategyios-ios)

    [iOS](#linebreakstrategyios-ios)
  * [`lineBreakModeIOS`](#linebreakmodeios-ios)

    [iOS](#linebreakmodeios-ios)

    [Android](#returnkeylabel-android)
  * [`returnKeyType`](#returnkeytype)
  * [`rejectResponderTermination`](#rejectrespondertermination-ios)

    [iOS](#rejectrespondertermination-ios)
  * [`rows`](#rows-android)

    [Android](#rows-android)
  * [`scrollEnabled`](#scrollenabled-ios)

    [iOS](#scrollenabled-ios)
  * [`secureTextEntry`](#securetextentry)
  * [`selection`](#selection)
  * [`selectionColor`](#selectioncolor)
  * [`selectionHandleColor`](#selectionhandlecolor-android)

    [Android](#selectionhandlecolor-android)
  * [`selectTextOnFocus`](#selecttextonfocus)
  * [`showSoftInputOnFocus`](#showsoftinputonfocus)
  * [`smartInsertDelete`](#smartinsertdelete-ios)

    [iOS](#smartinsertdelete-ios)
  * [`spellCheck`](#spellcheck-ios)

    [iOS](#spellcheck-ios)
  * [`submitBehavior`](#submitbehavior)
  * [`textAlign`](#textalign)
  * [`textContentType`](#textcontenttype-ios)

    [iOS](#textcontenttype-ios)
  * [`passwordRules`](#passwordrules-ios)

    [iOS](#passwordrules-ios)
  * [`style`](#style)
  * [`textBreakStrategy`](#textbreakstrategy-android)

    [Android](#textbreakstrategy-android)
  * [`underlineColorAndroid`](#underlinecolorandroid-android)

    [Android](#underlinecolorandroid-android)
  * [`value`](#value)

- [Methods](#methods)

  * [`.focus()`](#focus)
  * [`.blur()`](#blur)
  * [`clear()`](#clear)
  * [`isFocused()`](#isfocused)

----
url: https://reactnative.dev/docs/pushnotificationios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Deprecated

Use one of the [community packages](https://reactnative.directory/?search=notification) instead.

### Projects with Native Code Only

The following section only applies to projects with native code exposed. If you are using the managed Expo workflow, see the guide on [Notifications](https://docs.expo.dev/versions/latest/sdk/notifications/) in the Expo documentation for the appropriate alternative.

Handle notifications for your app, including scheduling and permissions.

***

## Getting Started[​](#getting-started "Direct link to Getting Started")

To enable push notifications, [configure your notifications with Apple](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server) and your server-side system.

Then, [enable remote notifications](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app#2980038) in your project. This will automatically enable the required settings.

### Enable support for `register` events[​](#enable-support-for-register-events "Direct link to enable-support-for-register-events")

In your `AppDelegate.m`, add:

Objective-C

```
#import <React/RCTPushNotificationManager.h>
```

Then implement the following in order to handle remote notification registration events:

Objective-C

```
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

{

 // This will trigger 'register' events on PushNotificationIOS

 [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error

{

 // This will trigger 'registrationError' events on PushNotificationIOS

 [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];

}
```

### Handle notifications[​](#handle-notifications "Direct link to Handle notifications")

You'll need to implement `UNUserNotificationCenterDelegate` in your `AppDelegate`:

Objective-C

```
#import <UserNotifications/UserNotifications.h>



@interface YourAppDelegate () <UNUserNotificationCenterDelegate>

@end
```

Set the delegate on app launch:

Objective-C

```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

  ...

  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

  center.delegate = self;



  return YES;

}
```

#### Foreground notifications[​](#foreground-notifications "Direct link to Foreground notifications")

Implement `userNotificationCenter:willPresentNotification:withCompletionHandler:` to handle notifications that arrive when the app is in the foreground. Use the completionHandler to determine if the notification will be shown to the user and notify `RCTPushNotificationManager` accordingly:

Objective-C

```
// Called when a notification is delivered to a foreground app.

- (void)userNotificationCenter:(UNUserNotificationCenter *)center

       willPresentNotification:(UNNotification *)notification

         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler

{

  // This will trigger 'notification' and 'localNotification' events on PushNotificationIOS

  [RCTPushNotificationManager didReceiveNotification:notification];

  // Decide if and how the notification will be shown to the user

  completionHandler(UNNotificationPresentationOptionNone);

}
```

#### Background notifications[​](#background-notifications "Direct link to Background notifications")

Implement `userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:` to handle when a notification is tapped, typically called for background notifications which the user taps to open the app. However, if you had set foreground notifications to be shown in `userNotificationCenter:willPresentNotification:withCompletionHandler:`, this method will also be invoked on foreground notifications when tapped. In this case, you should only notify `RCTPushNotificationManager` in one of these callbacks.

If the tapped notification resulted in app launch, call `setInitialNotification:`. If the notification was not previously handled by `userNotificationCenter:willPresentNotification:withCompletionHandler:`, call `didReceiveNotification:` as well:

Objective-C

```
- (void)  userNotificationCenter:(UNUserNotificationCenter *)center

  didReceiveNotificationResponse:(UNNotificationResponse *)response

           withCompletionHandler:(void (^)(void))completionHandler

{

  // This condition passes if the notification was tapped to launch the app

  if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {

    // Allow the notification to be retrieved on the JS side using getInitialNotification()

    [RCTPushNotificationManager setInitialNotification:response.notification];

  }

  // This will trigger 'notification' and 'localNotification' events on PushNotificationIOS

  [RCTPushNotificationManager didReceiveNotification:response.notification];

  completionHandler();

}
```

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `presentLocalNotification()`[​](#presentlocalnotification "Direct link to presentlocalnotification")

React TSX

```
static presentLocalNotification(details: PresentLocalNotificationDetails);
```

Schedules a local notification for immediate presentation.

**Parameters:**

| Name    | Type   | Required | Description |
| ------- | ------ | -------- | ----------- |
| details | object | Yes      | See below.  |

***

### `scheduleLocalNotification()`[​](#schedulelocalnotification "Direct link to schedulelocalnotification")

React TSX

```
static scheduleLocalNotification(details: ScheduleLocalNotificationDetails);
```

Schedules a local notification for future presentation.

**Parameters:**

| Name    | Type   | Required | Description |
| ------- | ------ | -------- | ----------- |
| details | object | Yes      | See below.  |

***

### `cancelAllLocalNotifications()`[​](#cancelalllocalnotifications "Direct link to cancelalllocalnotifications")

React TSX

```
static cancelAllLocalNotifications();
```

Cancels all scheduled local notifications.

***

### `removeAllDeliveredNotifications()`[​](#removealldeliverednotifications "Direct link to removealldeliverednotifications")

React TSX

```
static removeAllDeliveredNotifications();
```

Removes all delivered notifications from Notification Center.

***

### `getDeliveredNotifications()`[​](#getdeliverednotifications "Direct link to getdeliverednotifications")

React TSX

```
static getDeliveredNotifications(callback: (notifications: Object[]) => void);
```

Provides a list of the app’s notifications that are currently displayed in Notification Center.

**Parameters:**

| Name     | Type     | Required | Description                                                  |
| -------- | -------- | -------- | ------------------------------------------------------------ |
| callback | function | Yes      | Function which receives an array of delivered notifications. |

***

### `removeDeliveredNotifications()`[​](#removedeliverednotifications "Direct link to removedeliverednotifications")

React TSX

```
static removeDeliveredNotifications(identifiers: string[]);
```

Removes the specified notifications from Notification Center.

**Parameters:**

| Name        | Type  | Required | Description                        |
| ----------- | ----- | -------- | ---------------------------------- |
| identifiers | array | Yes      | Array of notification identifiers. |

***

### `setApplicationIconBadgeNumber()`[​](#setapplicationiconbadgenumber "Direct link to setapplicationiconbadgenumber")

React TSX

```
static setApplicationIconBadgeNumber(num: number);
```

Sets the badge number for the app icon on the Home Screen.

**Parameters:**

| Name   | Type   | Required | Description                    |
| ------ | ------ | -------- | ------------------------------ |
| number | number | Yes      | Badge number for the app icon. |

***

### `getApplicationIconBadgeNumber()`[​](#getapplicationiconbadgenumber "Direct link to getapplicationiconbadgenumber")

React TSX

```
static getApplicationIconBadgeNumber(callback: (num: number) => void);
```

Gets the current badge number for the app icon on the Home Screen.

**Parameters:**

| Name     | Type     | Required | Description                                        |
| -------- | -------- | -------- | -------------------------------------------------- |
| callback | function | Yes      | Function which processes the current badge number. |

***

### `cancelLocalNotifications()`[​](#cancellocalnotifications "Direct link to cancellocalnotifications")

React TSX

```
static cancelLocalNotifications(userInfo: Object);
```

Cancels any scheduled local notifications which match the fields in the provided `userInfo`.

**Parameters:**

| Name     | Type   | Required | Description |
| -------- | ------ | -------- | ----------- |
| userInfo | object | No       |             |

***

### `getScheduledLocalNotifications()`[​](#getscheduledlocalnotifications "Direct link to getscheduledlocalnotifications")

React TSX

```
static getScheduledLocalNotifications(

  callback: (notifications: ScheduleLocalNotificationDetails[]) => void,

);
```

Gets the list of local notifications that are currently scheduled.

**Parameters:**

| Name     | Type     | Required | Description                                                                  |
| -------- | -------- | -------- | ---------------------------------------------------------------------------- |
| callback | function | Yes      | Function which processes an array of objects describing local notifications. |

***

### `addEventListener()`[​](#addeventlistener "Direct link to addeventlistener")

React TSX

```
static addEventListener(

  type: PushNotificationEventName,

  handler:

    | ((notification: PushNotification) => void)

    | ((deviceToken: string) => void)

    | ((error: {message: string; code: number; details: any}) => void),

);
```

Attaches a listener to notification events including local notifications, remote notifications, and notification registration results.

**Parameters:**

| Name    | Type     | Required | Description                         |
| ------- | -------- | -------- | ----------------------------------- |
| type    | string   | Yes      | Event type to listen to. See below. |
| handler | function | Yes      | Listener.                           |

Valid events types include:

* `notification` : Fired when a remote notification is received. The handler will be invoked with an instance of `PushNotificationIOS`. This will handle notifications that arrive in the foreground or were tapped to open the app from the background.
* `localNotification` : Fired when a local notification is received. The handler will be invoked with an instance of `PushNotificationIOS`. This will handle notifications that arrive in the foreground or were tapped to open the app from the background.
* `register`: Fired when the user registers successfully for remote notifications. The handler will be invoked with a hex string representing the deviceToken.
* `registrationError`: Fired when the user fails to register for remote notifications. Typically occurs due to APNS issues or if the device is a simulator. The handler will be invoked with `{message: string, code: number, details: any}`.

***

### `removeEventListener()`[​](#removeeventlistener "Direct link to removeeventlistener")

React TSX

```
static removeEventListener(

  type: PushNotificationEventName,

);
```

Removes the event listener. Do this in `componentWillUnmount` to prevent memory leaks.

**Parameters:**

| Name | Type   | Required | Description                                       |
| ---- | ------ | -------- | ------------------------------------------------- |
| type | string | Yes      | Event type. See `addEventListener()` for options. |

***

### `requestPermissions()`[​](#requestpermissions "Direct link to requestpermissions")

React TSX

```
static requestPermissions(permissions?: PushNotificationPermissions[]);
```

| Name        | Type  | Required | Description            |
| ----------- | ----- | -------- | ---------------------- |
| permissions | array | No       | alert, badge, or sound |

***

### `abandonPermissions()`[​](#abandonpermissions "Direct link to abandonpermissions")

React TSX

```
static abandonPermissions();
```

Unregister for all remote notifications received via Apple Push Notification service.

You should call this method in rare circumstances only, such as when a new version of the app removes support for all types of remote notifications. Users can temporarily prevent apps from receiving remote notifications through the Settings app. Apps unregistered through this method can always re-register.

***

### `checkPermissions()`[​](#checkpermissions "Direct link to checkpermissions")

React TSX

```
static checkPermissions(

  callback: (permissions: PushNotificationPermissions) => void,

);
```

Check which push permissions are currently enabled.

**Parameters:**

| Name     | Type     | Required | Description |
| -------- | -------- | -------- | ----------- |
| callback | function | Yes      | See below.  |

`callback` will be invoked with a `permissions` object:

* `alert: boolean`
* `badge: boolean`
* `sound: boolean`

***

### `getInitialNotification()`[​](#getinitialnotification "Direct link to getinitialnotification")

React TSX

```
static getInitialNotification(): Promise<PushNotification | null>;
```

This method returns a promise. If the app was launched by a push notification, this promise resolves to an object of type `PushNotificationIOS` for the notification that was tapped. Otherwise, it resolves to `null`.

***

### `getAuthorizationStatus()`[​](#getauthorizationstatus "Direct link to getauthorizationstatus")

React TSX

```
static getAuthorizationStatus(): Promise<number>;
```

This method returns a promise that resolves to the current notification authorization status. See [UNAuthorizationStatus](https://developer.apple.com/documentation/usernotifications/unauthorizationstatus?language=objc) for possible values.

***

### `finish()`[​](#finish "Direct link to finish")

React TSX

```
finish(result: string);
```

This method is available for remote notifications that have been received via [`application:didReceiveRemoteNotification:fetchCompletionHandler:`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application?language=objc). However, this is superseded by `UNUserNotificationCenterDelegate` and will no longer be invoked if both `application:didReceiveRemoteNotification:fetchCompletionHandler:` and the newer handlers from `UNUserNotificationCenterDelegate` are implemented.

If for some reason you're still relying on `application:didReceiveRemoteNotification:fetchCompletionHandler:`, you'll need to set up event handling on the iOS side:

Objective-C

```
- (void)           application:(UIApplication *)application

  didReceiveRemoteNotification:(NSDictionary *)userInfo

        fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler

{

  [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:handler];

}
```

Call `finish()` to execute the native completion handlers once you're done handling the notification on the JS side. When calling this block, pass in the fetch result value that best describes the results of your operation. For a list of possible values, see `PushNotificationIOS.FetchResult`.

If you're using `application:didReceiveRemoteNotification:fetchCompletionHandler:`, you *must* call this handler and should do so as soon as possible. See the [official documentation](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application?language=objc) for more details.

***

### `getMessage()`[​](#getmessage "Direct link to getmessage")

React TSX

```
getMessage(): string | Object;
```

An alias for `getAlert` to get the notification's main message string.

***

### `getSound()`[​](#getsound "Direct link to getsound")

React TSX

```
getSound(): string;
```

Gets the sound string from the `aps` object. This will be `null` for local notifications.

***

### `getCategory()`[​](#getcategory "Direct link to getcategory")

React TSX

```
getCategory(): string;
```

Gets the category string from the `aps` object.

***

### `getAlert()`[​](#getalert "Direct link to getalert")

React TSX

```
getAlert(): string | Object;
```

Gets the notification's main message from the `aps` object. Also see the alias: `getMessage()`.

***

### `getContentAvailable()`[​](#getcontentavailable "Direct link to getcontentavailable")

React TSX

```
getContentAvailable(): number;
```

Gets the content-available number from the `aps` object.

***

### `getBadgeCount()`[​](#getbadgecount "Direct link to getbadgecount")

React TSX

```
getBadgeCount(): number;
```

Gets the badge count number from the `aps` object.

***

### `getData()`[​](#getdata "Direct link to getdata")

React TSX

```
getData(): Object;
```

Gets the data object on the notification.

***

### `getThreadID()`[​](#getthreadid "Direct link to getthreadid")

React TSX

```
getThreadID();
```

----
url: https://reactnative.dev/docs/view
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The most fundamental component for building a UI, `View` is a container that supports layout with [flexbox](/docs/flexbox), [style](/docs/style), [some touch handling](/docs/handling-touches), and [accessibility](/docs/accessibility) controls. `View` maps directly to the native view equivalent on whatever platform React Native is running on, whether that is a `UIView`, `<div>`, `android.view`, etc.

`View` is designed to be nested inside other views and can have 0 to many children of any type.

This example creates a `View` that wraps two boxes with color and a text component in a row with padding.

note

`View`s are designed to be used with [`StyleSheet`](/docs/style) for clarity and performance, although inline styles are also supported.

### Synthetic Touch Events[​](#synthetic-touch-events "Direct link to Synthetic Touch Events")

For `View` responder props (e.g., `onResponderMove`), the synthetic touch event passed to them are in form of [PressEvent](/docs/pressevent).

***

# Reference

## Props[​](#props "Direct link to Props")

***

### `accessibilityActions`[​](#accessibilityactions "Direct link to accessibilityactions")

Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The `accessibilityActions` property should contain a list of action objects. Each action object should contain the field name and label.

See the [Accessibility guide](/docs/accessibility#accessibility-actions) for more information.

| Type  |
| ----- |
| array |

***

### `accessibilityElementsHidden`iOS[​](#accessibilityelementshidden-ios "Direct link to accessibilityelementshidden-ios")

A boolean value indicating whether the given accessibility element, and any accessibility elements it contains, are hidden. Default is `false`.

See the [Accessibility guide](/docs/accessibility#accessibilityelementshidden-ios) for more information.

| Type |
| ---- |
| bool |

***

### `accessibilityHint`[​](#accessibilityhint "Direct link to accessibilityhint")

An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label.

| Type   |
| ------ |
| string |

***

### `accessibilityLanguage`iOS[​](#accessibilitylanguage-ios "Direct link to accessibilitylanguage-ios")

A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the [BCP 47 specification](https://www.rfc-editor.org/info/bcp47).

See the [iOS `accessibilityLanguage` doc](https://developer.apple.com/documentation/objectivec/nsobject/1615192-accessibilitylanguage) for more information.

| Type   |
| ------ |
| string |

***

### `accessibilityIgnoresInvertColors`iOS[​](#accessibilityignoresinvertcolors-ios "Direct link to accessibilityignoresinvertcolors-ios")

A value indicating this view should or should not be inverted when color inversion is turned on. A value of `true` will tell the view to not be inverted even if color inversion is turned on.

See the [Accessibility guide](/docs/accessibility#accessibilityignoresinvertcolors-ios) for more information.

| Type |
| ---- |
| bool |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the `Text` nodes separated by space.

| Type   |
| ------ |
| string |

***

### `accessibilityLiveRegion`Android[​](#accessibilityliveregion-android "Direct link to accessibilityliveregion-android")

Indicates to accessibility services whether the user should be notified when this view changes. Works for Android API >= 19 only. Possible values:

* `'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.

See the [Android `View` docs](https://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion) for reference.

| Type                                |
| ----------------------------------- |
| enum('none', 'polite', 'assertive') |

***

| Type   |
| ------ |
| string |

***

### `accessibilityState`[​](#accessibilitystate "Direct link to accessibilitystate")

Describes the current state of a component to the user of an assistive technology.

See the [Accessibility guide](/docs/accessibility#accessibilitystate) for more information.

| Type                                                                                             |
| ------------------------------------------------------------------------------------------------ |
| object: `{disabled: bool, selected: bool, checked: bool or 'mixed', busy: bool, expanded: bool}` |

***

### `accessibilityValue`[​](#accessibilityvalue "Direct link to accessibilityvalue")

Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, it contains range information (minimum, current, and maximum).

See the [Accessibility guide](/docs/accessibility#accessibilityvalue) for more information.

| Type                                                            |
| --------------------------------------------------------------- |
| object: `{min: number, max: number, now: number, text: string}` |

***

### `accessibilityViewIsModal`iOS[​](#accessibilityviewismodal-ios "Direct link to accessibilityviewismodal-ios")

A value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. Default is `false`.

See the [Accessibility guide](/docs/accessibility#accessibilityviewismodal-ios) for more information.

| Type |
| ---- |
| bool |

***

### `accessible`[​](#accessible "Direct link to accessible")

When `true`, indicates that the view is an accessibility element and discoverable by assistive technologies such as screen readers and hardware keyboards. By default, all the touchable elements are accessible.

See the [Accessibility guide](/docs/accessibility#accessible) for more information.

***

### `aria-busy`[​](#aria-busy "Direct link to aria-busy")

Indicates an element is being modified and that assistive technologies may want to wait until the changes are complete before informing the user about the update.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-checked`[​](#aria-checked "Direct link to aria-checked")

Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

| Type             | Default |
| ---------------- | ------- |
| boolean, 'mixed' | false   |

***

### `aria-disabled`[​](#aria-disabled "Direct link to aria-disabled")

Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-expanded`[​](#aria-expanded "Direct link to aria-expanded")

Indicates whether an expandable element is currently expanded or collapsed.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-hidden`[​](#aria-hidden "Direct link to aria-hidden")

Indicates whether the element is hidden from assistive technologies.

For example, in a window that contains sibling views `A` and `B`, setting `aria-hidden` to `true` on view `B` causes VoiceOver to ignore the `B` element and its children.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-label`[​](#aria-label "Direct link to aria-label")

Defines a string value that labels an interactive element.

| Type   |
| ------ |
| string |

***

### `aria-labelledby`Android[​](#aria-labelledby-android "Direct link to aria-labelledby-android")

Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the [`nativeID`](/docs/view#nativeid) of the related element:

React TSX

```
<View>

  <Text nativeID="formLabel">Label for Input Field</Text>

  <TextInput aria-label="input" aria-labelledby="formLabel" />

</View>
```

| Type   |
| ------ |
| string |

***

### `aria-live`Android[​](#aria-live-android "Direct link to aria-live-android")

Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

* **off** 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.

| Type                                     | Default |
| ---------------------------------------- | ------- |
| enum(`'assertive'`, `'off'`, `'polite'`) | `'off'` |

***

### `aria-modal`iOS[​](#aria-modal-ios "Direct link to aria-modal-ios")

Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. Has precedence over the [`accessibilityViewIsModal`](#accessibilityviewismodal-ios) prop.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-selected`[​](#aria-selected "Direct link to aria-selected")

Indicates whether a selectable element is currently selected or not.

| Type    |
| ------- |
| boolean |

### `aria-valuemax`[​](#aria-valuemax "Direct link to aria-valuemax")

Represents the maximum value for range-based components, such as sliders and progress bars. Has precedence over the `max` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuemin`[​](#aria-valuemin "Direct link to aria-valuemin")

Represents the minimum value for range-based components, such as sliders and progress bars. Has precedence over the `min` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuenow`[​](#aria-valuenow "Direct link to aria-valuenow")

Represents the current value for range-based components, such as sliders and progress bars. Has precedence over the `now` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuetext`[​](#aria-valuetext "Direct link to aria-valuetext")

Represents the textual description of the component. Has precedence over the `text` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| string |

***

### `collapsable`[​](#collapsable "Direct link to collapsable")

Views that are only used to layout their children or otherwise don't draw anything may be automatically removed from the native hierarchy as an optimization. Set this property to `false` to disable this optimization and ensure that this `View` exists in the native view hierarchy.

| Type    | Default |
| ------- | ------- |
| boolean | true    |

***

### `collapsableChildren`[​](#collapsablechildren "Direct link to collapsablechildren")

Setting to false prevents direct children of the view from being removed from the native view hierarchy, similar to the effect of setting `collapsable={false}` on each child.

| Type    | Default |
| ------- | ------- |
| boolean | true    |

***

### `experimental_accessibilityOrder`[​](#experimental_accessibilityorder "Direct link to experimental_accessibilityorder")

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

`experimental_accessibilityOrder` indicates the order in which an assistive technology focuses descendants of this `View`. This prop takes an array of strings where each string is a [`nativeID`](/docs/view#nativeid) of some descendant component whose order is being defined. This prop does not enable accessibility itself, each referenced component still needs to be accessible by setting [`accessible`](/docs/view#accessible) to true. This prop is both **nestable** and **exhaustive** meaning

* If `experimental_accessibilityOrder` contains a reference to some non-accessible component, it will focus the descendants of that component in the default order. Additionally, it can also contain a reference to other components that also have an `experimental_accessibilityOrder`.
* If some component that is otherwise accessible is not directly referenced in `experimental_accessibilityOrder`, or nested within some container directly referenced in `experimental_accessibilityOrder`, then it will not be accessible.

See the [accessibility guide](/docs/accessibility#experimental_accessibilityorder) for more information.

| Type             |
| ---------------- |
| array of strings |

***

### `focusable`Android[​](#focusable-android "Direct link to focusable-android")

Whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard.

| Type    |
| ------- |
| boolean |

***

### `hitSlop`[​](#hitslop "Direct link to hitslop")

This defines how far a touch event can start away from the view. Typical interface guidelines recommend touch targets that are at least 30 - 40 points/density-independent pixels.

For example, if a touchable view has a height of 20 the touchable height can be extended to 40 with `hitSlop={{top: 10, bottom: 10, left: 0, right: 0}}`

note

The touch area never extends past the parent view bounds, and the Z-index of sibling views always takes precedence if a touch hits two overlapping views.

| Type                                                                 |
| -------------------------------------------------------------------- |
| object: `{top: number, left: number, bottom: number, right: number}` |

***

### `id`[​](#id "Direct link to id")

Used to locate this view from native classes. Has precedence over `nativeID` prop.

warning

This disables the 'layout-only view removal' optimization for this view!

| Type   |
| ------ |
| string |

***

| Type                                             |
| ------------------------------------------------ |
| enum('auto', 'yes', 'no', 'no-hide-descendants') |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

Used to locate this view from native classes.

warning

This disables the 'layout-only view removal' optimization for this view!

| Type   |
| ------ |
| string |

***

### `needsOffscreenAlphaCompositing`[​](#needsoffscreenalphacompositing "Direct link to needsoffscreenalphacompositing")

Whether this `View` needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior. The default (`false`) falls back to drawing the component and its children with an alpha applied to the paint used to draw each element instead of rendering the full component offscreen and compositing it back with an alpha value. This default may be noticeable and undesired in the case where the `View` you are setting an opacity on has multiple overlapping elements (e.g. multiple overlapping `View`s, or text and a background).

Rendering offscreen to preserve correct alpha behavior is extremely expensive and hard to debug for non-native developers, which is why it is not turned on by default. If you do need to enable this property for an animation, consider combining it with renderToHardwareTextureAndroid if the view **contents** are static (i.e. it doesn't need to be redrawn each frame). If that property is enabled, this View will be rendered off-screen once, saved in a hardware texture, and then composited onto the screen with an alpha each frame without having to switch rendering targets on the GPU.

| Type |
| ---- |
| bool |

***

### `nextFocusDown`Android[​](#nextfocusdown-android "Direct link to nextfocusdown-android")

Designates the next view to receive focus when the user navigates down. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusDown).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`Android[​](#nextfocusforward-android "Direct link to nextfocusforward-android")

Designates the next view to receive focus when the user navigates forward. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusForward).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`Android[​](#nextfocusleft-android "Direct link to nextfocusleft-android")

Designates the next view to receive focus when the user navigates left. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusLeft).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`Android[​](#nextfocusright-android "Direct link to nextfocusright-android")

Designates the next view to receive focus when the user navigates right. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusRight).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`Android[​](#nextfocusup-android "Direct link to nextfocusup-android")

Designates the next view to receive focus when the user navigates up. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusUp).

| Type   |
| ------ |
| number |

***

### `onAccessibilityAction`[​](#onaccessibilityaction "Direct link to onaccessibilityaction")

Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

See the [Accessibility guide](/docs/accessibility#accessibility-actions) for more information.

| Type     |
| -------- |
| function |

***

### `onAccessibilityEscape`iOS[​](#onaccessibilityescape-ios "Direct link to onaccessibilityescape-ios")

When `accessible` is `true`, the system will invoke this function when the user performs the escape gesture.

| Type     |
| -------- |
| function |

***

### `onAccessibilityTap`iOS[​](#onaccessibilitytap-ios "Direct link to onaccessibilitytap-ios")

When `accessible` is true, the system will try to invoke this function when the user performs accessibility tap gesture.

| Type     |
| -------- |
| function |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

This event is fired immediately once the layout has been calculated, but the new layout may not yet be reflected on the screen at the time the event is received, especially if a layout animation is in progress.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: LayoutEvent}) => void` |

***

### `onMagicTap`iOS[​](#onmagictap-ios "Direct link to onmagictap-ios")

When `accessible` is `true`, the system will invoke this function when the user performs the magic tap gesture.

| Type     |
| -------- |
| function |

***

### `onMoveShouldSetResponder`[​](#onmoveshouldsetresponder "Direct link to onmoveshouldsetresponder")

Does this view want to "claim" touch responsiveness? This is called for every touch move on the `View` when it is not the responder.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onMoveShouldSetResponderCapture`[​](#onmoveshouldsetrespondercapture "Direct link to onmoveshouldsetrespondercapture")

If a parent `View` wants to prevent a child `View` from becoming responder on a move, it should have this handler which returns `true`.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onResponderGrant`[​](#onrespondergrant "Direct link to onrespondergrant")

The View is now responding for touch events. This is the time to highlight and show the user what is happening.

On Android, return true from this callback to prevent any other native components from becoming responder until this responder terminates.

| Type                                            |
| ----------------------------------------------- |
| `({nativeEvent: PressEvent}) => void ｜ boolean` |

***

### `onResponderMove`[​](#onrespondermove "Direct link to onrespondermove")

The user is moving their finger.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderReject`[​](#onresponderreject "Direct link to onresponderreject")

Another responder is already active and will not release it to that `View` asking to be the responder.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderRelease`[​](#onresponderrelease "Direct link to onresponderrelease")

Fired at the end of the touch.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderTerminate`[​](#onresponderterminate "Direct link to onresponderterminate")

The responder has been taken from the `View`. Might be taken by other views after a call to `onResponderTerminationRequest`, or might be taken by the OS without asking (e.g., happens with control center/ notification center on iOS)

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderTerminationRequest`[​](#onresponderterminationrequest "Direct link to onresponderterminationrequest")

Some other `View` wants to become responder and is asking this `View` to release its responder. Returning `true` allows its release.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onStartShouldSetResponder`[​](#onstartshouldsetresponder "Direct link to onstartshouldsetresponder")

Does this view want to become responder on the start of a touch?

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onStartShouldSetResponderCapture`[​](#onstartshouldsetrespondercapture "Direct link to onstartshouldsetrespondercapture")

If a parent `View` wants to prevent a child `View` from becoming responder on a touch start, it should have this handler which returns `true`.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `pointerEvents`[​](#pointerevents "Direct link to pointerevents")

Controls whether the `View` can be the target of touch events.

* `'auto'`: The View can be the target of touch events.
* `'none'`: The View is never the target of touch events.
* `'box-none'`: The View is never the target of touch events but its subviews can be. It behaves like if the view had the following classes in CSS:

CSS

```
.box-none {

  pointer-events: none;

}

.box-none * {

  pointer-events: auto;

}
```

* `'box-only'`: The view can be the target of touch events but its subviews cannot be. It behaves like if the view had the following classes in CSS:

CSS

```
.box-only {

  pointer-events: auto;

}

.box-only * {

  pointer-events: none;

}
```

| Type                                         |
| -------------------------------------------- |
| enum('box-none', 'none', 'box-only', 'auto') |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/element-nodes) when mounted.

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

This is a reserved performance property exposed by `RCTView` and is useful for scrolling content when there are many subviews, most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. The subviews must also have `overflow: hidden`, as should the containing view (or one of its superviews).

| Type |
| ---- |
| bool |

***

### `renderToHardwareTextureAndroid`Android[​](#rendertohardwaretextureandroid-android "Direct link to rendertohardwaretextureandroid-android")

Whether this `View` should render itself (and all of its children) into a single hardware texture on the GPU.

On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can be re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation.

| Type |
| ---- |
| bool |

***

### `role`[​](#role "Direct link to role")

`role` communicates the purpose of a component to the user of an assistive technology. Has precedence over the [`accessibilityRole`](/docs/view#accessibilityrole) prop.

| Type                             |
| -------------------------------- |
| [Role](/docs/accessibility#role) |

***

### `shouldRasterizeIOS`iOS[​](#shouldrasterizeios-ios "Direct link to shouldrasterizeios-ios")

Whether this `View` should be rendered as a bitmap before compositing.

On iOS, this is useful for animations and interactions that do not modify this component's dimensions nor its children; for example, when translating the position of a static view, rasterization allows the renderer to reuse a cached bitmap of a static view and quickly composite it during each frame.

Rasterization incurs an off-screen drawing pass and the bitmap consumes memory. Test and measure when using this property.

| Type |
| ---- |
| bool |

***

### `style`[​](#style "Direct link to style")

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

***

### `tabIndex`Android[​](#tabindex-android "Direct link to tabindex-android")

Whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. Supports the following values:

* `0` - View is focusable
* `-1` - View is not focusable

| Type        |
| ----------- |
| enum(0, -1) |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

warning

This disables the 'layout-only view removal' optimization for this view!

| Type   |
| ------ |
| string |

* [Synthetic Touch Events](#synthetic-touch-events)

* [Props](#props)

  * [`accessibilityActions`](#accessibilityactions)
  * [`accessibilityElementsHidden`](#accessibilityelementshidden-ios)

    [iOS](#accessibilityelementshidden-ios)
  * [`accessibilityHint`](#accessibilityhint)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)
  * [`accessibilityIgnoresInvertColors`](#accessibilityignoresinvertcolors-ios)

    [iOS](#accessibilityignoresinvertcolors-ios)
  * [`accessibilityLabel`](#accessibilitylabel)
  * [`accessibilityLiveRegion`](#accessibilityliveregion-android)

    [Android](#accessibilityliveregion-android)
  * [`accessibilityRole`](#accessibilityrole)
  * [`accessibilityState`](#accessibilitystate)
  * [`accessibilityValue`](#accessibilityvalue)
  * [`accessibilityViewIsModal`](#accessibilityviewismodal-ios)

    [iOS](#accessibilityviewismodal-ios)

    [Android](#aria-labelledby-android)
  * [`aria-live`](#aria-live-android)

    [Android](#aria-live-android)
  * [`aria-modal`](#aria-modal-ios)

    [iOS](#aria-modal-ios)

    [Android](#focusable-android)
  * [`hitSlop`](#hitslop)
  * [`id`](#id)
  * [`importantForAccessibility`](#importantforaccessibility-android)

    [Android](#importantforaccessibility-android)
  * [`nativeID`](#nativeid)
  * [`needsOffscreenAlphaCompositing`](#needsoffscreenalphacompositing)
  * [`nextFocusDown`](#nextfocusdown-android)

    [Android](#nextfocusdown-android)
  * [`nextFocusForward`](#nextfocusforward-android)

    [Android](#nextfocusforward-android)
  * [`nextFocusLeft`](#nextfocusleft-android)

    [Android](#nextfocusleft-android)
  * [`nextFocusRight`](#nextfocusright-android)

    [Android](#nextfocusright-android)
  * [`nextFocusUp`](#nextfocusup-android)

    [Android](#nextfocusup-android)
  * [`onAccessibilityAction`](#onaccessibilityaction)
  * [`onAccessibilityEscape`](#onaccessibilityescape-ios)

    [iOS](#onaccessibilityescape-ios)
  * [`onAccessibilityTap`](#onaccessibilitytap-ios)

    [iOS](#onaccessibilitytap-ios)
  * [`onLayout`](#onlayout)
  * [`onMagicTap`](#onmagictap-ios)

    [iOS](#onmagictap-ios)

    [Android](#rendertohardwaretextureandroid-android)
  * [`role`](#role)
  * [`shouldRasterizeIOS`](#shouldrasterizeios-ios)

    [iOS](#shouldrasterizeios-ios)
  * [`style`](#style)
  * [`tabIndex`](#tabindex-android)

    [Android](#tabindex-android)
  * [`testID`](#testid)

----
url: https://reactnative.dev/docs/environment-setup
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

If your app has unusual constraints that are not served well by a Framework, or you prefer to solve these problems yourself, you can make a React Native app without a Framework using Android Studio, Xcode. If you’re interested in this path, learn how to [set up your environment](/docs/set-up-your-environment) and how to [get started without a framework](/docs/getting-started-without-a-framework).

```
npx create-expo-app@latest
```

Once you’ve created your app, check out the rest of Expo’s getting started guide to start developing your app.

[Continue with Expo](https://docs.expo.dev/get-started/set-up-your-environment)

----
url: https://reactnative.dev/docs/next/toastandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/toastandroid)** (0.87).

Version: Next

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `show()`[​](#show "Direct link to show")

React TSX

```
static show(message: string, duration: number);
```

***

### `showWithGravity()`[​](#showwithgravity "Direct link to showwithgravity")

This property will only work on Android API 29 and below. For similar functionality on higher Android APIs, consider using snackbar or notification.

React TSX

```
static showWithGravity(message: string, duration: number, gravity: number);
```

***

### `showWithGravityAndOffset()`[​](#showwithgravityandoffset "Direct link to showwithgravityandoffset")

This property will only work on Android API 29 and below. For similar functionality on higher Android APIs, consider using snackbar or notification.

React TSX

```
static showWithGravityAndOffset(

  message: string,

  duration: number,

  gravity: number,

  xOffset: number,

  yOffset: number,

);
```

## Properties[​](#properties "Direct link to Properties")

### `SHORT`[​](#short "Direct link to short")

Indicates the duration on the screen.

React TSX

```
static SHORT: number;
```

***

### `LONG`[​](#long "Direct link to long")

Indicates the duration on the screen.

React TSX

```
static LONG: number;
```

***

### `TOP`[​](#top "Direct link to top")

Indicates the position on the screen.

React TSX

```
static TOP: number;
```

***

### `BOTTOM`[​](#bottom "Direct link to bottom")

Indicates the position on the screen.

React TSX

```
static BOTTOM: number;
```

***

### `CENTER`[​](#center "Direct link to center")

Indicates the position on the screen.

React TSX

```
static CENTER: number;
```

----
url: https://reactnative.dev/docs/timepickerandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=timepicker) instead.

----
url: https://reactnative.dev/docs/next/hermes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/hermes)** (0.87).

Version: Next

```
const isHermes = () => !!global.HermesInternal;
```

```
npm run android -- --mode="release"
```

```
yarn android --mode release
```

* npm
* Yarn

```
npm run ios -- --mode="Release"
```

```
yarn ios --mode Release
```

This will compile JavaScript to Hermes Bytecode during build time which will improve your app's startup speed on device.

## Switching back to JavaScriptCore[​](#switching-back-to-javascriptcore "Direct link to Switching back to JavaScriptCore")

React Native also supports using JavaScriptCore as the [JavaScript engine](/docs/next/javascript-environment). Follow the instructions [from the community repository](https://github.com/react-native-community/javascriptcore) to opt-out of Hermes.

* [Bundled Hermes](#bundled-hermes)
* [Confirming Hermes is in use](#confirming-hermes-is-in-use)
* [Switching back to JavaScriptCore](#switching-back-to-javascriptcore)

----
url: https://reactnative.dev/docs/next/global-PerformanceResourceTiming
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-PerformanceResourceTiming)** (0.87).

Version: Next

----
url: https://reactnative.dev/docs/the-new-architecture/pure-cxx-modules
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
npx @react-native-community/cli@latest init SampleApp --version "0.87.0"
```

```
// @flow

import type {TurboModule} from 'react-native'

import { TurboModuleRegistry } from "react-native";



export interface Spec extends TurboModule {

  +reverseString: (input: string) => string;

}



export default (TurboModuleRegistry.getEnforcing<Spec>(

  "NativeSampleModule"

): Spec);
```

specs/NativeSampleModule.ts

```
import {TurboModule, TurboModuleRegistry} from 'react-native';



export interface Spec extends TurboModule {

  readonly reverseString: (input: string) => string;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeSampleModule',

);
```

## 2. Configure Codegen[​](#2-configure-codegen "Direct link to 2. Configure Codegen")

The next step is to configure [Codegen](/docs/the-new-architecture/what-is-codegen) in your `package.json`. Update the file to include:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "AppSpecs",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.sampleapp.specs"

     }

   },

   "dependencies": {
```

This configuration tells Codegen to look for spec files in the `specs` folder. It also instructs Codegen to only generate code for `modules` and to namespace the generated code as `AppSpecs`.

## 3. Write the Native Code[​](#3-write-the-native-code "Direct link to 3. Write the Native Code")

Writing a C++ Turbo Native Module allows you to share the code between Android and iOS. Therefore we will be writing the code once, and we will look into what changes we need to apply to the platforms so that the C++ code can be picked up.

1. Create a folder named `shared` at the same level as the `android` and `ios` folders.

2. Inside the `shared` folder, create a new file called `NativeSampleModule.h`.

   shared/NativeSampleModule.h

   ```
   #pragma once



   #include <AppSpecsJSI.h>



   #include <memory>

   #include <string>



   namespace facebook::react {



   class NativeSampleModule : public NativeSampleModuleCxxSpec<NativeSampleModule> {

   public:

     NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker);



     std::string reverseString(jsi::Runtime& rt, std::string input);

   };



   } // namespace facebook::react
   ```

3. Inside the `shared` folder, create a new file called `NativeSampleModule.cpp`.

   shared/NativeSampleModule.cpp

   ```
   #include "NativeSampleModule.h"



   namespace facebook::react {



   NativeSampleModule::NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker)

       : NativeSampleModuleCxxSpec(std::move(jsInvoker)) {}



   std::string NativeSampleModule::reverseString(jsi::Runtime& rt, std::string input) {

     return std::string(input.rbegin(), input.rend());

   }



   } // namespace facebook::react
   ```

```
cmake_minimum_required(VERSION 3.13)



# Define the library name here.

project(appmodules)



# This file includes all the necessary to let you build your React Native application

include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake)



# Define where the additional source code lives. We need to crawl back the jni, main, src, app, android folders

target_sources(${CMAKE_PROJECT_NAME} PRIVATE ../../../../../shared/NativeSampleModule.cpp)



# Define where CMake can find the additional header files. We need to crawl back the jni, main, src, app, android folders

target_include_directories(${CMAKE_PROJECT_NAME} PUBLIC ../../../../../shared)
```

```
    buildTypes {

        debug {

            signingConfig signingConfigs.debug

        }

        release {

            // Caution! In production, you need to generate your own keystore file.

            // see https://reactnative.dev/docs/signed-apk-android.

            signingConfig signingConfigs.debug

            minifyEnabled enableProguardInReleaseBuilds

            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"

        }

    }



+   externalNativeBuild {

+       cmake {

+           path "src/main/jni/CMakeLists.txt"

+       }

+   }

}
```

This block tells the Gradle file where to look for the CMake file. The path is relative to the folder where the `build.gradle` file lives, so we need to add the path to the `CMakeLists.txt` files in the `jni` folder.

#### 3. Register the new Turbo Native Module[​](#3-register-the-new-turbo-native-module "Direct link to 3. Register the new Turbo Native Module")

The final step is to register the new C++ Turbo Native Module in the runtime, so that when JS requires the C++ Turbo Native Module, the app knows where to find it and can return it.

1. From the folder `SampleApp/android/app/src/main/jni`, run the following command:

shell

```
curl -O https://raw.githubusercontent.com/react/react-native/v0.87.0/packages/react-native/ReactAndroid/cmake-utils/default-app-setup/OnLoad.cpp
```

2. Then, modify this file as follows:

android/app/src/main/jni/OnLoad.cpp

```
#include <DefaultComponentsRegistry.h>

#include <DefaultTurboModuleManagerDelegate.h>

#include <autolinking.h>

#include <fbjni/fbjni.h>

#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>

#include <rncore.h>



+ // Include the NativeSampleModule header

+ #include <NativeSampleModule.h>



//...



std::shared_ptr<TurboModule> cxxModuleProvider(

    const std::string& name,

    const std::shared_ptr<CallInvoker>& jsInvoker) {

  // Here you can provide your CXX Turbo Modules coming from

  // either your application or from external libraries. The approach to follow

  // is similar to the following (for a module called `NativeCxxModuleExample`):

  //

  // if (name == NativeCxxModuleExample::kModuleName) {

  //   return std::make_shared<NativeCxxModuleExample>(jsInvoker);

  // }



+  // This code registers the module so that when the JS side asks for it, the app can return it

+  if (name == NativeSampleModule::kModuleName) {

+    return std::make_shared<NativeSampleModule>(jsInvoker);

+  }



  // And we fallback to the CXX module providers autolinked

  return autolinking_cxxModuleProvider(name, jsInvoker);

}



// leave the rest of the file
```

```
cd ios

bundle install

bundle exec pod install
```

#### 2. Add the shared folder to the iOS project[​](#2-add-the-shared-folder-to-the-ios-project "Direct link to 2. Add the shared folder to the iOS project")

This step adds the `shared` folder to the project to make it visible to Xcode.

1. Open the CocoaPods generated Xcode Workspace.

```
cd ios

open SampleApp.xcworkspace
```

```


#import <Foundation/Foundation.h>

#import <ReactCommon/RCTTurboModule.h>



NS_ASSUME_NONNULL_BEGIN



@interface NativeSampleModuleProvider : NSObject <RCTModuleProvider>



@end



NS_ASSUME_NONNULL_END
```

This declares a `NativeSampleModuleProvider` object that conforms to the `RCTModuleProvider` protocol.

7. Implement the content of the `NativeSampleModuleProvider.mm` with the following:

NativeSampleModuleProvider.mm

```


#import "NativeSampleModuleProvider.h"

#import <ReactCommon/CallInvoker.h>

#import <ReactCommon/TurboModule.h>

#import "NativeSampleModule.h"



@implementation NativeSampleModuleProvider



- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:

    (const facebook::react::ObjCTurboModule::InitParams &)params

{

  return std::make_shared<facebook::react::NativeSampleModule>(params.jsInvoker);

}



@end
```

This code implements the `RCTModuleProvider` protocol by creating the pure C++ `NativeSampleModule` when the `getTurboModule:` method is called.

##### 3.2 Update the package.json[​](#32-update-the-packagejson "Direct link to 3.2 Update the package.json")

The last step consists in updating the `package.json` to tell React Native about the link between the JS specs of the Native Module and the concrete implementation of those spec in native code.

Modify the `package.json` as it follows:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "AppSpecs",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.sampleapp.specs"

     },

     "ios": {

        "modulesProvider": {

          "NativeSampleModule":  "NativeSampleModuleProvider"

        }

     }

   },



   "dependencies": {
```

At this point, you need to re-install the pods to make sure that codegen runs again to generate the new files:

```
# from the ios folder

bundle exec pod install

open SampleApp.xcworkspace
```

If you now build your application from Xcode, you should be able to build successfully.

## 5. Testing your Code[​](#5-testing-your-code "Direct link to 5. Testing your Code")

It's now time to access our C++ Turbo Native Module from JS. To do so, we have to modify the `App.tsx` file to import the Turbo Native Module and to call it in our code.

1. Open the `App.tsx` file.
2. Replace the content of the template with the following code:

App.tsx

```
import {type JSX, useState} from 'react';

import {

  Button,

  SafeAreaView,

  StyleSheet,

  Text,

  TextInput,

  View,

} from 'react-native';

import SampleTurboModule from './specs/NativeSampleModule';



function App(): JSX.Element {

  const [value, setValue] = useState('');

  const [reversedValue, setReversedValue] = useState('');



  const onPress = () => {

    const revString = SampleTurboModule.reverseString(value);

    setReversedValue(revString);

  };



  return (

    <SafeAreaView style={styles.container}>

      <View>

        <Text style={styles.title}>

          Welcome to C++ Turbo Native Module Example

        </Text>

        <Text>Write down here the text you want to reverse</Text>

        <TextInput

          style={styles.textInput}

          placeholder="Write your text here"

          onChangeText={setValue}

          value={value}

        />

        <Button title="Reverse" onPress={onPress} />

        <Text>Reversed text: {reversedValue}</Text>

      </View>

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

  },

  title: {

    fontSize: 18,

    marginBottom: 20,

  },

  textInput: {

    borderColor: 'black',

    borderWidth: 1,

    borderRadius: 5,

    padding: 10,

    marginTop: 10,

  },

});



export default App;
```

The interesting lines in this app are:

* `import SampleTurboModule from './specs/NativeSampleModule';`: this line imports the Turbo Native Module in the app,
* `const revString = SampleTurboModule.reverseString(value);` in the `onPress` callback: this is how you can use the Turbo Native Module in your app.

warning

For the sake of this example and to keep it as short as possible, we directly imported the spec file in our app. The best practice in this case is to create a separate file to wrap the specs and use that file into your application. This allows you to prepare the input for the specs and gives you more control over them in JS.

Congratulations, you wrote your first C++ Turbo Native Module!

| Android | iOS |
| ------- | --- |
|         |     |

----
url: https://reactnative.dev/docs/next/app-extensions
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/app-extensions)** (0.87).

Version: Next

----
url: https://reactnative.dev/docs/global-URL
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/URL) for more information.

The global `URL` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/image
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
dependencies {

  // If your app supports Android versions before Ice Cream Sandwich (API level 14)

  implementation 'com.facebook.fresco:animated-base-support:1.3.0'



  // For animated GIF support

  implementation 'com.facebook.fresco:animated-gif:3.6.0'



  // For WebP support, including animated WebP

  implementation 'com.facebook.fresco:animated-webp:3.6.0'

  implementation 'com.facebook.fresco:webpsupport:3.6.0'



  // For WebP support, without animations

  implementation 'com.facebook.fresco:webpsupport:3.6.0'

}
```

note

The version listed above may not be updated in time. Please check [`packages/react-native/gradle/libs.versions.toml`](https://github.com/react/react-native/blob/main/packages/react-native/gradle/libs.versions.toml) in the main repo to see which fresco version is being used in a specific tagged version.

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### `accessible`[​](#accessible "Direct link to accessible")

When true, indicates the image is an accessibility element.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

The text that's read by the screen reader when the user interacts with the image.

| Type   |
| ------ |
| string |

***

### `alt`[​](#alt "Direct link to alt")

A string that defines an alternative text description of the image, which will be read by the screen reader when the user interacts with it. Using this will automatically mark this element as accessible.

| Type   |
| ------ |
| string |

***

### `blurRadius`[​](#blurradius "Direct link to blurradius")

blurRadius: the blur radius of the blur filter added to the image.

| Type   |
| ------ |
| number |

tip

On IOS, you will need to increase `blurRadius` by more than `5`.

***

### `capInsets`iOS[​](#capinsets-ios "Direct link to capinsets-ios")

When the image is resized, the corners of the size specified by `capInsets` will stay a fixed size, but the center content and borders of the image will be stretched. This is useful for creating resizable rounded buttons, shadows, and other resizable assets. More info in the [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).

| Type               |
| ------------------ |
| [Rect](/docs/rect) |

***

### `crossOrigin`[​](#crossorigin "Direct link to crossorigin")

A string of a keyword specifying the CORS mode to use when fetching the image resource. It works similar to crossorigin attribute in HTML.

* `anonymous`: No exchange of user credentials in the image request.
* `use-credentials`: Sets `Access-Control-Allow-Credentials` header value to `true` in the image request.

| Type                                     | Default       |
| ---------------------------------------- | ------------- |
| enum(`'anonymous'`, `'use-credentials'`) | `'anonymous'` |

***

### `defaultSource`[​](#defaultsource "Direct link to defaultsource")

A static image to display while loading the image source.

| Type                                   |
| -------------------------------------- |
| [ImageSource](/docs/image#imagesource) |

note

On Android, the default source prop is ignored on debug builds.

***

### `fadeDuration`Android[​](#fadeduration-android "Direct link to fadeduration-android")

Fade animation duration in milliseconds.

| Type   | Default |
| ------ | ------- |
| number | `300`   |

***

### `height`[​](#height "Direct link to height")

Height of the image component.

| Type   |
| ------ |
| number |

***

### `loadingIndicatorSource`[​](#loadingindicatorsource "Direct link to loadingindicatorsource")

Similarly to `source`, this property represents the resource used to render the loading indicator for the image. The loading indicator is displayed until image is ready to be displayed, typically after the image is downloaded.

| Type                                                        |
| ----------------------------------------------------------- |
| [ImageSource](/docs/image#imagesource) (`uri` only), number |

***

### `onError`[​](#onerror "Direct link to onerror")

Invoked on load error.

| Type                                |
| ----------------------------------- |
| (`{nativeEvent: {error} }`) => void |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: LayoutEvent} => void` |

***

### `onLoad`[​](#onload "Direct link to onload")

Invoked when load completes successfully.

**Example:** `onLoad={({nativeEvent: {source: {width, height}}}) => setImageRealSize({width, height})}`

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: ImageLoadEvent} => void` |

***

### `onLoadEnd`[​](#onloadend "Direct link to onloadend")

Invoked when load either succeeds or fails.

| Type       |
| ---------- |
| () => void |

***

### `onLoadStart`[​](#onloadstart "Direct link to onloadstart")

Invoked on load start.

**Example:** `onLoadStart={() => this.setState({loading: true})}`

| Type       |
| ---------- |
| () => void |

***

### `onPartialLoad`iOS[​](#onpartialload-ios "Direct link to onpartialload-ios")

Invoked when a partial load of the image is complete. The definition of what constitutes a "partial load" is loader specific though this is meant for progressive JPEG loads.

| Type       |
| ---------- |
| () => void |

***

### `onProgress`[​](#onprogress "Direct link to onprogress")

Invoked on download progress.

| Type                                        |
| ------------------------------------------- |
| (`{nativeEvent: {loaded, total} }`) => void |

***

### `progressiveRenderingEnabled`Android[​](#progressiverenderingenabled-android "Direct link to progressiverenderingenabled-android")

When `true`, enables progressive jpeg streaming - <https://frescolib.org/docs/progressive-jpegs>.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `referrerPolicy`[​](#referrerpolicy "Direct link to referrerpolicy")

A string indicating which referrer to use when fetching the resource. Sets the value for `Referrer-Policy` header in the image request. Works similar to `referrerpolicy` attribute in HTML.

| Type                                                                                                                                                                                     | Default                             |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| enum(`'no-referrer'`, `'no-referrer-when-downgrade'`, `'origin'`, `'origin-when-cross-origin'`, `'same-origin'`, `'strict-origin'`, `'strict-origin-when-cross-origin'`, `'unsafe-url'`) | `'strict-origin-when-cross-origin'` |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/element-nodes) when mounted.

***

| Type                                            | Default  |
| ----------------------------------------------- | -------- |
| enum(`'auto'`, `'resize'`, `'scale'`, `'none'`) | `'auto'` |

***

| Type                                                              | Default   |
| ----------------------------------------------------------------- | --------- |
| enum(`'cover'`, `'contain'`, `'stretch'`, `'repeat'`, `'center'`) | `'cover'` |

***

### `resizeMultiplier`Android[​](#resizemultiplier-android "Direct link to resizemultiplier-android")

When the `resizeMethod` is set to `resize`, the destination dimensions are multiplied by this value. The `scale` method is used to perform the remainder of the resize. A default of `1.0` means the bitmap size is designed to fit the destination dimensions. A multiplier greater than `1.0` will set the resize options larger than that of the destination dimensions, and the resulting bitmap will be scaled down from the hardware size. Defaults to `1.0`.

This prop is most useful in cases where the destination dimensions are quite small and the source image is significantly larger. The `resize` resize method performs downsampling and significant image quality is lost between the source and destination image sizes, often resulting in a blurry image. By using a multiplier, the decoded image is slightly larger than the target size but smaller than the source image (if the source image is large enough). This allows aliasing artifacts to produce faux quality through scaling operations on the multiplied image.

If you have a source image with dimensions 200x200 and destination dimensions of 24x24, a resizeMultiplier of `2.0` will tell Fresco to downsample the image to 48x48. Fresco picks the closest power of 2 (so, 50x50) and decodes the image into a bitmap of that size. Without the multiplier, the closest power of 2 would be 25x25. The resultant image is scaled down by the system.

| Type   | Default |
| ------ | ------- |
| number | `1.0`   |

***

### `source`[​](#source "Direct link to source")

The image source (either a remote URL or a local file resource).

This prop can also contain several remote URLs, specified together with their width and height and potentially with scale/other URI arguments. The native side will then choose the best `uri` to display based on the measured size of the image container. A `cache` property can be added to control how networked request interacts with the local cache. (For more information see [Cache Control for Images](/docs/images#cache-control)).

The currently supported formats are `png`, `jpg`, `jpeg`, `bmp`, `gif`, `webp`, `psd` (iOS only). In addition, iOS supports several RAW image formats. Refer to Apple's documentation for the current list of supported camera models (for iOS 12, see <https://support.apple.com/en-ca/HT208967>).

Please note that the `webp` format is supported on iOS **only** when bundled with the JavaScript code.

| Type                                   |
| -------------------------------------- |
| [ImageSource](/docs/image#imagesource) |

***

### `src`[​](#src "Direct link to src")

A string representing the remote URL of the image. This prop has precedence over `source` prop.

**Example:** `src={'https://reactnative.dev/img/tiny_logo.png'}`

| Type   |
| ------ |
| string |

***

### `srcSet`[​](#srcset "Direct link to srcset")

A string representing comma separated list of possible candidate image source. Each image source contains a URL of an image and a pixel density descriptor. If no descriptor is specified, it defaults to descriptor of `1x`.

If `srcSet` does not contain a `1x` descriptor, the value in `src` is used as image source with `1x` descriptor (if provided).

This prop has precedence over both the `src` and `source` props.

**Example:** `srcSet={'https://reactnative.dev/img/tiny_logo.png 1x, https://reactnative.dev/img/header_logo.svg 2x'}`

| Type   |
| ------ |
| string |

***

### `style`[​](#style "Direct link to style")

| Type                                                                                                                                                                             |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Image Style Props](/docs/image-style-props#props), [Layout Props](/docs/layout-props#props), [Shadow Props](/docs/shadow-props#props), [Transforms](/docs/transforms#transform) |

***

### `testID`[​](#testid "Direct link to testid")

A unique identifier for this element to be used in UI Automation testing scripts.

| Type   |
| ------ |
| string |

***

### `tintColor`[​](#tintcolor "Direct link to tintcolor")

Changes the color of all non-transparent pixels to the `tintColor`.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `width`[​](#width "Direct link to width")

Width of the image component.

| Type   |
| ------ |
| number |

## Methods[​](#methods "Direct link to Methods")

### `abortPrefetch()`Android[​](#abortprefetch-android "Direct link to abortprefetch-android")

React TSX

```
static abortPrefetch(requestId: number);
```

Abort prefetch request.

**Parameters:**

| Name              | Type   | Description                             |
| ----------------- | ------ | --------------------------------------- |
| requestIdRequired | number | Request id as returned by `prefetch()`. |

***

### `getSize()`[​](#getsize "Direct link to getsize")

React TSX

```
static getSize(uri: string): Promise<{width: number, height: number}>;
```

Retrieve the width and height (in pixels) of an image prior to displaying it. This method can fail if the image cannot be found, or fails to download.

In order to retrieve the image dimensions, the image may first need to be loaded or downloaded, after which it will be cached. This means that in principle you could use this method to preload images, however it is not optimized for that purpose, and may in future be implemented in a way that does not fully load/download the image data. A proper, supported way to preload images will be provided as a separate API.

**Parameters:**

| Name        | Type   | Description                |
| ----------- | ------ | -------------------------- |
| uriRequired | string | The location of the image. |

***

### `getSizeWithHeaders()`[​](#getsizewithheaders "Direct link to getsizewithheaders")

React TSX

```
static getSizeWithHeaders(

  uri: string,

  headers: {[index: string]: string}

): Promise<{width: number, height: number}>;
```

Retrieve the width and height (in pixels) of an image prior to displaying it with the ability to provide the headers for the request. This method can fail if the image cannot be found, or fails to download. It also does not work for static image resources.

In order to retrieve the image dimensions, the image may first need to be loaded or downloaded, after which it will be cached. This means that in principle you could use this method to preload images, however it is not optimized for that purpose, and may in future be implemented in a way that does not fully load/download the image data. A proper, supported way to preload images will be provided as a separate API.

**Parameters:**

| Name            | Type   | Description                  |
| --------------- | ------ | ---------------------------- |
| uriRequired     | string | The location of the image.   |
| headersRequired | object | The headers for the request. |

***

### `prefetch()`[​](#prefetch "Direct link to prefetch")

React TSX

```
await Image.prefetch(url);
```

Prefetches a remote image for later use by downloading it to the disk cache. Returns a promise which resolves to a boolean.

**Parameters:**

| Name        | Type            | Description                                            |
| ----------- | --------------- | ------------------------------------------------------ |
| urlRequired | string          | The remote location of the image.                      |
| callback    | functionAndroid | The function that will be called with the `requestId`. |

***

### `queryCache()`[​](#querycache "Direct link to querycache")

React TSX

```
static queryCache(

  urls: string[],

): Promise<Record<string, 'memory' | 'disk' | 'disk/memory'>>;
```

Perform cache interrogation. Returns a promise which resolves to a mapping from URL to cache status, such as "disk", "memory" or "disk/memory". If a requested URL is not in the mapping, it means it's not in the cache.

**Parameters:**

| Name         | Type  | Description                                |
| ------------ | ----- | ------------------------------------------ |
| urlsRequired | array | List of image URLs to check the cache for. |

***

### `resolveAssetSource()`[​](#resolveassetsource "Direct link to resolveassetsource")

React TSX

```
static resolveAssetSource(source: ImageSourcePropType): {

  height: number;

  width: number;

  scale: number;

  uri: string;

};
```

Resolves an asset reference into an object which has the properties `uri`, `scale`, `width`, and `height`.

**Parameters:**

| Name           | Type                                           | Description                                                                  |
| -------------- | ---------------------------------------------- | ---------------------------------------------------------------------------- |
| sourceRequired | [ImageSource](/docs/image#imagesource), number | A number (opaque type returned by `require('./foo.png')`) or an ImageSource. |

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### ImageCacheEnumiOS[​](#imagecacheenum-ios "Direct link to imagecacheenum-ios")

Enum which can be used to set the cache handling or strategy for the potentially cached responses.

| Type                                                               | Default     |
| ------------------------------------------------------------------ | ----------- |
| enum(`'default'`, `'reload'`, `'force-cache'`, `'only-if-cached'`) | `'default'` |

* `default`: Use the native platforms default strategy.
* `reload`: The data for the URL will be loaded from the originating source. No existing cache data should be used to satisfy a URL load request.
* `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.

### ImageLoadEvent[​](#imageloadevent "Direct link to ImageLoadEvent")

Object returned in the `onLoad` callback.

| Type   |
| ------ |
| object |

**Properties:**

| Name   | Type   | Description                         |
| ------ | ------ | ----------------------------------- |
| source | object | The [source object](#source-object) |

#### Source Object[​](#source-object "Direct link to Source Object")

**Properties:**

| Name   | Type   | Description                                                  |
| ------ | ------ | ------------------------------------------------------------ |
| width  | number | The width of loaded image.                                   |
| height | number | The height of loaded image.                                  |
| uri    | string | A string representing the resource identifier for the image. |

### ImageSource[​](#imagesource "Direct link to ImageSource")

| Type                             |
| -------------------------------- |
| object, array of objects, number |

**Properties (if passing as object or array of objects):**

| Name      | Type                                             | Description                                                                                                                                                                          |
| --------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| uri       | string                                           | A string representing the resource identifier for the image, which could be an http address, a local file path, or the name of a static image resource.                              |
| width     | number                                           | Can be specified if known at build time, in which case the value will be used to set the default `<Image/>` component dimension.                                                     |
| height    | number                                           | Can be specified if known at build time, in which case the value will be used to set the default `<Image/>` component dimension.                                                     |
| scale     | number                                           | Used to indicate the scale factor of the image. Defaults to `1.0` if unspecified, meaning that one image pixel equates to one display point / DIP.                                   |
| bundleiOS | string                                           | The iOS asset bundle which the image is included in. This will default to `[NSBundle mainBundle]` if not set.                                                                        |
| method    | string                                           | The HTTP Method to use. Defaults to `'GET'` if not specified.                                                                                                                        |
| headers   | object                                           | An object representing the HTTP headers to send along with the request for a remote image.                                                                                           |
| body      | string                                           | The HTTP body to send with the request. This must be a valid UTF-8 string, and will be sent exactly as specified, with no additional encoding (e.g. URL-escaping or base64) applied. |
| cacheiOS  | [ImageCacheEnum](/docs/image#imagecacheenum-ios) | Determines how the requests handles potentially cached responses.                                                                                                                    |

    [iOS](#capinsets-ios)
  * [`crossOrigin`](#crossorigin)
  * [`defaultSource`](#defaultsource)
  * [`fadeDuration`](#fadeduration-android)

    [Android](#fadeduration-android)

    [iOS](#onpartialload-ios)
  * [`onProgress`](#onprogress)
  * [`progressiveRenderingEnabled`](#progressiverenderingenabled-android)

    [Android](#progressiverenderingenabled-android)
  * [`referrerPolicy`](#referrerpolicy)
  * [`ref`](#ref)
  * [`resizeMethod`](#resizemethod-android)

    [Android](#resizemethod-android)
  * [`resizeMode`](#resizemode)
  * [`resizeMultiplier`](#resizemultiplier-android)

    [Android](#resizemultiplier-android)

    [Android](#abortprefetch-android)

    [iOS](#imagecacheenum-ios)
  * [ImageLoadEvent](#imageloadevent)
  * [ImageSource](#imagesource)

----
url: https://reactnative.dev/docs/the-new-architecture/using-codegen
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
npx @react-native-community/cli@latest init SampleApp --version "0.87.0"
```

**Codegen** is used to generate the glue-code for your custom modules or components. See the guides for Turbo Native Modules and Fabric Native Components for more details on how to create them.

## Configuring **Codegen**[​](#configuring-codegen "Direct link to configuring-codegen")

**Codegen** can be configured in your app by modifying the `package.json` file. **Codegen** is controlled by a custom field called `codegenConfig`.

package.json

```
  "codegenConfig": {

    "name": "<SpecName>",

    "type": "<types>",

    "jsSrcsDir": "<source_dir>",

    "android": {

      "javaPackageName": "<java.package.name>"

    },

    "ios": {

      "modules": {

        "TestModule": {

          "className": "<iOS-class-implementing-the-RCTModuleProvider-protocol>",

          "unstableRequiresMainQueueSetup": false,

          "conformsToProtocols": ["RCTImageURLLoader", "RCTURLRequestHandler", "RCTImageDataDecoder"],

        }

      },

      "components": {

        "TestComponent": {

          "className": "<iOS-class-implementing-the-component>"

        }

      }

    }

  },
```

    * `.className`: This module's ObjC class. Or, if it's a [C++-only module](/docs/next/the-new-architecture/pure-cxx-modules), its `RCTModuleProvider` class.
    * `.unstableRequiresMainQueueSetup`: Initialize this module on the UI Thread, before running any JavaScript.
    * `.conformsToProtocols`: Annotate which of these protocols this module conforms to any of the following protocols: [`RCTImageURLLoader`](https://github.com/react/react-native/blob/00d5caee9921b6c10be8f7d5b3903c6afe8dbefa/packages/react-native/Libraries/Image/RCTImageURLLoader.h#L26-L81), [`RCTURLRequestHandler`](https://github.com/react/react-native/blob/00d5caee9921b6c10be8f7d5b3903c6afe8dbefa/packages/react-native/React/Base/RCTURLRequestHandler.h#L11-L52), [`RCTImageDataDecoder`](https://github.com/react/react-native/blob/00d5caee9921b6c10be8f7d5b3903c6afe8dbefa/packages/react-native/Libraries/Image/RCTImageDataDecoder.h#L15-L53).

  * `.components[componentName]`:
    * `.className`: This component's ObjC class (e.g: `TextInput` -> `RCTTextInput`).

```
./gradlew generateCodegenArtifactsFromSchema
```

This task invokes the `generateCodegenArtifactsFromSchema` command on all the imported projects of the app (the app and all the node modules which are linked to it). It generates the code in the corresponding `node_modules/<dependency>` folder. For example, if you have a Fabric Native Component whose Node module is called `my-fabric-component`, the generated code is located in the `SampleApp/node_modules/my-fabric-component/android/build/generated/source/codegen` path. For the app, the code is generated in the `android/app/build/generated/source/codegen` folder.

#### The Generated Code[​](#the-generated-code "Direct link to The Generated Code")

After running the gradle command above, you will find the codegen code in the `SampleApp/android/app/build` folder. The structure will look like this:

```
build

└── generated

    └── source

        └── codegen

            ├── java

            │   └── com

            │       ├── facebook

            │       │   └── react

            │       │       └── viewmanagers

            │       │           ├── <nativeComponent>ManagerDelegate.java

            │       │           └── <nativeComponent>ManagerInterface.java

            │       └── sampleapp

            │           └── NativeLocalStorageSpec.java

            ├── jni

            │   ├── <codegenConfig.name>-generated.cpp

            │   ├── <codegenConfig.name>.h

            │   ├── CMakeLists.txt

            │   └── react

            │       └── renderer

            │           └── components

            │               └── <codegenConfig.name>

            │                   ├── <codegenConfig.name>JSI-generated.cpp

            │                   ├── <codegenConfig.name>.h

            │                   ├── ComponentDescriptors.cpp

            │                   ├── ComponentDescriptors.h

            │                   ├── EventEmitters.cpp

            │                   ├── EventEmitters.h

            │                   ├── Props.cpp

            │                   ├── Props.h

            │                   ├── ShadowNodes.cpp

            │                   ├── ShadowNodes.h

            │                   ├── States.cpp

            │                   └── States.h

            └── schema.json
```

```
node node_modules/react-native/scripts/generate-codegen-artifacts.js



Usage: generate-codegen-artifacts.js -p [path to app] -t [target platform] -o [output path]



Options:

      --help            Show help                                      [boolean]

      --version         Show version number                            [boolean]

  -p, --path            Path to the React Native project root.        [required]

  -t, --targetPlatform  Target platform. Supported values: "android", "ios",

                        "all".                                        [required]

  -o, --outputPath      Path where generated artifacts will be output to.
```

where:

* `--path` is the path to the root folder of your app.
* `--outputPath` is the destination where **Codegen** will write the generated files.
* `--targetPlatform` is the platform you'd like to generate the code for.

#### The Generated Code[​](#the-generated-code-1 "Direct link to The Generated Code")

Running the script with these arguments:

```
node node_modules/react-native/scripts/generate-codegen-artifacts.js \

    --path . \

    --outputPath ios/ \

    --targetPlatform ios
```

Will generate these files in the `ios/build` folder:

```
build

└── generated

    └── ios

        ├── <codegenConfig.name>

        │   ├── <codegenConfig.name>-generated.mm

        │   └── <codegenConfig.name>.h

        ├── <codegenConfig.name>JSI-generated.cpp

        ├── <codegenConfig.name>JSI.h

        ├── FBReactNativeSpec

        │   ├── FBReactNativeSpec-generated.mm

        │   └── FBReactNativeSpec.h

        ├── FBReactNativeSpecJSI-generated.cpp

        ├── FBReactNativeSpecJSI.h

        ├── RCTModulesConformingToProtocolsProvider.h

        ├── RCTModulesConformingToProtocolsProvider.mm

        └── react

            └── renderer

                └── components

                    └── <codegenConfig.name>

                        ├── ComponentDescriptors.cpp

                        ├── ComponentDescriptors.h

                        ├── EventEmitters.cpp

                        ├── EventEmitters.h

                        ├── Props.cpp

                        ├── Props.h

                        ├── RCTComponentViewHelpers.h

                        ├── ShadowNodes.cpp

                        ├── ShadowNodes.h

                        ├── States.cpp

                        └── States.h
```

----
url: https://reactnative.dev/docs/next/the-new-architecture/direct-manipulation-new-architecture
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/direct-manipulation-new-architecture)** (0.87).

Version: Next

You can use the [`clear`](/docs/next/textinput#clear) method to clear the `TextInput` which clears the current input text using the same approach.

## Avoiding conflicts with the render function[​](#avoiding-conflicts-with-the-render-function "Direct link to Avoiding conflicts with the render function")

If you update a property that is also managed by the render function, you might end up with some unpredictable and confusing bugs because anytime the component re-renders and that property changes, whatever value was previously set from `setNativeProps` will be completely ignored and overridden.

* [setNativeProps to edit TextInput value](#setnativeprops-to-edit-textinput-value)
* [Avoiding conflicts with the render function](#avoiding-conflicts-with-the-render-function)

----
url: https://reactnative.dev/docs/animatedvaluexy
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

2D Value for driving 2D animations, such as pan gestures. Almost identical API to normal [`Animated.Value`](/docs/animatedvalue), but multiplexed. Contains two regular `Animated.Value`s under the hood.

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `setValue()`[​](#setvalue "Direct link to setvalue")

React TSX

```
setValue(value: {x: number; y: number});
```

Directly set the value. This will stop any animations running on the value and update all the bound properties.

**Parameters:**

| Name  | Type                     | Required | Description |
| ----- | ------------------------ | -------- | ----------- |
| value | `{x: number; y: number}` | Yes      | Value       |

***

### `setOffset()`[​](#setoffset "Direct link to setoffset")

React TSX

```
setOffset(offset: {x: number; y: number});
```

Sets an offset that is applied on top of whatever value is set, whether via `setValue`, an animation, or `Animated.event`. Useful for compensating things like the start of a pan gesture.

**Parameters:**

| Name   | Type                     | Required | Description  |
| ------ | ------------------------ | -------- | ------------ |
| offset | `{x: number; y: number}` | Yes      | Offset value |

***

### `flattenOffset()`[​](#flattenoffset "Direct link to flattenoffset")

React TSX

```
flattenOffset();
```

Merges the offset value into the base value and resets the offset to zero. The final output of the value is unchanged.

***

### `extractOffset()`[​](#extractoffset "Direct link to extractoffset")

React TSX

```
extractOffset();
```

Sets the offset value to the base value, and resets the base value to zero. The final output of the value is unchanged.

***

### `addListener()`[​](#addlistener "Direct link to addlistener")

React TSX

```
addListener(callback: (value: {x: number; y: number}) => void);
```

Adds an asynchronous listener to the value so you can observe updates from animations. This is useful because there is no way to synchronously read the value because it might be driven natively.

Returns a string that serves as an identifier for the listener.

**Parameters:**

| Name     | Type     | Required | Description                                                                                 |
| -------- | -------- | -------- | ------------------------------------------------------------------------------------------- |
| callback | function | Yes      | The callback function which will receive an object with a `value` key set to the new value. |

***

### `removeListener()`[​](#removelistener "Direct link to removelistener")

React TSX

```
removeListener(id: string);
```

Unregister a listener. The `id` param shall match the identifier previously returned by `addListener()`.

**Parameters:**

| Name | Type   | Required | Description                        |
| ---- | ------ | -------- | ---------------------------------- |
| id   | string | Yes      | Id for the listener being removed. |

***

### `removeAllListeners()`[​](#removealllisteners "Direct link to removealllisteners")

React TSX

```
removeAllListeners();
```

Remove all registered listeners.

***

### `stopAnimation()`[​](#stopanimation "Direct link to stopanimation")

React TSX

```
stopAnimation(callback?: (value: {x: number; y: number}) => void);
```

Stops any running animation or tracking. `callback` is invoked with the final value after stopping the animation, which is useful for updating state to match the animation position with layout.

**Parameters:**

| Name     | Type     | Required | Description                                   |
| -------- | -------- | -------- | --------------------------------------------- |
| callback | function | No       | A function that will receive the final value. |

***

### `resetAnimation()`[​](#resetanimation "Direct link to resetanimation")

React TSX

```
resetAnimation(callback?: (value: {x: number; y: number}) => void);
```

Stops any animation and resets the value to its original.

**Parameters:**

| Name     | Type     | Required | Description                                      |
| -------- | -------- | -------- | ------------------------------------------------ |
| callback | function | No       | A function that will receive the original value. |

***

### `getLayout()`[​](#getlayout "Direct link to getlayout")

React TSX

```
getLayout(): {left: Animated.Value, top: Animated.Value};
```

Converts `{x, y}` into `{left, top}` for use in style, e.g.

React TSX

```
style={this.state.anim.getLayout()}
```

***

### `getTranslateTransform()`[​](#gettranslatetransform "Direct link to gettranslatetransform")

React TSX

```
getTranslateTransform(): [

  {translateX: Animated.Value},

  {translateY: Animated.Value},

];
```

Converts `{x, y}` into a useable translation transform, e.g.

React TSX

```
style={{

  transform: this.state.anim.getTranslateTransform()

}}
```

----
url: https://reactnative.dev/docs/appregistry
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

### Project with Native Code Required

If you are using the managed Expo workflow there is only ever one entry component registered with `AppRegistry` and it is handled automatically (or through [registerRootComponent](https://docs.expo.dev/versions/latest/sdk/register-root-component/)). You do not need to use this API.

`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`.

React TSX

```
import {Text, AppRegistry} from 'react-native';



const App = () => (

  <View>

    <Text>App1</Text>

  </View>

);



AppRegistry.registerComponent('Appname', () => App);
```

To "stop" an application when a view should be destroyed, call `AppRegistry.unmountApplicationComponentAtRootTag` with the tag that was passed into `runApplication`. These should always be used as a pair.

`AppRegistry` should be required early in the `require` sequence to make sure the JS execution environment is setup before other modules are required.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `getAppKeys()`[​](#getappkeys "Direct link to getappkeys")

React TSX

```
static getAppKeys(): string[];
```

Returns an array of strings.

***

### `getRegistry()`[​](#getregistry "Direct link to getregistry")

React TSX

```
static getRegistry(): {sections: string[]; runnables: Runnable[]};
```

Returns a [Registry](/docs/appregistry#registry) object.

***

### `getRunnable()`[​](#getrunnable "Direct link to getrunnable")

React TSX

```
static getRunnable(appKey: string): : Runnable | undefined;
```

Returns a [Runnable](/docs/appregistry#runnable) object.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| appKeyRequired | string |

***

### `getSectionKeys()`[​](#getsectionkeys "Direct link to getsectionkeys")

React TSX

```
static getSectionKeys(): string[];
```

Returns an array of strings.

***

### `getSections()`[​](#getsections "Direct link to getsections")

React TSX

```
static getSections(): Record<string, Runnable>;
```

Returns a [Runnables](/docs/appregistry#runnables) object.

***

### `registerCancellableHeadlessTask()`[​](#registercancellableheadlesstask "Direct link to registercancellableheadlesstask")

React TSX

```
static registerCancellableHeadlessTask(

  taskKey: string,

  taskProvider: TaskProvider,

  taskCancelProvider: TaskCancelProvider,

);
```

Register a headless task which can be cancelled. A headless task is a bit of code that runs without a UI.

**Parameters:**

| Name                        | Type                                                       | Description                                                                                                                                                                                                                         |
| --------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| taskKey Required            | string                                                     | The native id for this task instance that was used when startHeadlessTask was called.                                                                                                                                               |
| taskProvider Required       | [TaskProvider](/docs/appregistry#taskprovider)             | A promise returning function that takes some data passed from the native side as the only argument. When the promise is resolved or rejected the native side is notified of this event and it may decide to destroy the JS context. |
| taskCancelProvider Required | [TaskCancelProvider](/docs/appregistry#taskcancelprovider) | a void returning function that takes no arguments; when a cancellation is requested, the function being executed by taskProvider should wrap up and return ASAP.                                                                    |

***

### `registerComponent()`[​](#registercomponent "Direct link to registercomponent")

React TSX

```
static registerComponent(

  appKey: string,

  getComponentFunc: ComponentProvider,

  section?: boolean,

): string;
```

**Parameters:**

| Name                      | Type              |
| ------------------------- | ----------------- |
| appKeyRequired            | string            |
| componentProviderRequired | ComponentProvider |
| section                   | boolean           |

***

### `registerConfig()`[​](#registerconfig "Direct link to registerconfig")

React TSX

```
static registerConfig(config: AppConfig[]);
```

**Parameters:**

| Name           | Type                                        |
| -------------- | ------------------------------------------- |
| configRequired | [AppConfig](/docs/appregistry#appconfig)\[] |

***

### `registerHeadlessTask()`[​](#registerheadlesstask "Direct link to registerheadlesstask")

React TSX

```
static registerHeadlessTask(

  taskKey: string,

  taskProvider: TaskProvider,

);
```

Register a headless task. A headless task is a bit of code that runs without a UI.

This is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.

**Parameters:**

| Name                 | Type                                           | Description                                                                                                                                                                                                                         |
| -------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| taskKeyRequired      | string                                         | The native id for this task instance that was used when startHeadlessTask was called.                                                                                                                                               |
| taskProviderRequired | [TaskProvider](/docs/appregistry#taskprovider) | A promise returning function that takes some data passed from the native side as the only argument. When the promise is resolved or rejected the native side is notified of this event and it may decide to destroy the JS context. |

***

### `registerRunnable()`[​](#registerrunnable "Direct link to registerrunnable")

React TSX

```
static registerRunnable(appKey: string, func: Runnable): string;
```

**Parameters:**

| Name           | Type     |
| -------------- | -------- |
| appKeyRequired | string   |
| runRequired    | function |

***

### `registerSection()`[​](#registersection "Direct link to registersection")

React TSX

```
static registerSection(

  appKey: string,

  component: ComponentProvider,

);
```

**Parameters:**

| Name              | Type              |
| ----------------- | ----------------- |
| appKeyRequired    | string            |
| componentRequired | ComponentProvider |

***

### `runApplication()`[​](#runapplication "Direct link to runapplication")

React TSX

```
static runApplication(appKey: string, appParameters: any): void;
```

Loads the JavaScript bundle and runs the app.

**Parameters:**

| Name                  | Type   |
| --------------------- | ------ |
| appKeyRequired        | string |
| appParametersRequired | any    |

***

### `setComponentProviderInstrumentationHook()`[​](#setcomponentproviderinstrumentationhook "Direct link to setcomponentproviderinstrumentationhook")

React TSX

```
static setComponentProviderInstrumentationHook(

  hook: ComponentProviderInstrumentationHook,

);
```

**Parameters:**

| Name         | Type     |
| ------------ | -------- |
| hookRequired | function |

A valid `hook` function accepts the following as arguments:

| Name                            | Type               |
| ------------------------------- | ------------------ |
| componentRequired               | ComponentProvider  |
| scopedPerformanceLoggerRequired | IPerformanceLogger |

The function must also return a React Component.

***

### `setWrapperComponentProvider()`[​](#setwrappercomponentprovider "Direct link to setwrappercomponentprovider")

React TSX

```
static setWrapperComponentProvider(

  provider: WrapperComponentProvider,

);
```

**Parameters:**

| Name             | Type              |
| ---------------- | ----------------- |
| providerRequired | ComponentProvider |

***

### `startHeadlessTask()`[​](#startheadlesstask "Direct link to startheadlesstask")

React TSX

```
static startHeadlessTask(

  taskId: number,

  taskKey: string,

  data: any,

);
```

Only called from native code. Starts a headless task.

**Parameters:**

| Name            | Type   | Description                                                          |
| --------------- | ------ | -------------------------------------------------------------------- |
| taskIdRequired  | number | The native id for this task instance to keep track of its execution. |
| taskKeyRequired | string | The key for the task to start.                                       |
| dataRequired    | any    | The data to pass to the task.                                        |

***

### `unmountApplicationComponentAtRootTag()`[​](#unmountapplicationcomponentatroottag "Direct link to unmountapplicationcomponentatroottag")

React TSX

```
static unmountApplicationComponentAtRootTag(rootTag: number);
```

Stops an application when a view should be destroyed.

**Parameters:**

| Name            | Type   |
| --------------- | ------ |
| rootTagRequired | number |

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### AppConfig[​](#appconfig "Direct link to AppConfig")

Application configuration for the `registerConfig` method.

| Type   |
| ------ |
| object |

**Properties:**

| Name           | Type              |
| -------------- | ----------------- |
| appKeyRequired | string            |
| component      | ComponentProvider |
| run            | function          |
| section        | boolean           |

note

Every config is expected to set either `component` or `run` function.

### Registry[​](#registry "Direct link to Registry")

| Type   |
| ------ |
| object |

**Properties:**

| Name      | Type                                             |
| --------- | ------------------------------------------------ |
| runnables | array of [Runnables](/docs/appregistry#runnable) |
| sections  | array of strings                                 |

### Runnable[​](#runnable "Direct link to Runnable")

| Type   |
| ------ |
| object |

**Properties:**

| Name      | Type              |
| --------- | ----------------- |
| component | ComponentProvider |
| run       | function          |

### Runnables[​](#runnables "Direct link to Runnables")

An object with key of `appKey` and value of type of [`Runnable`](/docs/appregistry#runnable).

| Type   |
| ------ |
| object |

### Task[​](#task "Direct link to Task")

A `Task` is a function that accepts any data as argument and returns a Promise that resolves to `undefined`.

| Type     |
| -------- |
| function |

### TaskCanceller[​](#taskcanceller "Direct link to TaskCanceller")

A `TaskCanceller` is a function that accepts no argument and returns void.

| Type     |
| -------- |
| function |

### TaskCancelProvider[​](#taskcancelprovider "Direct link to TaskCancelProvider")

A valid `TaskCancelProvider` is a function that returns a [`TaskCanceller`](/docs/appregistry#taskcanceller).

| Type     |
| -------- |
| function |

### TaskProvider[​](#taskprovider "Direct link to TaskProvider")

A valid `TaskProvider` is a function that returns a [`Task`](/docs/appregistry#task).

| Type     |
| -------- |
| function |

----
url: https://reactnative.dev/docs/global-intersectionobserverentry
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Canary 🧪

**This API is currently only available in React Native’s Canary and Experimental channels.**

If you want to try it out, please [enable the Canary Channel](/docs/release-levels) in your app.

The [`IntersectionObserverEntry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry) interface, as defined in Web specifications. It describes the intersection between the target element and its root container at a specific moment of transition.

Instances of `IntersectionObserverEntry` are delivered to an [`IntersectionObserver`](/docs/global-intersectionobserver) callback in its `entries` parameter.

***

```
get rnRootIntersectionRatio(): number;
```

----
url: https://reactnative.dev/docs/layoutanimation
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Automatically animates views to their new positions when the next layout happens.

A common way to use this API is to call it before updating the state hook in functional components and calling `setState` in class components.

Note that in order to get this to work on **Android** you need to set the following flags via `UIManager`:

JavaScript

```
if (Platform.OS === 'android') {

  if (UIManager.setLayoutAnimationEnabledExperimental) {

    UIManager.setLayoutAnimationEnabledExperimental(true);

  }

}
```

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `configureNext()`[​](#configurenext "Direct link to configurenext")

React TSX

```
static configureNext(

  config: LayoutAnimationConfig,

  onAnimationDidEnd?: () => void,

  onAnimationDidFail?: () => void,

);
```

Schedules an animation to happen on the next layout.

#### Parameters:[​](#parameters "Direct link to Parameters:")

| Name               | Type     | Required | Description                         |
| ------------------ | -------- | -------- | ----------------------------------- |
| config             | object   | Yes      | See config description below.       |
| onAnimationDidEnd  | function | No       | Called when the animation finished. |
| onAnimationDidFail | function | No       | Called when the animation failed.   |

The `config` parameter is an object with the keys below. [`create`](/docs/layoutanimation#create) returns a valid object for `config`, and the [`Presets`](/docs/layoutanimation#presets) objects can also all be passed as the `config`.

* `duration` in milliseconds
* `create`, optional config for animating in new views
* `update`, optional config for animating views that have been updated
* `delete`, optional config for animating views as they are removed

The config that's passed to `create`, `update`, or `delete` has the following keys:

* `type`, the [animation type](/docs/layoutanimation#types) to use
* `property`, the [layout property](/docs/layoutanimation#properties) to animate (optional, but recommended for `create` and `delete`)
* `springDamping` (number, optional and only for use with `type: Type.spring`)
* `initialVelocity` (number, optional)
* `delay` (number, optional)
* `duration` (number, optional)

***

### `create()`[​](#create "Direct link to create")

React TSX

```
static create(duration, type, creationProp)
```

Helper that creates an object (with `create`, `update`, and `delete` fields) to pass into [`configureNext`](/docs/layoutanimation#configurenext). The `type` parameter is an [animation type](/docs/layoutanimation#types), and the `creationProp` parameter is a [layout property](/docs/layoutanimation#properties).

**Example:**

## Properties[​](#properties "Direct link to Properties")

### Types[​](#types "Direct link to Types")

An enumeration of animation types to be used in the [`create`](/docs/layoutanimation#create) method, or in the `create`/`update`/`delete` configs for [`configureNext`](/docs/layoutanimation#configurenext). (example usage: `LayoutAnimation.Types.easeIn`)

| Types         |
| ------------- |
| spring        |
| linear        |
| easeInEaseOut |
| easeIn        |
| easeOut       |
| keyboard      |

***

### Properties[​](#properties-1 "Direct link to Properties")

An enumeration of layout properties to be animated to be used in the [`create`](/docs/layoutanimation#create) method, or in the `create`/`update`/`delete` configs for [`configureNext`](/docs/layoutanimation#configurenext). (example usage: `LayoutAnimation.Properties.opacity`)

| Properties |
| ---------- |
| opacity    |
| scaleX     |
| scaleY     |
| scaleXY    |

***

### Presets[​](#presets "Direct link to Presets")

A set of predefined animation configs to pass into [`configureNext`](/docs/layoutanimation#configurenext).

| Presets       | Value                                                                                                                                                          |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| easeInEaseOut | `create(300, 'easeInEaseOut', 'opacity')`                                                                                                                      |
| linear        | `create(500, 'linear', 'opacity')`                                                                                                                             |
| spring        | `{duration: 700, create: {type: 'linear', property: 'opacity'}, update: {type: 'spring', springDamping: 0.4}, delete: {type: 'linear', property: 'opacity'} }` |

***

### `easeInEaseOut`[​](#easeineaseout "Direct link to easeineaseout")

Calls `configureNext()` with `Presets.easeInEaseOut`.

***

### `linear`[​](#linear "Direct link to linear")

Calls `configureNext()` with `Presets.linear`.

***

----
url: https://reactnative.dev/docs/i18nmanager
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
static isRTL: boolean;
```

A boolean value indicating whether the app is currently in RTL layout mode.

The value of `isRTL` is determined by the following logic:

* If `forceRTL` is `true`, `isRTL` returns `true`

* If `allowRTL` is `false`, `isRTL` returns `false`

* Otherwise, `isRTL` will be `true` given the following:

  * **iOS:**

    * The user-preferred language on the device is an RTL language
    * The application-defined localizations include the user-chosen language (as defined in the Xcode project file (`knownRegions = (...)`)

  * **Android:**

    * The user-preferred language on the device is an RTL language
    * The application's `AndroidManifest.xml` defines `android:supportsRTL="true"` on the `<application>` element

### `doLeftAndRightSwapInRTL`[​](#doleftandrightswapinrtl "Direct link to doleftandrightswapinrtl")

TypeScript

```
static doLeftAndRightSwapInRTL: boolean;
```

A boolean value indicating whether left and right style properties should be automatically swapped when in RTL mode. When enabled, left becomes right and right becomes left in RTL layouts.

## Methods[​](#methods "Direct link to Methods")

### `allowRTL()`[​](#allowrtl "Direct link to allowrtl")

TypeScript

```
static allowRTL: (allowRTL: boolean) => void;
```

```
static forceRTL: (forced: boolean) => void;
```

```
static swapLeftAndRightInRTL: (swapLeftAndRight: boolean) => void;
```

----
url: https://reactnative.dev/docs/next/building-for-tv
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/building-for-tv)** (0.87).

Version: Next

TV devices support has been implemented with the intention of making existing React Native applications work on Apple TV and Android TV, with few or no changes needed in the JavaScript code for the applications.

Deprecated

TV support has moved to the [React Native for TV](https://github.com/react-native-tvos/react-native-tvos#readme) repository. Please see the **README** there for information on projects for Apple TV or Android TV.

----
url: https://reactnative.dev/docs/appstate
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

***

# Reference

## Events[​](#events "Direct link to Events")

### `change`[​](#change "Direct link to change")

This event is received when the app state has changed. The listener is called with one of [the current app state values](/docs/appstate#app-states).

```
static addEventListener(

  type: AppStateEvent,

  listener: (state: AppStateStatus) => void,

): EventSubscription;
```

Sets up a function that will be called whenever the specified event type on AppState occurs. Valid values for `eventType` are [listed above](#events). Returns the `EventSubscription`.

## Properties[​](#properties "Direct link to Properties")

### `currentState`[​](#currentstate "Direct link to currentstate")

React TSX

```
static currentState: AppStateStatus;
```

* [App States](#app-states)

* [Basic Usage](#basic-usage)

* [Events](#events)

  * [`change`](#change)
  * [`memoryWarning`](#memorywarning-ios)

    [iOS](#memorywarning-ios)
  * [`focus`](#focus-android)

    [Android](#focus-android)
  * [`blur`](#blur-android)

    [Android](#blur-android)

* [Methods](#methods)
  * [`addEventListener()`](#addeventlistener)

* [Properties](#properties)
  * [`currentState`](#currentstate)

----
url: https://reactnative.dev/docs/the-new-architecture/turbo-modules-with-swift
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
import Foundation



@objcMembers public class NativeLocalStorage: NSObject {

  let userDefaults = UserDefaults(suiteName: "local-storage");



  public func getItem(for key: String) -> String? {

    return userDefaults?.string(forKey: key)

  }



  public func setItem(for key: String, value: String) {

    userDefaults?.set(value, forKey: key)

  }



  public func removeItem(for key: String) {

    userDefaults?.removeObject(forKey: key)

  }



  public func clear() {

    userDefaults?.dictionaryRepresentation().keys.forEach { removeItem(for: $0) }

  }

}
```

Notice that you have to declare all the methods that you need to call from Objective-C as `public` and with the `@objc` annotation. Remember also to make your class inherit from `NSObject`, otherwise it would not be possible to use it from Objective-C.

### Update the `RCTNativeLocalStorage` file[​](#update-the-rctnativelocalstorage-file "Direct link to update-the-rctnativelocalstorage-file")

Then, you need to update the implementation of the `RCTNativeLocalStorage` to be able to create the Swift module and to call its methods.

1. Open the `RCTNativeLocalStorage.mm` file
2. Update it as it follows:

RCTNativeLocalStorage.mm

```
//  RCTNativeLocalStorage.m

//  TurboModuleExample



#import "RCTNativeLocalStorage.h"

+#import "SampleApp-Swift.h"



- static NSString *const RCTNativeLocalStorageKey = @"local-storage";



-@interface RCTNativeLocalStorage()

-@property (strong, nonatomic) NSUserDefaults *localStorage;

-@end



-@implementation RCTNativeLocalStorage

+@implementation RCTNativeLocalStorage {

+    NativeLocalStorage *storage;

+}



-RCT_EXPORT_MODULE(NativeLocalStorage)



 - (id) init {

   if (self = [super init]) {

-    _localStorage = [[NSUserDefaults alloc] initWithSuiteName:RCTNativeLocalStorageKey];

+    storage = [NativeLocalStorage new];

   }

   return self;

 }



 - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {

   return std::make_shared<facebook::react::NativeLocalStorageSpecJSI>(params);

 }



 - (NSString * _Nullable)getItem:(NSString *)key {

-   return [self.localStorage stringForKey:key];

+   return [storage getItemFor:key];

 }



 - (void)setItem:(NSString *)value key:(NSString *)key {

-   [self.localStorage setObject:value forKey:key];

+   [storage setItemFor:key value:value];

 }



 - (void)removeItem:(NSString *)key {

-   [self.localStorage removeObjectForKey:key];

+   [storage removeItemFor:key];

 }



 - (void)clear {

-   NSDictionary *keys = [self.localStorage dictionaryRepresentation];

-   for (NSString *key in keys) {

-     [self removeItem:key];

-   }

+  [storage clear];

 }



++ (NSString *)moduleName

+{

+  return @"NativeLocalStorage";

+}



@end
```

```
//

//  Use this file to import your target's public headers that you would like to expose to Swift.

//



+ #import <React-RCTAppDelegate/RCTDefaultReactNativeFactoryDelegate.h>
```

----
url: https://reactnative.dev/docs/next/boxshadowvalue
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/boxshadowvalue)** (0.87).

Version: Next

The `BoxShadowValue` object is taken by the [`boxShadow`](/docs/next/view-style-props#boxshadow) style prop. It is comprised of 2-4 lengths, an optional color, and an optional `inset` boolean. These values collectively define the box shadow's color, position, size, and blurriness.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

  offsetX: 10,

  offsetY: -3,

  blurRadius: '15px',

  spreadDistance: '10px',

  color: 'red',

  inset: true,

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `offsetX`[​](#offsetx "Direct link to offsetx")

The offset on the x-axis. This can be positive or negative. A positive value indicates right and negative indicates left.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | No       |

### `offsetY`[​](#offsety "Direct link to offsety")

The offset on the y-axis. This can be positive or negative. A positive value indicates up and negative indicates down.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | No       |

### `blurRadius`[​](#blurradius "Direct link to blurradius")

Represents the radius used in the [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) algorithm. The larger the value the blurrier the shadow is. Only non-negative values are valid. The default is 0.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | Yes      |

### `spreadDistance`[​](#spreaddistance "Direct link to spreaddistance")

How much larger or smaller the shadow grows or shrinks. A positive value will grow the shadow, a negative value will shrink the shadow.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | Yes      |

### `color`[​](#color "Direct link to color")

The color of the shadow. The default is `black`.

| Type                       | Optional |
| -------------------------- | -------- |
| [color](/docs/next/colors) | Yes      |

### `inset`[​](#inset "Direct link to inset")

Whether the shadow is inset or not. Inset shadows will appear around the inside of the element's border box as opposed to the outside.

| Type    | Optional |
| ------- | -------- |
| boolean | Yes      |

## Used by[​](#used-by "Direct link to Used by")

* [`boxShadow`](/docs/next/view-style-props#boxshadow)

----
url: https://reactnative.dev/docs/next/debugging-native-code
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/debugging-native-code)** (0.87).

Version: Next

### Projects with Native Code Only

The following section only applies to projects with native code exposed. If you are using the managed Expo workflow, see the guide on [prebuild](https://docs.expo.dev/workflow/prebuild/) to use this API.

## Accessing Logs[​](#accessing-logs "Direct link to Accessing Logs")

You can display the native logs for an iOS or Android app by using the following commands in a terminal while the app is running:

```
# For Android:

npx react-native log-android

# Or, for iOS:

npx react-native log-ios
```

You may also access these through Debug > Open System Log… in the iOS Simulator or by running `adb logcat "*:S" ReactNative:V ReactNativeJS:V` in a terminal while an Android app is running on a device or emulator.

**💡 Custom Native Logs**

If you are writing a Native Module and want to add custom logs to your module for debugging purposes, you can use the following method:

#### Android (Java/Kotlin)[​](#android-javakotlin "Direct link to Android (Java/Kotlin)")

In your native module, use the `Log` class to add logs that can be viewed in Logcat:

Java

```
import android.util.Log;



private void log(String message) {

    Log.d("YourModuleName", message);

}
```

To view these logs in Logcat, use this command, replacing `YourModuleName` with your custom tag:

```
adb logcat "*:S" ReactNative:V ReactNativeJS:V YourModuleName:D
```

#### iOS (Objective-C/Swift)[​](#ios-objective-cswift "Direct link to iOS (Objective-C/Swift)")

In your native module, use `NSLog` for custom logs:

Objective-C

```
NSLog(@"YourModuleName: %@", message);
```

Or, in Swift:

Swift

```
print("YourModuleName: \(message)")
```

----
url: https://reactnative.dev/docs/next/integration-with-existing-apps
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/integration-with-existing-apps)** (0.87).

Version: Next

Follow the guide on [setting up your development environment](/docs/next/set-up-your-environment) and using [React Native without a framework](/docs/next/getting-started-without-a-framework) to configure your development environment for building React Native apps for Android. This guide also assumes you're familiar with the basics of Android development such as creating Activities and editing the `AndroidManifest.xml` file.

## 1. Set up directory structure[​](#1-set-up-directory-structure "Direct link to 1. Set up directory structure")

To ensure a smooth experience, create a new folder for your integrated React Native project, then **move your existing Android project** to the `/android` subfolder.

## 2. Install NPM dependencies[​](#2-install-npm-dependencies "Direct link to 2. Install NPM dependencies")

Go to the root directory and run the following command:

shell

```
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/main/template/package.json
```

This will copy the `package.json` [file from the Community template](https://github.com/react-native-community/template/blob/main/template/package.json) to your project.

Next, install the NPM packages by running:

* npm
* Yarn

```
npm install
```

```
yarn install
```

Installation process has created a new `node_modules` folder. This folder stores all the JavaScript dependencies required to build your project.

Add `node_modules/` to your `.gitignore` file (here the [Community default one](https://github.com/react-native-community/template/blob/main/template/_gitignore)).

## 3. Adding React Native to your app[​](#3-adding-react-native-to-your-app "Direct link to 3. Adding React Native to your app")

### Configuring Gradle[​](#configuring-gradle "Direct link to Configuring Gradle")

React Native uses the React Native Gradle Plugin to configure your dependencies and project setup.

First, let's edit your `settings.gradle` file by adding those lines (as suggested from the [Community template](https://github.com/react-native-community/template/blob/main/template/android/settings.gradle)):

Groovy

```
// Configures the React Native Gradle Settings plugin used for autolinking

pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }

plugins { id("com.facebook.react.settings") }

extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }

// If using .gradle.kts files:

// extensions.configure<com.facebook.react.ReactSettingsExtension> { autolinkLibrariesFromCommand() }

includeBuild("../node_modules/@react-native/gradle-plugin")



// Include your existing Gradle modules here.

// include(":app")
```

Then you need to open your top level `build.gradle` and include this line (as suggested from the [Community template](https://github.com/react-native-community/template/blob/main/template/android/build.gradle)):

Diff

```
buildscript {

    repositories {

        google()

        mavenCentral()

    }

    dependencies {

        classpath("com.android.tools.build:gradle:7.3.1")

+       classpath("com.facebook.react:react-native-gradle-plugin")

    }

}
```

This makes sure the React Native Gradle Plugin (RNGP) is available inside your project. Finally, add those lines inside your Applications's `build.gradle` file (it's a different `build.gradle` file usually inside your `app` folder - you can use the [Community template file as reference](https://github.com/react-native-community/template/blob/main/template/android/build.gradle)):

Diff

```
apply plugin: "com.android.application"

+apply plugin: "com.facebook.react"



repositories {

    mavenCentral()

}



dependencies {

    // Other dependencies here

+   // Note: we intentionally don't specify the version number here as RNGP will take care of it.

+   // If you don't use the RNGP, you'll have to specify version manually.

+   implementation("com.facebook.react:react-android")

+   implementation("com.facebook.react:hermes-android")

}



+react {

+   // Needed to enable Autolinking - https://github.com/react-native-community/cli/blob/master/docs/autolinking.md

+   autolinkLibrariesWithApp()

+}
```

Finally, open your application `gradle.properties` files and add the following line (here the [Community template file as reference](https://github.com/react-native-community/template/blob/main/template/android/gradle.properties)):

Diff

```
+reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64

+newArchEnabled=true

+hermesEnabled=true
```

### Configuring your manifest[​](#configuring-your-manifest "Direct link to Configuring your manifest")

First, make sure you have the Internet permission in your `AndroidManifest.xml`:

Diff

```
<manifest xmlns:android="http://schemas.android.com/apk/res/android">



+   <uses-permission android:name="android.permission.INTERNET" />



    <application

      android:name=".MainApplication">

    </application>

</manifest>
```

Then you need to enable [cleartext traffic](https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted) in your **debug** `AndroidManifest.xml`:

Diff

```
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools">



    <application

+       android:usesCleartextTraffic="true"

+       tools:targetApi="28"

    />

</manifest>
```

As usual, here the AndroidManifest.xml file from the Community template to use as a reference: [main](https://github.com/react-native-community/template/blob/main/template/android/app/src/main/AndroidManifest.xml) and [debug](https://github.com/react-native-community/template/blob/main/template/android/app/src/debug/AndroidManifest.xml).

Our index.js should look as follows (here the [Community template file as reference](https://github.com/react-native-community/template/blob/main/template/index.js)):

JavaScript

```
import {AppRegistry} from 'react-native';

import App from './App';



AppRegistry.registerComponent('HelloWorld', () => App);
```

### Create a `App.tsx` file[​](#create-a-apptsx-file "Direct link to create-a-apptsx-file")

Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX](https://en.wikipedia.org/wiki/JSX_\(JavaScript\)) expressions. It contains the root React Native component that we will integrate into our Android application ([link](https://github.com/react-native-community/template/blob/main/template/App.tsx)):

React TSX

```
import {type JSX} from 'react';

import {

  SafeAreaView,

  ScrollView,

  StatusBar,

  StyleSheet,

  Text,

  useColorScheme,

  View,

} from 'react-native';

import {

  Colors,

  DebugInstructions,

  Header,

  ReloadInstructions,

} from 'react-native/Libraries/NewAppScreen';



function App(): JSX.Element {

  const isDarkMode = useColorScheme() === 'dark';



  const backgroundStyle = {

    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,

  };



  return (

    <SafeAreaView style={backgroundStyle}>

      <StatusBar

        barStyle={isDarkMode ? 'light-content' : 'dark-content'}

        backgroundColor={backgroundStyle.backgroundColor}

      />

      <ScrollView

        contentInsetAdjustmentBehavior="automatic"

        style={backgroundStyle}>

        <Header />

        <View

          style={{

            backgroundColor: isDarkMode

              ? Colors.black

              : Colors.white,

            padding: 24,

          }}>

          <Text style={styles.title}>Step One</Text>

          <Text>

            Edit <Text style={styles.bold}>App.tsx</Text> to

            change this screen and see your edits.

          </Text>

          <Text style={styles.title}>See your changes</Text>

          <ReloadInstructions />

          <Text style={styles.title}>Debug</Text>

          <DebugInstructions />

        </View>

      </ScrollView>

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  title: {

    fontSize: 24,

    fontWeight: '600',

  },

  bold: {

    fontWeight: '700',

  },

});



export default App;
```

Here is the [Community template file as reference](https://github.com/react-native-community/template/blob/main/template/App.tsx).

```
package <your-package-here>;



import android.app.Application;

+import com.facebook.react.PackageList;

+import com.facebook.react.ReactApplication;

+import com.facebook.react.ReactHost;

+import com.facebook.react.ReactNativeHost;

+import com.facebook.react.ReactPackage;

+import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;

+import com.facebook.react.defaults.DefaultReactHost;

+import com.facebook.react.defaults.DefaultReactNativeHost;

+import com.facebook.soloader.SoLoader;

+import com.facebook.react.soloader.OpenSourceMergedSoMapping

+import java.util.List;



-class MainApplication extends Application {

+class MainApplication extends Application implements ReactApplication {

+ @Override

+ public ReactNativeHost getReactNativeHost() {

+   return new DefaultReactNativeHost(this) {

+     @Override

+     protected List<ReactPackage> getPackages() { return new PackageList(this).getPackages(); }

+     @Override

+     protected String getJSMainModuleName() { return "index"; }

+     @Override

+     public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; }

+     @Override

+     protected boolean isNewArchEnabled() { return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; }

+     @Override

+     protected Boolean isHermesEnabled() { return BuildConfig.IS_HERMES_ENABLED; }

+   };

+ }



+ @Override

+ public ReactHost getReactHost() {

+   return DefaultReactHost.getDefaultReactHost(getApplicationContext(), getReactNativeHost());

+ }



  @Override

  public void onCreate() {

    super.onCreate();

+   SoLoader.init(this, OpenSourceMergedSoMapping);

+   if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

+     DefaultNewArchitectureEntryPoint.load();

+   }

  }

}
```

Diff

```
// package <your-package-here>



import android.app.Application

+import com.facebook.react.PackageList

+import com.facebook.react.ReactApplication

+import com.facebook.react.ReactHost

+import com.facebook.react.ReactNativeHost

+import com.facebook.react.ReactPackage

+import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

+import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

+import com.facebook.react.defaults.DefaultReactNativeHost

+import com.facebook.soloader.SoLoader

+import com.facebook.react.soloader.OpenSourceMergedSoMapping



-class MainApplication : Application() {

+class MainApplication : Application(), ReactApplication {



+ override val reactNativeHost: ReactNativeHost =

+      object : DefaultReactNativeHost(this) {

+        override fun getPackages(): List<ReactPackage> = PackageList(this).packages

+        override fun getJSMainModuleName(): String = "index"

+        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG

+        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

+        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

+      }



+ override val reactHost: ReactHost

+   get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

+   SoLoader.init(this, OpenSourceMergedSoMapping)

+   if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

+     load()

+   }

  }

}
```

As usual, here the [`MainApplication.kt` Community template file as reference](https://github.com/react-native-community/template/blob/main/template/android/app/src/main/java/com/helloworld/MainApplication.kt).

#### Creating a `ReactActivity`[​](#creating-a-reactactivity "Direct link to creating-a-reactactivity")

Finally, we need to create a new `Activity` that will extend `ReactActivity` and host the React Native code. This activity will be responsible for starting the React Native runtime and rendering the React component.

* Java
* Kotlin

Java

```
// package <your-package-here>;



import com.facebook.react.ReactActivity;

import com.facebook.react.ReactActivityDelegate;

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;

import com.facebook.react.defaults.DefaultReactActivityDelegate;



public class MyReactActivity extends ReactActivity {



    @Override

    protected String getMainComponentName() {

        return "HelloWorld";

    }



    @Override

    protected ReactActivityDelegate createReactActivityDelegate() {

        return new DefaultReactActivityDelegate(this, getMainComponentName(), DefaultNewArchitectureEntryPoint.getFabricEnabled());

    }

}
```

Kotlin

```
// package <your-package-here>



import com.facebook.react.ReactActivity

import com.facebook.react.ReactActivityDelegate

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled

import com.facebook.react.defaults.DefaultReactActivityDelegate



class MyReactActivity : ReactActivity() {



    override fun getMainComponentName(): String = "HelloWorld"



    override fun createReactActivityDelegate(): ReactActivityDelegate =

        DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)

}
```

As usual, here the [`MainActivity.kt` Community template file as reference](https://github.com/react-native-community/template/blob/main/template/android/app/src/main/java/com/helloworld/MainActivity.kt).

Whenever you create a new Activity, you need to add it to your `AndroidManifest.xml` file. You also need set the theme of `MyReactActivity` to `Theme.AppCompat.Light.NoActionBar` (or to any non-ActionBar theme) as otherwise your application will render an ActionBar on top of your React Native screen:

Diff

```
<manifest xmlns:android="http://schemas.android.com/apk/res/android">



    <uses-permission android:name="android.permission.INTERNET" />



    <application

      android:name=".MainApplication">



+     <activity

+       android:name=".MyReactActivity"

+       android:label="@string/app_name"

+       android:theme="@style/Theme.AppCompat.Light.NoActionBar">

+     </activity>

    </application>

</manifest>
```

Now your activity is ready to run some JavaScript code.

## 6. Test your integration[​](#6-test-your-integration "Direct link to 6. Test your integration")

You have completed all the basic steps to integrate React Native with your application. Now we will start the [Metro bundler](https://metrobundler.dev/) to build your TypeScript application code into a bundle. Metro's HTTP server shares the bundle from `localhost` on your developer environment to a simulator or device. This allows for [hot reloading](https://reactnative.dev/blog/2016/03/24/introducing-hot-reloading).

First, you need to create a `metro.config.js` file in the root of your project as follows:

JavaScript

```
const {getDefaultConfig} = require('@react-native/metro-config');

module.exports = getDefaultConfig(__dirname);
```

You can checkout the [`metro.config.js` file](https://github.com/react-native-community/template/blob/main/template/metro.config.js) from the Community template file as reference.

Once you have the configuration file in place, you can run the bundler. Run the following command in the root directory of your project:

* npm
* Yarn

```
npm start
```

```
yarn start
```

Now build and run your Android app as normal.

Once you reach your React-powered Activity inside the app, it should load the JavaScript code from the development server and display:

### Creating a release build in Android Studio[​](#creating-a-release-build-in-android-studio "Direct link to Creating a release build in Android Studio")

You can use Android Studio to create your release builds too! It’s as quick as creating release builds of your previously-existing native Android app.

The React Native Gradle Plugin will take care of bundling the JS code inside your APK/App Bundle.

If you're not using Android Studio, you can create a release build with:

```
cd android

# For a Release APK

./gradlew :app:assembleRelease

# For a Release AAB

./gradlew :app:bundleRelease
```

### Now what?[​](#now-what "Direct link to Now what?")

At this point you can continue developing your app as usual. Refer to our [debugging](/docs/next/debugging) and [deployment](/docs/next/running-on-device) docs to learn more about working with React Native.

Follow the guide on [setting up your development environment](/docs/next/set-up-your-environment) and using [React Native without a framework](/docs/next/getting-started-without-a-framework) to configure your development environment for building React Native apps for iOS. This guide also assumes you're familiar with the basics of iOS development such as creating a `UIViewController` and editing the `Podfile` file.

### 1. Set up directory structure[​](#1-set-up-directory-structure "Direct link to 1. Set up directory structure")

To ensure a smooth experience, create a new folder for your integrated React Native project, then **move your existing iOS project** to the `/ios` subfolder.

## 2. Install NPM dependencies[​](#2-install-npm-dependencies "Direct link to 2. Install NPM dependencies")

Go to the root directory and run the following command:

shell

```
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/main/template/package.json
```

This will copy the `package.json` [file from the Community template](https://github.com/react-native-community/template/blob/main/template/package.json) to your project.

Next, install the NPM packages by running:

* npm
* Yarn

```
npm install
```

```
yarn install
```

Installation process has created a new `node_modules` folder. This folder stores all the JavaScript dependencies required to build your project.

Add `node_modules/` to your `.gitignore` file (here the [Community default one](https://github.com/react-native-community/template/blob/main/template/_gitignore)).

### 3. Install Development tools[​](#3-install-development-tools "Direct link to 3. Install Development tools")

### Command Line Tools for Xcode[​](#command-line-tools-for-xcode "Direct link to Command Line Tools for Xcode")

Install the Command Line Tools. Choose **Settings... (or Preferences...)** in the Xcode menu. Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown.

### CocoaPods[​](#cocoapods "Direct link to CocoaPods")

[CocoaPods](https://cocoapods.org) is a package management tool for iOS and macOS development. We use it to add the actual React Native framework code locally into your current project.

We recommend installing CocoaPods using [Homebrew](https://brew.sh/):

```
brew install cocoapods
```

```
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/main/template/Gemfile
```

This will download the Gemfile from the template.

note

If you created your project with Xcode 16, you need to update the Gemfile as it follows:

Diff

```
-gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1'

+gem 'cocoapods', '1.16.2'

gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0'

-gem 'xcodeproj', '< 1.26.0'

+gem 'xcodeproj', '1.27.0'
```

Xcode 16 generates a project in a slightly different ways from previous versions of Xcode, and you need the latest CocoaPods and Xcodeproj gems to make it work properly.

Similarly, for the **Podfile**, go to the `ios` folder of your project and run

shell

```
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/main/template/ios/Podfile
```

Please use the Community Template as a reference point for the [Gemfile](https://github.com/react-native-community/template/blob/main/template/Gemfile) and for the [Podfile](https://github.com/react-native-community/template/blob/main/template/ios/Podfile).

note

Remember to change [this line](https://github.com/react-native-community/template/blob/main/template/ios/Podfile#L17).

Now, we need to run a couple of extra commands to install the Ruby gems and the Pods. Navigate to the `ios` folder and run the following commands:

```
bundle install

bundle exec pod install
```

Our `index.js` should look as follows (here the [Community template file as reference](https://github.com/react-native-community/template/blob/main/template/index.js)):

JavaScript

```
import {AppRegistry} from 'react-native';

import App from './App';



AppRegistry.registerComponent('HelloWorld', () => App);
```

### Create a `App.tsx` file[​](#create-a-apptsx-file "Direct link to create-a-apptsx-file")

Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX](https://en.wikipedia.org/wiki/JSX_\(JavaScript\)) expressions. It contains the root React Native component that we will integrate into our iOS application ([link](https://github.com/react-native-community/template/blob/main/template/App.tsx)):

React TSX

```
import {type JSX} from 'react';

import {

  SafeAreaView,

  ScrollView,

  StatusBar,

  StyleSheet,

  Text,

  useColorScheme,

  View,

} from 'react-native';



import {

  Colors,

  DebugInstructions,

  Header,

  ReloadInstructions,

} from 'react-native/Libraries/NewAppScreen';



function App(): JSX.Element {

  const isDarkMode = useColorScheme() === 'dark';



  const backgroundStyle = {

    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,

  };



  return (

    <SafeAreaView style={backgroundStyle}>

      <StatusBar

        barStyle={isDarkMode ? 'light-content' : 'dark-content'}

        backgroundColor={backgroundStyle.backgroundColor}

      />

      <ScrollView

        contentInsetAdjustmentBehavior="automatic"

        style={backgroundStyle}>

        <Header />

        <View

          style={{

            backgroundColor: isDarkMode

              ? Colors.black

              : Colors.white,

            padding: 24,

          }}>

          <Text style={styles.title}>Step One</Text>

          <Text>

            Edit <Text style={styles.bold}>App.tsx</Text> to

            change this screen and see your edits.

          </Text>

          <Text style={styles.title}>See your changes</Text>

          <ReloadInstructions />

          <Text style={styles.title}>Debug</Text>

          <DebugInstructions />

        </View>

      </ScrollView>

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  title: {

    fontSize: 24,

    fontWeight: '600',

  },

  bold: {

    fontWeight: '700',

  },

});



export default App;
```

Here is the [Community template file as reference](https://github.com/react-native-community/template/blob/main/template/App.tsx).

## 5. Integrating with your iOS code[​](#5-integrating-with-your-ios-code "Direct link to 5. Integrating with your iOS code")

We now need to add some native code in order to start the React Native runtime and tell it to render our React components.

### Requirements[​](#requirements "Direct link to Requirements")

React Native initialization is now unbound to any specific part of an iOS app.

React Native can be initialized using a class called `RCTReactNativeFactory`, that takes care of handling the React Native lifecycle for you.

`RCTAppDelegate` is deprecated

`RCTAppDelegate` is deprecated and will be removed in a future version of React Native. New apps should bootstrap from an app-owned `SceneDelegate` (see [Bootstrapping with SceneDelegate](#6-bootstrapping-with-scenedelegate)). Existing apps that subclass `RCTAppDelegate` should migrate to `RCTReactNativeFactory` directly.

Once the class is initialized, you can either:

* bootstrap a full app from your `SceneDelegate` (see [Bootstrapping with SceneDelegate](#6-bootstrapping-with-scenedelegate)), or
* generate a `UIView` from the factory and load it in any `UIViewController` (the approach below).

In the following example, we will create a ViewController that can load a React Native view as its `view`.

```
#import "ReactViewController.h"

+#import <React/RCTBundleURLProvider.h>

+#import <RCTReactNativeFactory.h>

+#import <RCTDefaultReactNativeFactoryDelegate.h>

+#import <ReactAppDependencyProvider/RCTAppDependencyProvider.h>





@interface ReactViewController ()



@end



+@interface ReactNativeFactoryDelegate: RCTDefaultReactNativeFactoryDelegate

+@end



-@implementation ReactViewController

+@implementation ReactViewController {

+  RCTReactNativeFactory *_factory;

+  id<RCTReactNativeFactoryDelegate> _factoryDelegate;

+}



 - (void)viewDidLoad {

     [super viewDidLoad];

     // Do any additional setup after loading the view.

+    _factoryDelegate = [ReactNativeFactoryDelegate new];

+    _factoryDelegate.dependencyProvider = [RCTAppDependencyProvider new];

+    _factory = [[RCTReactNativeFactory alloc] initWithDelegate:_factoryDelegate];

+    self.view = [_factory.rootViewFactory viewWithModuleName:@"HelloWorld"];

 }



@end



+@implementation ReactNativeFactoryDelegate

+

+- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge

+{

+  return [self bundleURL];

+}

+

+- (NSURL *)bundleURL

+{

+#if DEBUG

+  return [RCTBundleURLProvider.sharedSettings jsBundleURLForBundleRoot:@"index"];

+#else

+  return [NSBundle.mainBundle URLForResource:@"main" withExtension:@"jsbundle"];

+#endif

+}



@end
```

Now open the `ReactViewController.swift` file and apply the following changes

ReactViewController.swift

```
import UIKit

+import React

+import React_RCTAppDelegate

+import ReactAppDependencyProvider



class ReactViewController: UIViewController {

+  var reactNativeFactory: RCTReactNativeFactory?

+  var reactNativeFactoryDelegate: RCTReactNativeFactoryDelegate?



  override func viewDidLoad() {

    super.viewDidLoad()

+    reactNativeFactoryDelegate = ReactNativeDelegate()

+    reactNativeFactoryDelegate!.dependencyProvider = RCTAppDependencyProvider()

+    reactNativeFactory = RCTReactNativeFactory(delegate: reactNativeFactoryDelegate!)

+    view = reactNativeFactory!.rootViewFactory.view(withModuleName: "HelloWorld")



  }

}



+class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate {

+    override func sourceURL(for bridge: RCTBridge) -> URL? {

+      self.bundleURL()

+    }

+

+    override func bundleURL() -> URL? {

+      #if DEBUG

+      RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")

+      #else

+      Bundle.main.url(forResource: "main", withExtension: "jsbundle")

+      #endif

+    }

+

+}
```

#### Presenting a React Native view in a rootViewController[​](#presenting-a-react-native-view-in-a-rootviewcontroller "Direct link to Presenting a React Native view in a rootViewController")

Finally, we can present our React Native view. To do so, we need a new View Controller that can host a view in which we can load the JS content. We already have the initial `ViewController`, and we can make it present the `ReactViewController`. There are several ways to do so, depending on your app. For this example, we assume that you have a button that presents React Native modally.

* ObjectiveC
* Swift

ViewController.m

```
#import "ViewController.h"

+#import "ReactViewController.h"



@interface ViewController ()



@end



- @implementation ViewController

+@implementation ViewController {

+  ReactViewController *reactViewController;

+}



 - (void)viewDidLoad {

   [super viewDidLoad];

   // Do any additional setup after loading the view.

   self.view.backgroundColor = UIColor.systemBackgroundColor;

+  UIButton *button = [UIButton new];

+  [button setTitle:@"Open React Native" forState:UIControlStateNormal];

+  [button setTitleColor:UIColor.systemBlueColor forState:UIControlStateNormal];

+  [button setTitleColor:UIColor.blueColor forState:UIControlStateHighlighted];

+  [button addTarget:self action:@selector(presentReactNative) forControlEvents:UIControlEventTouchUpInside];

+  [self.view addSubview:button];



+  button.translatesAutoresizingMaskIntoConstraints = NO;

+  [NSLayoutConstraint activateConstraints:@[

+    [button.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],

+    [button.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],

+    [button.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor],

+    [button.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],

+  ]];

 }



+- (void)presentReactNative

+{

+  if (reactViewController == NULL) {

+    reactViewController = [ReactViewController new];

+  }

+  [self presentViewController:reactViewController animated:YES];

+}



@end
```

ViewController.swift

```
import UIKit



class ViewController: UIViewController {



+  var reactViewController: ReactViewController?



  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view.

    self.view.backgroundColor = .systemBackground



+    let button = UIButton()

+    button.setTitle("Open React Native", for: .normal)

+    button.setTitleColor(.systemBlue, for: .normal)

+    button.setTitleColor(.blue, for: .highlighted)

+    button.addAction(UIAction { [weak self] _ in

+      guard let self else { return }

+      if reactViewController == nil {

+       reactViewController = ReactViewController()

+      }

+      present(reactViewController!, animated: true)

+    }, for: .touchUpInside)

+    self.view.addSubview(button)

+

+    button.translatesAutoresizingMaskIntoConstraints = false

+    NSLayoutConstraint.activate([

+      button.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),

+      button.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),

+      button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),

+      button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),

+    ])

  }

}
```

Make sure to disable the Sandbox scripting. To achieve this, in Xcode, click on your app, then on build settings. Filter for script and set the `User Script Sandboxing` to `NO`. This step is needed to properly switch between the Debug and Release version of the [Hermes engine](https://github.com/facebook/hermes/blob/main/README.md) that we ship with React Native.

Finally, make sure to add the `UIViewControllerBasedStatusBarAppearance` key into your `Info.plist` file, with value of `NO`.

## 6. Bootstrapping with SceneDelegate[​](#6-bootstrapping-with-scenedelegate "Direct link to 6. Bootstrapping with SceneDelegate")

Requires React Native 0.88 or later

The `SceneDelegate` APIs described in this section require React Native 0.88 or later. Earlier releases do not provide the `connectionOptions:` overloads of `startReactNative` nor the `SceneDelegate` methods on `RCTLinkingManager`.

If your app uses the UIScene lifecycle (the default for apps created with recent versions of Xcode), React Native bootstrap happens in your app-owned `SceneDelegate`. Your `AppDelegate` stays as the process entry point (`@main`) and handles `UIApplication`-level callbacks such as push notifications.

To bootstrap React Native with SceneDelegate:

1. Declare `UIApplicationSceneManifest` in `Info.plist` and point it at your `SceneDelegate` class.
2. Keep `UIApplicationSupportsMultipleScenes` set to `false`. React Native does not support multi-window / multi-instance apps yet.
3. Subclass `RCTDefaultReactNativeFactoryDelegate`, conform to `UIWindowSceneDelegate`, create an `RCTReactNativeFactory`, and call `startReactNativeWithModuleName:inWindow:connectionOptions:` from `scene:willConnectToSession:options:`.
4. Forward deep links from your `SceneDelegate` to `RCTLinkingManager`.
5. Keep push notifications and other `UIApplicationDelegate` callbacks on your `AppDelegate`.

### Info.plist[​](#infoplist "Direct link to Info.plist")

Add a scene manifest similar to the Community Template. At minimum you need:

XML

```
<key>UIApplicationSceneManifest</key>

<dict>

  <key>UIApplicationSupportsMultipleScenes</key>

  <false/>

  <key>UISceneConfigurations</key>

  <dict>

    <key>UIWindowSceneSessionRoleApplication</key>

    <array>

      <dict>

        <key>UISceneConfigurationName</key>

        <string>Default Configuration</string>

        <key>UISceneDelegateClassName</key>

        <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>

      </dict>

    </array>

  </dict>

</dict>
```

For Objective-C apps, use your SceneDelegate class name directly instead of `$(PRODUCT_MODULE_NAME).SceneDelegate`.

### Create the SceneDelegate[​](#create-the-scenedelegate "Direct link to Create the SceneDelegate")

* ObjectiveC
* Swift

Create `SceneDelegate.h`:

SceneDelegate.h

```
#import <RCTDefaultReactNativeFactoryDelegate.h>

#import <RCTReactNativeFactory.h>

#import <UIKit/UIKit.h>



@interface SceneDelegate : RCTDefaultReactNativeFactoryDelegate <UIWindowSceneDelegate>



@property (nonatomic, strong, nullable) UIWindow *window;

@property (nonatomic, strong, nullable) RCTReactNativeFactory *reactNativeFactory;



@end
```

Create `SceneDelegate.m`:

SceneDelegate.m

```
#import "SceneDelegate.h"



#import <React/RCTBundleURLProvider.h>

#import <React/RCTLinkingManager.h>

#import <ReactAppDependencyProvider/RCTAppDependencyProvider.h>



@implementation SceneDelegate



- (void)scene:(UIScene *)scene

    willConnectToSession:(UISceneSession *)session

                 options:(UISceneConnectionOptions *)connectionOptions

{

  if (![scene isKindOfClass:[UIWindowScene class]]) {

    return;

  }



  self.dependencyProvider = [RCTAppDependencyProvider new];

  self.reactNativeFactory = [[RCTReactNativeFactory alloc] initWithDelegate:self];



  UIWindowScene *windowScene = (UIWindowScene *)scene;

  self.window = [[UIWindow alloc] initWithWindowScene:windowScene];



  [self.reactNativeFactory startReactNativeWithModuleName:@"HelloWorld"

                                                 inWindow:self.window

                                        connectionOptions:connectionOptions];

}



- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts

{

  [RCTLinkingManager scene:scene openURLContexts:URLContexts];

}



- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity

{

  [RCTLinkingManager scene:scene continueUserActivity:userActivity];

}



- (NSURL *)bundleURL

{

#if DEBUG

  return [RCTBundleURLProvider.sharedSettings jsBundleURLForBundleRoot:@"index"];

#else

  return [NSBundle.mainBundle URLForResource:@"main" withExtension:@"jsbundle"];

#endif

}



@end
```

Create `SceneDelegate.swift`:

SceneDelegate.swift

```
import React

import React_RCTAppDelegate

import ReactAppDependencyProvider

import UIKit



class SceneDelegate: RCTDefaultReactNativeFactoryDelegate, UIWindowSceneDelegate {

  var window: UIWindow?

  var reactNativeFactory: RCTReactNativeFactory?



  func scene(

    _ scene: UIScene,

    willConnectTo session: UISceneSession,

    options connectionOptions: UIScene.ConnectionOptions

  ) {

    guard let windowScene = scene as? UIWindowScene else {

      return

    }



    dependencyProvider = RCTAppDependencyProvider()

    reactNativeFactory = RCTReactNativeFactory(delegate: self)

    window = UIWindow(windowScene: windowScene)



    reactNativeFactory?.startReactNative(

      withModuleName: "HelloWorld",

      in: window,

      connectionOptions: connectionOptions

    )

  }



  func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

    RCTLinkingManager.scene(scene, openURLContexts: URLContexts)

  }



  func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {

    RCTLinkingManager.scene(scene, continue: userActivity)

  }



  override func bundleURL() -> URL? {

    #if DEBUG

    RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")

    #else

    Bundle.main.url(forResource: "main", withExtension: "jsbundle")

    #endif

  }

}
```

### Application delegate responsibilities[​](#application-delegate-responsibilities "Direct link to Application delegate responsibilities")

Your `AppDelegate` can remain minimal and only handle callbacks that belong to the application object, such as push notifications:

* ObjectiveC
* Swift

AppDelegate.m

```
#import "AppDelegate.h"



@implementation AppDelegate



- (BOOL)application:(UIApplication *)application

    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

  return YES;

}



@end
```

AppDelegate.swift

```
import UIKit



@main

class AppDelegate: UIResponder, UIApplicationDelegate {

  func application(

    _ application: UIApplication,

    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil

  ) -> Bool {

    true

  }

}
```

note

React Native currently supports a single instance per process, so multiple scenes are not supported. Keep `UIApplicationSupportsMultipleScenes` set to `false`.

`reactNativeFactory` field

Store the `RCTReactNativeFactory` in a property on your `SceneDelegate` so that it is retained for the lifetime of the scene. If it is only held by a local variable, it is deallocated as soon as `scene:willConnectToSession:options:` returns and React Native tears down with it.

## 7. Test your integration[​](#7-test-your-integration "Direct link to 7. Test your integration")

You have completed all the basic steps to integrate React Native with your application. Now we will start the [Metro bundler](https://metrobundler.dev/) to build your TypeScript application code into a bundle. Metro's HTTP server shares the bundle from `localhost` on your developer environment to a simulator or device. This allows for [hot reloading](https://reactnative.dev/blog/2016/03/24/introducing-hot-reloading).

First, you need to create a `metro.config.js` file in the root of your project as follows:

JavaScript

```
const {getDefaultConfig} = require('@react-native/metro-config');

module.exports = getDefaultConfig(__dirname);
```

You can checkout the [`metro.config.js` file](https://github.com/react-native-community/template/blob/main/template/metro.config.js) from the Community template file as reference.

Then, you need to create a `.watchmanconfig` file in the root of your project. The file must contain an empty json object:

```
echo {} > .watchmanconfig
```

Once you have the configuration file in place, you can run the bundler. Run the following command in the root directory of your project:

* npm
* Yarn

```
npm start
```

```
yarn start
```

```
set -e



WITH_ENVIRONMENT="$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh"

REACT_NATIVE_XCODE="$REACT_NATIVE_PATH/scripts/react-native-xcode.sh"



/bin/sh -c "$WITH_ENVIRONMENT $REACT_NATIVE_XCODE"
```

6. Drag and drop the script before the one called `[CP] Embed Pods Frameworks`.

Now, if you build your app for Release, it will work as expected.

## 8. Passing initial props to the React Native view[​](#8-passing-initial-props-to-the-react-native-view "Direct link to 8. Passing initial props to the React Native view")

In some case, you'd like to pass some information from the Native app to JavaScript. For example, you might want to pass the user id of the currently logged user to React Native, together with a token that can be used to retrieve information from a database.

This is possible by using the `initialProperties` parameter of the `view(withModuleName:initialProperty)` overload of the `RCTReactNativeFactory` class. The following steps shows you how to do it.

### Update the App.tsx file to read the initial properties.[​](#update-the-apptsx-file-to-read-the-initial-properties "Direct link to Update the App.tsx file to read the initial properties.")

Open the `App.tsx` file and add the following code:

App.tsx

```
import {

  Colors,

  DebugInstructions,

  Header,

  ReloadInstructions,

} from 'react-native/Libraries/NewAppScreen';



-function App(): React.JSX.Element {

+function App(props): React.JSX.Element {

  const isDarkMode = useColorScheme() === 'dark';



  const backgroundStyle = {

    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,

  };



  return (

    <SafeAreaView style={backgroundStyle}>

      <StatusBar

        barStyle={isDarkMode ? 'light-content' : 'dark-content'}

        backgroundColor={backgroundStyle.backgroundColor}

      />

      <ScrollView

        contentInsetAdjustmentBehavior="automatic"

        style={backgroundStyle}>

        <Header />

-       <View

-         style={{

-           backgroundColor: isDarkMode

-             ? Colors.black

-             : Colors.white,

-           padding: 24,

-         }}>

-         <Text style={styles.title}>Step One</Text>

-         <Text>

-           Edit <Text style={styles.bold}>App.tsx</Text> to

-           change this screen and see your edits.

-         </Text>

-         <Text style={styles.title}>See your changes</Text>

-         <ReloadInstructions />

-         <Text style={styles.title}>Debug</Text>

-         <DebugInstructions />

+         <Text style={styles.title}>UserID: {props.userID}</Text>

+         <Text style={styles.title}>Token: {props.token}</Text>

        </View>

      </ScrollView>

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  title: {

    fontSize: 24,

    fontWeight: '600',

+   marginLeft: 20,

  },

  bold: {

    fontWeight: '700',

  },

});



export default App;
```

These changes will tell React Native that your App component is now accepting some properties. The `RCTreactNativeFactory` will take care of passing them to the component when it's rendered.

### Update the Native code to pass the initial properties to JavaScript.[​](#update-the-native-code-to-pass-the-initial-properties-to-javascript "Direct link to Update the Native code to pass the initial properties to JavaScript.")

#### SceneDelegate bootstrap[​](#scenedelegate-bootstrap "Direct link to SceneDelegate bootstrap")

* ObjectiveC
* Swift

Modify `SceneDelegate.m` to pass initial properties when starting React Native:

SceneDelegate.m

```
  [self.reactNativeFactory startReactNativeWithModuleName:@"HelloWorld"

                                                 inWindow:self.window

+                                       initialProperties:@{

+                                         @"userID": @"12345678",

+                                         @"token": @"secretToken"

+                                       }

                                        connectionOptions:connectionOptions];
```

Modify `SceneDelegate.swift` to pass initial properties when starting React Native:

SceneDelegate.swift

```
    reactNativeFactory?.startReactNative(

      withModuleName: "HelloWorld",

      in: window,

+     initialProperties: [

+       "userID": "12345678",

+       "token": "secretToken"

+     ],

      connectionOptions: connectionOptions

    )
```

#### Embedded view controller[​](#embedded-view-controller "Direct link to Embedded view controller")

* ObjectiveC
* Swift

Modify the `ReactViewController.mm` to pass the initial properties to JavaScript.

ReactViewController.mm

```
 - (void)viewDidLoad {

   [super viewDidLoad];

   // Do any additional setup after loading the view.



   _factoryDelegate = [ReactNativeFactoryDelegate new];

   _factoryDelegate.dependencyProvider = [RCTAppDependencyProvider new];

   _factory = [[RCTReactNativeFactory alloc] initWithDelegate:_factoryDelegate];

-  self.view = [_factory.rootViewFactory viewWithModuleName:@"HelloWorld"];

+  self.view = [_factory.rootViewFactory viewWithModuleName:@"HelloWorld" initialProperties:@{

+    @"userID": @"12345678",

+    @"token": @"secretToken"

+  }];

}
```

Modify the `ReactViewController.swift` to pass the initial properties to the React Native view.

ReactViewController.swift

```
  override func viewDidLoad() {

    super.viewDidLoad()

    reactNativeFactoryDelegate = ReactNativeDelegate()

    reactNativeFactoryDelegate!.dependencyProvider = RCTAppDependencyProvider()

    reactNativeFactory = RCTReactNativeFactory(delegate: reactNativeFactoryDelegate!)

-   view = reactNativeFactory!.rootViewFactory.view(withModuleName: "HelloWorld")

+   view = reactNativeFactory!.rootViewFactory.view(withModuleName: "HelloWorld" initialProperties: [

+     "userID": "12345678",

+     "token": "secretToken"

+])



  }

}
```

3. Run your app once again. You should see the following screen after you present the `ReactViewController`:

## Now what?[​](#now-what "Direct link to Now what?")

At this point you can continue developing your app as usual. Refer to our [debugging](/docs/next/debugging) and [deployment](/docs/next/running-on-device) docs to learn more about working with React Native.

----
url: https://reactnative.dev/docs/next/safeareaview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/safeareaview)** (0.87).

Version: Next

Deprecated

Use [react-native-safe-area-context](https://github.com/AppAndFlow/react-native-safe-area-context) instead.

The purpose of `SafeAreaView` is to render content within the safe area boundaries of a device. It is currently only applicable to iOS devices with iOS version 11 or later.

`SafeAreaView` renders nested content and automatically applies padding to reflect the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. Moreover, and most importantly, Safe Area's paddings reflect the physical limitation of the screen, such as rounded corners or camera notches (i.e. the sensor housing area on iPhone 13).

## Example[​](#example "Direct link to Example")

To use, wrap your top level view with a `SafeAreaView` with a `flex: 1` style applied to it. You may also want to use a background color that matches your application's design.

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

note

As padding is used to implement the behavior of the component, padding rules in styles applied to a `SafeAreaView` will be ignored and can cause different results depending on the platform. See [#22211](https://github.com/react/react-native/issues/22211) for details.

* [Example](#example)
* [Props](#props)
  * [View Props](#view-props)

----
url: https://reactnative.dev/docs/vibration
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Vibrates the device.

## Example[​](#example "Direct link to Example")

info

Android apps should request the `android.permission.VIBRATE` permission by adding `<uses-permission android:name="android.permission.VIBRATE"/>` to `AndroidManifest.xml`.

note

The Vibration API is implemented as a `AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)` call on iOS.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `cancel()`[​](#cancel "Direct link to cancel")

React TSX

```
static cancel();
```

Call this to stop vibrating after having invoked `vibrate()` with repetition enabled.

***

### `vibrate()`[​](#vibrate "Direct link to vibrate")

React TSX

```
static vibrate(

  pattern?: number | number[],

  repeat?: boolean

);
```

Triggers a vibration with a fixed duration.

**On Android,** the vibration duration defaults to 400 milliseconds, and an arbitrary vibration duration can be specified by passing a number as the value for the `pattern` argument. **On iOS,** the vibration duration is fixed at roughly 400 milliseconds.

The `vibrate()` method can take a `pattern` argument with an array of numbers that represent time in milliseconds. You may set `repeat` to true to run through the vibration pattern in a loop until `cancel()` is called.

**On Android,** the odd indices of the `pattern` array represent the vibration duration, while the even ones represent the separation time. **On iOS,** the numbers in the `pattern` array represent the separation time, as the vibration duration is fixed.

**Parameters:**

| Name    | Type                             | Default | Description                                                                                     |
| ------- | -------------------------------- | ------- | ----------------------------------------------------------------------------------------------- |
| pattern | numberAndroid***array of numbers | `400`   | Vibration duration in milliseconds.***Vibration pattern as an array of numbers in milliseconds. |
| repeat  | boolean                          | `false` | Repeat vibration pattern until `cancel()`.                                                      |

* [Example](#example)

* [Methods](#methods)

  * [`cancel()`](#cancel)
  * [`vibrate()`](#vibrate)

----
url: https://reactnative.dev/docs/next/legacy/native-modules-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/legacy/native-modules-android)** (0.87).

Version: Next

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

Welcome to Native Modules for Android. Please start by reading the [Native Modules Intro](/docs/next/legacy/native-modules-intro) for an intro to what native modules are.

```
package com.your-apps-package-name; // replace your-apps-package-name with your app’s package name

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.bridge.ReactContext;

import com.facebook.react.bridge.ReactContextBaseJavaModule;

import com.facebook.react.bridge.ReactMethod;

import java.util.Map;

import java.util.HashMap;



public class CalendarModule extends ReactContextBaseJavaModule {

   CalendarModule(ReactApplicationContext context) {

       super(context);

   }

}
```

Kotlin

```
package com.your-apps-package-name; // replace your-apps-package-name with your app’s package name

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.bridge.ReactContext

import com.facebook.react.bridge.ReactContextBaseJavaModule

import com.facebook.react.bridge.ReactMethod



class CalendarModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {...}
```

```
// add to CalendarModule.java

@Override

public String getName() {

   return "CalendarModule";

}
```

Kotlin

```
// add to CalendarModule.kt

override fun getName() = "CalendarModule"
```

The native module can then be accessed in JS like this:

React TSX

```
const {CalendarModule} = ReactNative.NativeModules;
```

### Export a Native Method to JavaScript[​](#export-a-native-method-to-javascript "Direct link to Export a Native Method to JavaScript")

Next you will need to add a method to your native module that will create calendar events and can be invoked in JavaScript. All native module methods meant to be invoked from JavaScript must be annotated with `@ReactMethod`.

Set up a method `createCalendarEvent()` for `CalendarModule` that can be invoked in JS through `CalendarModule.createCalendarEvent()`. For now, the method will take in a name and location as strings. Argument type options will be covered shortly.

* Java
* Kotlin

Java

```
@ReactMethod

public void createCalendarEvent(String name, String location) {

}
```

Kotlin

```
@ReactMethod fun createCalendarEvent(name: String, location: String) {}
```

Add a debug log in the method to confirm it has been invoked when you call it from your application. Below is an example of how you can import and use the [Log](https://developer.android.com/reference/android/util/Log) class from the Android util package:

* Java
* Kotlin

Java

```
import android.util.Log;



@ReactMethod

public void createCalendarEvent(String name, String location) {

   Log.d("CalendarModule", "Create event called with name: " + name

   + " and location: " + location);

}
```

Kotlin

```
import android.util.Log



@ReactMethod

fun createCalendarEvent(name: String, location: String) {

    Log.d("CalendarModule", "Create event called with name: $name and location: $location")

}
```

Once you finish implementing the native module and hook it up in JavaScript, you can follow [these steps](https://developer.android.com/studio/debug/am-logcat.html) to view the logs from your app.

### Synchronous Methods[​](#synchronous-methods "Direct link to Synchronous Methods")

You can pass `isBlockingSynchronousMethod = true` to a native method to mark it as a synchronous method.

* Java
* Kotlin

Java

```
@ReactMethod(isBlockingSynchronousMethod = true)
```

Kotlin

```
@ReactMethod(isBlockingSynchronousMethod = true)
```

```
package com.your-app-name; // replace your-app-name with your app’s name

import com.facebook.react.ReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.uimanager.ViewManager;



import java.util.ArrayList;

import java.util.Collections;

import java.util.List;



public class MyAppPackage implements ReactPackage {



   @Override

   public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {

       return Collections.emptyList();

   }



   @Override

   public List<NativeModule> createNativeModules(

           ReactApplicationContext reactContext) {

       List<NativeModule> modules = new ArrayList<>();



       modules.add(new CalendarModule(reactContext));



       return modules;

   }



}
```

Kotlin

```
package com.your-app-name // replace your-app-name with your app’s name



import android.view.View

import com.facebook.react.ReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.uimanager.ReactShadowNode

import com.facebook.react.uimanager.ViewManager



class MyAppPackage : ReactPackage {



    override fun createViewManagers(

        reactContext: ReactApplicationContext

    ): MutableList<ViewManager<View, ReactShadowNode<*>>> = mutableListOf()



    override fun createNativeModules(

        reactContext: ReactApplicationContext

    ): MutableList<NativeModule> = listOf(CalendarModule(reactContext)).toMutableList()

}
```

```
@Override

protected List<ReactPackage> getPackages() {

    List<ReactPackage> packages = new PackageList(this).getPackages();

    // Packages that cannot be autolinked yet can be added manually here, for example:

    // packages.add(new MyReactNativePackage());

    packages.add(new MyAppPackage());

    return packages;

}
```

Kotlin

```
override fun getPackages(): List<ReactPackage> =

    PackageList(this).packages.apply {

        // Packages that cannot be autolinked yet can be added manually here, for example:

        // add(MyReactNativePackage())

        add(MyAppPackage())

    }
```

You have now successfully registered your native module for Android!

### Test What You Have Built[​](#test-what-you-have-built "Direct link to Test What You Have Built")

At this point, you have set up the basic scaffolding for your native module in Android. Test that out by accessing the native module and invoking its exported method in JavaScript.

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.

React TSX

```
import {NativeModules, Button} from 'react-native';



const NewModuleButton = () => {

  const onPress = () => {

    console.log('We will invoke the native module here!');

  };



  return (

    <Button

      title="Click to invoke your native module!"

      color="#841584"

      onPress={onPress}

    />

  );

};



export default NewModuleButton;
```

In order to access your native module from JavaScript you need to first import `NativeModules` from React Native:

React TSX

```
import {NativeModules} from 'react-native';
```

You can then access the `CalendarModule` native module off of `NativeModules`.

React 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`:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent('testName', 'testLocation');

};
```

The final step is to rebuild the React Native app so that you can have the latest native code (with your new native module!) available. In your command line, where the react native application is located, run the following:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

```
/**

* This exposes the native CalendarModule module as a JS module. This has a

* function 'createCalendarEvent' which takes the following parameters:



* 1. String name: A string representing the name of the event

* 2. String location: A string representing the location of the event

*/

import {NativeModules} from 'react-native';

const {CalendarModule} = NativeModules;

export default CalendarModule;
```

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:

React TSX

```
/**

 * This exposes the native CalendarModule module as a JS module. This has a

 * function 'createCalendarEvent' which takes the following parameters:

 *

 * 1. String name: A string representing the name of the event

 * 2. String location: A string representing the location of the event

 */

import {NativeModules} from 'react-native';

const {CalendarModule} = NativeModules;

interface CalendarInterface {

  createCalendarEvent(name: string, location: string): void;

}

export default CalendarModule as CalendarInterface;
```

In your other JavaScript files you can access the native module and invoke its method like this:

React TSX

```
import CalendarModule from './CalendarModule';

CalendarModule.createCalendarEvent('foo', 'bar');
```

note

This assumes that the place you are importing `CalendarModule` is in the same hierarchy as `CalendarModule.js`. Please update the relative import as necessary.

### Argument Types[​](#argument-types "Direct link to Argument Types")

When a native module method is invoked in JavaScript, React Native converts the arguments from JS objects to their Java/Kotlin object analogues. So for example, if your Java Native Module method accepts a double, in JS you need to call the method with a number. React Native will handle the conversion for you. Below is a list of the argument types supported for native module methods and the JavaScript equivalents they map to.

| Java          | Kotlin        | JavaScript |
| ------------- | ------------- | ---------- |
| Boolean       | Boolean       | ?boolean   |
| boolean       |               | boolean    |
| Double        | Double        | ?number    |
| double        |               | number     |
| String        | String        | string     |
| Callback      | Callback      | Function   |
| Promise       | Promise       | Promise    |
| ReadableMap   | ReadableMap   | Object     |
| ReadableArray | ReadableArray | Array      |

```
    String dateFormat = "yyyy-MM-dd";

    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

    Calendar eStartDate = Calendar.getInstance();

    try {

        eStartDate.setTime(sdf.parse(startDate));

    }
```

Kotlin

```
    val dateFormat = "yyyy-MM-dd"

    val sdf = SimpleDateFormat(dateFormat, Locale.US)

    val eStartDate = Calendar.getInstance()

    try {

        sdf.parse(startDate)?.let {

            eStartDate.time = it

        }

    }
```

### Exporting Constants[​](#exporting-constants "Direct link to Exporting Constants")

A native module can export constants by implementing the native method `getConstants()`, which is available in JS. Below you will implement `getConstants()` and return a Map that contains a `DEFAULT_EVENT_NAME` constant you can access in JavaScript:

* Java
* Kotlin

Java

```
@Override

public Map<String, Object> getConstants() {

   final Map<String, Object> constants = new HashMap<>();

   constants.put("DEFAULT_EVENT_NAME", "New Event");

   return constants;

}
```

Kotlin

```
override fun getConstants(): MutableMap<String, Any> =

    hashMapOf("DEFAULT_EVENT_NAME" to "New Event")
```

The constant can then be accessed by invoking `getConstants` on the native module in JS:

React TSX

```
const {DEFAULT_EVENT_NAME} = CalendarModule.getConstants();

console.log(DEFAULT_EVENT_NAME);
```

```
import com.facebook.react.bridge.Callback;



@ReactMethod

public void createCalendarEvent(String name, String location, Callback callBack) {

}
```

Kotlin

```
import com.facebook.react.bridge.Callback



@ReactMethod fun createCalendarEvent(name: String, location: String, callback: Callback) {}
```

You can invoke the callback in your Java/Kotlin method, providing whatever data you want to pass to JavaScript. Please note that you can only pass serializable data from native code to JavaScript. If you need to pass back a native object you can use `WriteableMaps`, if you need to use a collection use `WritableArrays`. It is also important to highlight that the callback is not invoked immediately after the native function completes. Below the ID of an event created in an earlier call is passed to the callback.

* Java
* Kotlin

Java

```
  @ReactMethod

   public void createCalendarEvent(String name, String location, Callback callBack) {

       Integer eventId = ...

       callBack.invoke(eventId);

   }
```

Kotlin

```
  @ReactMethod

  fun createCalendarEvent(name: String, location: String, callback: Callback) {

      val eventId = ...

      callback.invoke(eventId)

  }
```

This method could then be accessed in JavaScript using:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent(

    'Party',

    'My House',

    eventId => {

      console.log(`Created a new event with id ${eventId}`);

    },

  );

};
```

Another important detail to note is that a native module method can only invoke one callback, one time. This means that you can either call a success callback or a failure callback, but not both, and each callback can only be invoked at most one time. A native module can, however, store the callback and invoke it later.

There are two approaches to error handling with callbacks. The first is to follow Node’s convention and treat the first argument passed to the callback as an error object.

* Java
* Kotlin

Java

```
  @ReactMethod

   public void createCalendarEvent(String name, String location, Callback callBack) {

       Integer eventId = ...

       callBack.invoke(null, eventId);

   }
```

Kotlin

```
  @ReactMethod

  fun createCalendarEvent(name: String, location: String, callback: Callback) {

      val eventId = ...

      callback.invoke(null, eventId)

  }
```

In JavaScript, you can then check the first argument to see if an error was passed through:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent(

    'testName',

    'testLocation',

    (error, eventId) => {

      if (error) {

        console.error(`Error found! ${error}`);

      }

      console.log(`event id ${eventId} returned`);

    },

  );

};
```

Another option is to use an onSuccess and onFailure callback:

* Java
* Kotlin

Java

```
@ReactMethod

public void createCalendarEvent(String name, String location, Callback myFailureCallback, Callback mySuccessCallback) {

}
```

Kotlin

```
@ReactMethod

  fun createCalendarEvent(

      name: String,

      location: String,

      myFailureCallback: Callback,

      mySuccessCallback: Callback

  ) {}
```

Then in JavaScript you can add a separate callback for error and success responses:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent(

    'testName',

    'testLocation',

    error => {

      console.error(`Error found! ${error}`);

    },

    eventId => {

      console.log(`event id ${eventId} returned`);

    },

  );

};
```

### Promises[​](#promises "Direct link to Promises")

Native modules can also fulfill a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), which can simplify your JavaScript, especially when using ES2016's [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) syntax. When the last parameter of a native module Java/Kotlin method is a Promise, its corresponding JS method will return a JS Promise object.

Refactoring the above code to use a promise instead of callbacks looks like this:

* Java
* Kotlin

Java

```
import com.facebook.react.bridge.Promise;



@ReactMethod

public void createCalendarEvent(String name, String location, Promise promise) {

    try {

        Integer eventId = ...

        promise.resolve(eventId);

    } catch(Exception e) {

        promise.reject("Create Event Error", e);

    }

}
```

Kotlin

```
import com.facebook.react.bridge.Promise



@ReactMethod

fun createCalendarEvent(name: String, location: String, promise: Promise) {

    try {

        val eventId = ...

        promise.resolve(eventId)

    } catch (e: Throwable) {

        promise.reject("Create Event Error", e)

    }

}
```

note

Similar to callbacks, a native module method can either reject or resolve a promise (but not both) and can do so at most once. This means that you can either call a success callback or a failure callback, but not both, and each callback can only be invoked at most one time. A native module can, however, store the callback and invoke it later.

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:

React TSX

```
const onSubmit = async () => {

  try {

    const eventId = await CalendarModule.createCalendarEvent(

      'Party',

      'My House',

    );

    console.log(`Created a new event with id ${eventId}`);

  } catch (e) {

    console.error(e);

  }

};
```

The reject method takes different combinations of the following arguments:

* Java
* Kotlin

Java

```
String code, String message, WritableMap userInfo, Throwable throwable
```

Kotlin

```
code: String, message: String, userInfo: WritableMap, throwable: Throwable
```

For more detail, you can find the `Promise.java` interface [here](https://github.com/react/react-native/blob/main/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Promise.kt). If `userInfo` is not provided, ReactNative will set it to null. For the rest of the parameters React Native will use a default value. The `message` argument provides the error `message` shown at the top of an error call stack. Below is an example of the error message shown in JavaScript from the following reject call in Java/Kotlin.

Java/Kotlin reject call:

* Java
* Kotlin

Java

```
promise.reject("Create Event error", "Error parsing date", e);
```

Kotlin

```
promise.reject("Create Event error", "Error parsing date", e)
```

```
...

import com.facebook.react.modules.core.DeviceEventManagerModule;

import com.facebook.react.bridge.WritableMap;

import com.facebook.react.bridge.Arguments;

...

private void sendEvent(ReactContext reactContext,

                      String eventName,

                      @Nullable WritableMap params) {

 reactContext

     .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)

     .emit(eventName, params);

}



private int listenerCount = 0;



@ReactMethod

public void addListener(String eventName) {

  if (listenerCount == 0) {

    // Set up any upstream listeners or background tasks as necessary

  }



  listenerCount += 1;

}



@ReactMethod

public void removeListeners(Integer count) {

  listenerCount -= count;

  if (listenerCount == 0) {

    // Remove upstream listeners, stop unnecessary background tasks

  }

}

...

WritableMap params = Arguments.createMap();

params.putString("eventProperty", "someValue");

...

sendEvent(reactContext, "EventReminder", params);
```

Kotlin

```
...

import com.facebook.react.bridge.WritableMap

import com.facebook.react.bridge.Arguments

import com.facebook.react.modules.core.DeviceEventManagerModule

...



private fun sendEvent(reactContext: ReactContext, eventName: String, params: WritableMap?) {

    reactContext

      .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)

      .emit(eventName, params)

}



private var listenerCount = 0



@ReactMethod

fun addListener(eventName: String) {

  if (listenerCount == 0) {

    // Set up any upstream listeners or background tasks as necessary

  }



  listenerCount += 1

}



@ReactMethod

fun removeListeners(count: Int) {

  listenerCount -= count

  if (listenerCount == 0) {

    // Remove upstream listeners, stop unnecessary background tasks

  }

}

...

val params = Arguments.createMap().apply {

    putString("eventProperty", "someValue")

}

...

sendEvent(reactContext, "EventReminder", params)
```

JavaScript modules can then register to receive events by `addListener` on the [NativeEventEmitter](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/EventEmitter/NativeEventEmitter.js) class.

React TSX

```
import {NativeEventEmitter, NativeModules} from 'react-native';

...

useEffect(() => {

    const eventEmitter = new NativeEventEmitter(NativeModules.ToastExample);

    let eventListener = eventEmitter.addListener('EventReminder', event => {

      console.log(event.eventProperty) // "someValue"

    });



    // Removes the listener once unmounted

    return () => {

      eventListener.remove();

    };

  }, []);
```

### Getting Activity Result from startActivityForResult[​](#getting-activity-result-from-startactivityforresult "Direct link to Getting Activity Result from startActivityForResult")

You'll need to listen to `onActivityResult` if you want to get results from an activity you started with `startActivityForResult`. To do this, you must extend `BaseActivityEventListener` or implement `ActivityEventListener`. The former is preferred as it is more resilient to API changes. Then, you need to register the listener in the module's constructor like so:

* Java
* Kotlin

Java

```
reactContext.addActivityEventListener(mActivityResultListener);
```

Kotlin

```
reactContext.addActivityEventListener(mActivityResultListener);
```

Now you can listen to `onActivityResult` by implementing the following method:

* Java
* Kotlin

Java

```
@Override

public void onActivityResult(

 final Activity activity,

 final int requestCode,

 final int resultCode,

 final Intent intent) {

 // Your logic here

}
```

Kotlin

```
override fun onActivityResult(

    activity: Activity?,

    requestCode: Int,

    resultCode: Int,

    intent: Intent?

) {

    // Your logic here

}
```

Let's implement a basic image picker to demonstrate this. The image picker will expose the method `pickImage` to JavaScript, which will return the path of the image when called.

* Java
* Kotlin

Kotlin

```
public class ImagePickerModule extends ReactContextBaseJavaModule {



  private static final int IMAGE_PICKER_REQUEST = 1;

  private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST";

  private static final String E_PICKER_CANCELLED = "E_PICKER_CANCELLED";

  private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER";

  private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND";



  private Promise mPickerPromise;



  private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {



    @Override

    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) {

      if (requestCode == IMAGE_PICKER_REQUEST) {

        if (mPickerPromise != null) {

          if (resultCode == Activity.RESULT_CANCELED) {

            mPickerPromise.reject(E_PICKER_CANCELLED, "Image picker was cancelled");

          } else if (resultCode == Activity.RESULT_OK) {

            Uri uri = intent.getData();



            if (uri == null) {

              mPickerPromise.reject(E_NO_IMAGE_DATA_FOUND, "No image data found");

            } else {

              mPickerPromise.resolve(uri.toString());

            }

          }



          mPickerPromise = null;

        }

      }

    }

  };



  ImagePickerModule(ReactApplicationContext reactContext) {

    super(reactContext);



    // Add the listener for `onActivityResult`

    reactContext.addActivityEventListener(mActivityEventListener);

  }



  @Override

  public String getName() {

    return "ImagePickerModule";

  }



  @ReactMethod

  public void pickImage(final Promise promise) {

    Activity currentActivity = getCurrentActivity();



    if (currentActivity == null) {

      promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");

      return;

    }



    // Store the promise to resolve/reject when picker returns data

    mPickerPromise = promise;



    try {

      final Intent galleryIntent = new Intent(Intent.ACTION_PICK);



      galleryIntent.setType("image/*");



      final Intent chooserIntent = Intent.createChooser(galleryIntent, "Pick an image");



      currentActivity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST);

    } catch (Exception e) {

      mPickerPromise.reject(E_FAILED_TO_SHOW_PICKER, e);

      mPickerPromise = null;

    }

  }

}
```

Kotlin

```
class ImagePickerModule(reactContext: ReactApplicationContext) :

    ReactContextBaseJavaModule(reactContext) {



    private var pickerPromise: Promise? = null



    private val activityEventListener =

        object : BaseActivityEventListener() {

            override fun onActivityResult(

                activity: Activity?,

                requestCode: Int,

                resultCode: Int,

                intent: Intent?

            ) {

                if (requestCode == IMAGE_PICKER_REQUEST) {

                    pickerPromise?.let { promise ->

                        when (resultCode) {

                            Activity.RESULT_CANCELED ->

                                promise.reject(E_PICKER_CANCELLED, "Image picker was cancelled")

                            Activity.RESULT_OK -> {

                                val uri = intent?.data



                                uri?.let { promise.resolve(uri.toString())}

                                    ?: promise.reject(E_NO_IMAGE_DATA_FOUND, "No image data found")

                            }

                        }



                        pickerPromise = null

                    }

                }

            }

        }



    init {

        reactContext.addActivityEventListener(activityEventListener)

    }



    override fun getName() = "ImagePickerModule"



    @ReactMethod

    fun pickImage(promise: Promise) {

        val activity = currentActivity



        if (activity == null) {

            promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist")

            return

        }



        pickerPromise = promise



        try {

            val galleryIntent = Intent(Intent.ACTION_PICK).apply { type = "image\/*" }



            val chooserIntent = Intent.createChooser(galleryIntent, "Pick an image")



            activity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST)

        } catch (t: Throwable) {

            pickerPromise?.reject(E_FAILED_TO_SHOW_PICKER, t)

            pickerPromise = null

        }

    }



    companion object {

        const val IMAGE_PICKER_REQUEST = 1

        const val E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST"

        const val E_PICKER_CANCELLED = "E_PICKER_CANCELLED"

        const val E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER"

        const val E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND"

    }

}
```

### Listening to Lifecycle Events[​](#listening-to-lifecycle-events "Direct link to Listening to Lifecycle Events")

Listening to the activity's LifeCycle events such as `onResume`, `onPause` etc. is very similar to how `ActivityEventListener` was implemented. The module must implement `LifecycleEventListener`. Then, you need to register a listener in the module's constructor like so:

* Java
* Kotlin

Java

```
reactContext.addLifecycleEventListener(this);
```

Kotlin

```
reactContext.addLifecycleEventListener(this)
```

Now you can listen to the activity's LifeCycle events by implementing the following methods:

* Java
* Kotlin

Java

```
@Override

public void onHostResume() {

   // Activity `onResume`

}

@Override

public void onHostPause() {

   // Activity `onPause`

}

@Override

public void onHostDestroy() {

   // Activity `onDestroy`

}
```

Kotlin

```
override fun onHostResume() {

    // Activity `onResume`

}



override fun onHostPause() {

    // Activity `onPause`

}



override fun onHostDestroy() {

    // Activity `onDestroy`

}
```

----
url: https://reactnative.dev/docs/next/profiling
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/profiling)** (0.87).

Version: Next

Profiling is the process of analyzing an app's performance, resource usage, and behavior to identify potential bottlenecks or inefficiencies. It's worth making use of profiling tools to ensure your app works smoothly across different devices and conditions.

For iOS, Instruments is an invaluable tool, and on Android you should learn to use the [Android Studio Profiler](/docs/next/profiling#profiling-android-ui-performance-with-system-tracing).

But first, [**make sure that Development Mode is OFF!**](/docs/next/performance#running-in-development-mode-devtrue).

----
url: https://reactnative.dev/docs/next/timepickerandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/timepickerandroid)** (0.87).

Version: Next

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=timepicker) instead.

----
url: https://reactnative.dev/docs/props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Most components can be customized when they are created, with different parameters. These created parameters are called `props`, short for properties.

For example, one basic React Native component is the `Image`. When you create an image, you can use a prop named `source` to control what image it shows.

Notice the braces surrounding `{pic}` - these embed the variable `pic` into JSX. You can put any JavaScript expression inside braces in JSX.

Your own components can also use `props`. This lets you make a single component that is used in many different places in your app, with slightly different properties in each place by referring to `props` in your `render` function. Here's an example:

* TypeScript
* JavaScript

Using `name` as a prop lets us customize the `Greeting` component, so we can reuse that component for each of our greetings. This example also uses the `Greeting` component in JSX, similar to the [Core Components](/docs/intro-react-native-components). The power to do this is what makes React so cool - if you find yourself wishing that you had a different set of UI primitives to work with, you can invent new ones.

The other new thing going on here is the [`View`](/docs/view) component. A [`View`](/docs/view) is useful as a container for other components, to help control style and layout.

With `props` and the basic [`Text`](/docs/text), [`Image`](/docs/image), and [`View`](/docs/view) components, you can build a wide variety of static screens. To learn how to make your app change over time, you need to [learn about State](/docs/state).

----
url: https://reactnative.dev/docs/next/flexbox
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/flexbox)** (0.87).

Version: Next

A component can specify the layout of its children using the Flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes.

You will normally use a combination of `flexDirection`, `alignItems`, and `justifyContent` to achieve the right layout.

caution

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with `flexDirection` defaulting to `column` instead of `row`, `alignContent` defaulting to `flex-start` instead of `stretch`, `flexShrink` defaulting to `0` instead of `1`, the `flex` parameter only supporting a single number.

## Flex[​](#flex "Direct link to Flex")

[`flex`](/docs/next/layout-props#flex) will define how your items are going to **“fill”** over the available space along your main axis. Space will be divided according to each element's flex property.

In the following example, the red, orange, and green views are all children in the container view that has `flex: 1` set. The red view uses `flex: 1` , the orange view uses `flex: 2`, and the green view uses `flex: 3` . **1+2+3 = 6**, which means that the red view will get `1/6` of the space, the orange `2/6` of the space, and the green `3/6` of the space.

## Flex Direction[​](#flex-direction "Direct link to Flex Direction")

[`flexDirection`](/docs/next/layout-props#flexdirection) controls the direction in which the children of a node are laid out. This is also referred to as the main axis. The cross axis is the axis perpendicular to the main axis, or the axis which the wrapping lines are laid out in.

Layout [`direction`](/docs/next/layout-props#direction) specifies the direction in which children and text in a hierarchy should be laid out. Layout direction also affects what edge `start` and `end` refer to. By default, React Native lays out with LTR layout direction. In this mode `start` refers to left and `end` refers to right.

* `LTR` (**default value**) Text and children are laid out from left to right. Margin and padding applied to the start of an element are applied on the left side.

* `RTL` Text and children are laid out from right to left. Margin and padding applied to the start of an element are applied on the right side.

- TypeScript
- JavaScript

## Justify Content[​](#justify-content "Direct link to Justify Content")

[`justifyContent`](/docs/next/layout-props#justifycontent) describes how to align children within the main axis of their container. For example, you can use this property to center a child horizontally within a container with `flexDirection` set to `row` or vertically within a container with `flexDirection` set to `column`.

[`alignItems`](/docs/next/layout-props#alignitems) describes how to align children along the cross axis of their container. It is very similar to `justifyContent` but instead of applying to the main axis, `alignItems` applies to the cross axis.

[`alignSelf`](/docs/next/layout-props#alignself) has the same options and effect as `alignItems` but instead of affecting the children within a container, you can apply this property to a single child to change its alignment within its parent. `alignSelf` overrides any option set by the parent with `alignItems`.

* TypeScript
* JavaScript

## Align Content[​](#align-content "Direct link to Align Content")

[alignContent](/docs/next/layout-props#aligncontent) defines the distribution of lines along the cross-axis. This only has effect when items are wrapped to multiple lines using `flexWrap`.

The [`flexWrap`](/docs/next/layout-props#flexwrap) property is set on containers and it controls what happens when children overflow the size of the container along the main axis. By default, children are forced into a single line (which can shrink elements). If wrapping is allowed, items are wrapped into multiple lines along the main axis if needed.

When wrapping lines, `alignContent` can be used to specify how the lines are placed in the container. Learn more [here](https://www.yogalayout.dev/docs/styling/flex-wrap).

* TypeScript
* JavaScript

## Flex Basis, Grow, and Shrink[​](#flex-basis-grow-and-shrink "Direct link to Flex Basis, Grow, and Shrink")

* [`flexBasis`](/docs/next/layout-props#flexbasis) is an axis-independent way of providing the default size of an item along the main axis. Setting the `flexBasis` of a child is similar to setting the `width` of that child if its parent is a container with `flexDirection: row` or setting the `height` of a child if its parent is a container with `flexDirection: column`. The `flexBasis` of an item is the default size of that item, the size of the item before any `flexGrow` and `flexShrink` calculations are performed.

* [`flexGrow`](/docs/next/layout-props#flexgrow) describes how much space within a container should be distributed among its children along the main axis. After laying out its children, a container will distribute any remaining space according to the flex grow values specified by its children.

  `flexGrow` accepts any floating point value >= 0, with 0 being the default value. A container will distribute any remaining space among its children weighted by the children’s `flexGrow` values.

* [`flexShrink`](/docs/next/layout-props#flexshrink) describes how to shrink children along the main axis in the case in which the total size of the children overflows the size of the container on the main axis. `flexShrink` is very similar to `flexGrow` and can be thought of in the same way if any overflowing size is considered to be negative remaining space. These two properties also work well together by allowing children to grow and shrink as needed.

  `flexShrink` accepts any floating point value >= 0, with 0 being the default value (on the web, the default is 1). A container will shrink its children weighted by the children’s `flexShrink` values.

You can learn more [here](https://www.yogalayout.dev/docs/styling/flex-basis-grow-shrink).

* TypeScript
* JavaScript

## Row Gap, Column Gap and Gap[​](#row-gap-column-gap-and-gap "Direct link to Row Gap, Column Gap and Gap")

* [`rowGap`](/docs/next/layout-props#rowgap) sets the size of the gap (gutter) between an element's rows.

* [`columnGap`](/docs/next/layout-props#columngap) sets the size of the gap (gutter) between an element's columns.

* [`gap`](/docs/next/layout-props#gap) sets the size of the gap (gutter) between rows and columns. It is a shorthand for `rowGap` and `columnGap`.

The `position` type of an element defines how it is positioned relative to either itself, its parent, or its [containing block](/docs/next/flexbox#the-containing-block).

We've covered the basics, but there are many other styles you may need for layouts. The full list of props that control layout is documented [here](/docs/next/layout-props).

----
url: https://reactnative.dev/docs/next/i18nmanager
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/i18nmanager)** (0.87).

Version: Next

```
static isRTL: boolean;
```

A boolean value indicating whether the app is currently in RTL layout mode.

The value of `isRTL` is determined by the following logic:

* If `forceRTL` is `true`, `isRTL` returns `true`

* If `allowRTL` is `false`, `isRTL` returns `false`

* Otherwise, `isRTL` will be `true` given the following:

  * **iOS:**

    * The user-preferred language on the device is an RTL language
    * The application-defined localizations include the user-chosen language (as defined in the Xcode project file (`knownRegions = (...)`)

  * **Android:**

    * The user-preferred language on the device is an RTL language
    * The application's `AndroidManifest.xml` defines `android:supportsRTL="true"` on the `<application>` element

### `doLeftAndRightSwapInRTL`[​](#doleftandrightswapinrtl "Direct link to doleftandrightswapinrtl")

TypeScript

```
static doLeftAndRightSwapInRTL: boolean;
```

A boolean value indicating whether left and right style properties should be automatically swapped when in RTL mode. When enabled, left becomes right and right becomes left in RTL layouts.

## Methods[​](#methods "Direct link to Methods")

### `allowRTL()`[​](#allowrtl "Direct link to allowrtl")

TypeScript

```
static allowRTL: (allowRTL: boolean) => void;
```

```
static forceRTL: (forced: boolean) => void;
```

```
static swapLeftAndRightInRTL: (swapLeftAndRight: boolean) => void;
```

----
url: https://reactnative.dev/docs/next/the-new-architecture/using-codegen
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/using-codegen)** (0.87).

Version: Next

```
npx @react-native-community/cli@latest init SampleApp --version "latest"
```

**Codegen** is used to generate the glue-code for your custom modules or components. See the guides for Turbo Native Modules and Fabric Native Components for more details on how to create them.

## Configuring **Codegen**[​](#configuring-codegen "Direct link to configuring-codegen")

**Codegen** can be configured in your app by modifying the `package.json` file. **Codegen** is controlled by a custom field called `codegenConfig`.

package.json

```
  "codegenConfig": {

    "name": "<SpecName>",

    "type": "<types>",

    "jsSrcsDir": "<source_dir>",

    "android": {

      "javaPackageName": "<java.package.name>"

    },

    "ios": {

      "modules": {

        "TestModule": {

          "className": "<iOS-class-implementing-the-RCTModuleProvider-protocol>",

          "unstableRequiresMainQueueSetup": false,

          "conformsToProtocols": ["RCTImageURLLoader", "RCTURLRequestHandler", "RCTImageDataDecoder"],

        }

      },

      "components": {

        "TestComponent": {

          "className": "<iOS-class-implementing-the-component>"

        }

      }

    }

  },
```

    * `.className`: This module's ObjC class. Or, if it's a [C++-only module](/docs/next/the-new-architecture/pure-cxx-modules), its `RCTModuleProvider` class.
    * `.unstableRequiresMainQueueSetup`: Initialize this module on the UI Thread, before running any JavaScript.
    * `.conformsToProtocols`: Annotate which of these protocols this module conforms to any of the following protocols: [`RCTImageURLLoader`](https://github.com/react/react-native/blob/00d5caee9921b6c10be8f7d5b3903c6afe8dbefa/packages/react-native/Libraries/Image/RCTImageURLLoader.h#L26-L81), [`RCTURLRequestHandler`](https://github.com/react/react-native/blob/00d5caee9921b6c10be8f7d5b3903c6afe8dbefa/packages/react-native/React/Base/RCTURLRequestHandler.h#L11-L52), [`RCTImageDataDecoder`](https://github.com/react/react-native/blob/00d5caee9921b6c10be8f7d5b3903c6afe8dbefa/packages/react-native/Libraries/Image/RCTImageDataDecoder.h#L15-L53).

  * `.components[componentName]`:
    * `.className`: This component's ObjC class (e.g: `TextInput` -> `RCTTextInput`).

```
./gradlew generateCodegenArtifactsFromSchema
```

This task invokes the `generateCodegenArtifactsFromSchema` command on all the imported projects of the app (the app and all the node modules which are linked to it). It generates the code in the corresponding `node_modules/<dependency>` folder. For example, if you have a Fabric Native Component whose Node module is called `my-fabric-component`, the generated code is located in the `SampleApp/node_modules/my-fabric-component/android/build/generated/source/codegen` path. For the app, the code is generated in the `android/app/build/generated/source/codegen` folder.

#### The Generated Code[​](#the-generated-code "Direct link to The Generated Code")

After running the gradle command above, you will find the codegen code in the `SampleApp/android/app/build` folder. The structure will look like this:

```
build

└── generated

    └── source

        └── codegen

            ├── java

            │   └── com

            │       ├── facebook

            │       │   └── react

            │       │       └── viewmanagers

            │       │           ├── <nativeComponent>ManagerDelegate.java

            │       │           └── <nativeComponent>ManagerInterface.java

            │       └── sampleapp

            │           └── NativeLocalStorageSpec.java

            ├── jni

            │   ├── <codegenConfig.name>-generated.cpp

            │   ├── <codegenConfig.name>.h

            │   ├── CMakeLists.txt

            │   └── react

            │       └── renderer

            │           └── components

            │               └── <codegenConfig.name>

            │                   ├── <codegenConfig.name>JSI-generated.cpp

            │                   ├── <codegenConfig.name>.h

            │                   ├── ComponentDescriptors.cpp

            │                   ├── ComponentDescriptors.h

            │                   ├── EventEmitters.cpp

            │                   ├── EventEmitters.h

            │                   ├── Props.cpp

            │                   ├── Props.h

            │                   ├── ShadowNodes.cpp

            │                   ├── ShadowNodes.h

            │                   ├── States.cpp

            │                   └── States.h

            └── schema.json
```

```
node node_modules/react-native/scripts/generate-codegen-artifacts.js



Usage: generate-codegen-artifacts.js -p [path to app] -t [target platform] -o [output path]



Options:

      --help            Show help                                      [boolean]

      --version         Show version number                            [boolean]

  -p, --path            Path to the React Native project root.        [required]

  -t, --targetPlatform  Target platform. Supported values: "android", "ios",

                        "all".                                        [required]

  -o, --outputPath      Path where generated artifacts will be output to.
```

where:

* `--path` is the path to the root folder of your app.
* `--outputPath` is the destination where **Codegen** will write the generated files.
* `--targetPlatform` is the platform you'd like to generate the code for.

#### The Generated Code[​](#the-generated-code-1 "Direct link to The Generated Code")

Running the script with these arguments:

```
node node_modules/react-native/scripts/generate-codegen-artifacts.js \

    --path . \

    --outputPath ios/ \

    --targetPlatform ios
```

Will generate these files in the `ios/build` folder:

```
build

└── generated

    └── ios

        ├── <codegenConfig.name>

        │   ├── <codegenConfig.name>-generated.mm

        │   └── <codegenConfig.name>.h

        ├── <codegenConfig.name>JSI-generated.cpp

        ├── <codegenConfig.name>JSI.h

        ├── FBReactNativeSpec

        │   ├── FBReactNativeSpec-generated.mm

        │   └── FBReactNativeSpec.h

        ├── FBReactNativeSpecJSI-generated.cpp

        ├── FBReactNativeSpecJSI.h

        ├── RCTModulesConformingToProtocolsProvider.h

        ├── RCTModulesConformingToProtocolsProvider.mm

        └── react

            └── renderer

                └── components

                    └── <codegenConfig.name>

                        ├── ComponentDescriptors.cpp

                        ├── ComponentDescriptors.h

                        ├── EventEmitters.cpp

                        ├── EventEmitters.h

                        ├── Props.cpp

                        ├── Props.h

                        ├── RCTComponentViewHelpers.h

                        ├── ShadowNodes.cpp

                        ├── ShadowNodes.h

                        ├── States.cpp

                        └── States.h
```

----
url: https://reactnative.dev/docs/next/platform
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/platform)** (0.87).

Version: Next

## Example[​](#example "Direct link to Example")

***

# Reference

## Properties[​](#properties "Direct link to Properties")

### `constants`[​](#constants "Direct link to constants")

React TSX

```
static constants: PlatformConstants;
```

Returns an object which contains all available common and specific constants related to the platform.

**Properties:**

| Name                   | Type    | Optional | Description                                                                                                                                                                                       |
| ---------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| isDisableAnimations    | boolean | Yes      | Whether animations should be disabled. When not set, defaults to the value of `isTesting`.                                                                                                        |
| isTesting              | boolean | No       |                                                                                                                                                                                                   |
| reactNativeVersion     | object  | No       | Information about React Native version. Keys are `major`, `minor`, `patch` with optional `prerelease` and values are `number`s.                                                                   |
| VersionAndroid         | number  | No       | OS version constant specific to Android.                                                                                                                                                          |
| ReleaseAndroid         | string  | No       |                                                                                                                                                                                                   |
| SerialAndroid          | string  | No       | Hardware serial number of an Android device.                                                                                                                                                      |
| FingerprintAndroid     | string  | No       | A string that uniquely identifies the build.                                                                                                                                                      |
| ModelAndroid           | string  | No       | The end-user-visible name for the Android device.                                                                                                                                                 |
| BrandAndroid           | string  | No       | The consumer-visible brand with which the product/hardware will be associated.                                                                                                                    |
| ManufacturerAndroid    | string  | No       | The manufacturer of the Android device.                                                                                                                                                           |
| ServerHostAndroid      | string  | Yes      |                                                                                                                                                                                                   |
| uiModeAndroid          | string  | No       | Possible values are: `'car'`, `'desk'`, `'normal'`,`'tv'`, `'watch'` and `'unknown'`. Read more about [Android ModeType](https://developer.android.com/reference/android/app/UiModeManager.html). |
| forceTouchAvailableiOS | boolean | No       | Indicate the availability of 3D Touch on a device.                                                                                                                                                |
| interfaceIdiomiOS      | string  | No       | The interface type for the device. Read more about [UIUserInterfaceIdiom](https://developer.apple.com/documentation/uikit/uiuserinterfaceidiom).                                                  |
| osVersioniOS           | string  | No       | OS version constant specific to iOS.                                                                                                                                                              |
| systemNameiOS          | string  | No       | OS name constant specific to iOS.                                                                                                                                                                 |

***

### `isDisableAnimations`[​](#isdisableanimations "Direct link to isdisableanimations")

React TSX

```
static isDisableAnimations: boolean;
```

Returns `true` when animations are turned off, usually during automated tests. Falls back to [`isTesting`](#istesting) if not set. On Android, it can be set with the `IS_DISABLE_ANIMATIONS` system property.

| Type    |
| ------- |
| boolean |

***

### `isPad`iOS[​](#ispad-ios "Direct link to ispad-ios")

React TSX

```
static isPad: boolean;
```

Returns a boolean which defines if device is an iPad.

| Type    |
| ------- |
| boolean |

***

### `isTV`[​](#istv "Direct link to istv")

React TSX

```
static isTV: boolean;
```

Returns a boolean which defines if device is a TV.

| Type    |
| ------- |
| boolean |

***

### `isVision`[​](#isvision "Direct link to isvision")

React TSX

```
static isVision: boolean;
```

Returns a boolean which defines if device is an Apple Vision. *If you are using [Apple Vision Pro (Designed for iPad)](https://developer.apple.com/documentation/visionos/determining-whether-to-bring-your-app-to-visionos) `isVision` will be `false` but `isPad` will be `true`*

| Type    |
| ------- |
| boolean |

***

### `isTesting`[​](#istesting "Direct link to istesting")

React TSX

```
static isTesting: boolean;
```

Returns a boolean which defines if application is running in Developer Mode with testing flag set.

| Type    |
| ------- |
| boolean |

***

### `OS`[​](#os "Direct link to os")

React TSX

```
static OS: 'android' | 'ios';
```

Returns string value representing the current OS.

| Type                       |
| -------------------------- |
| enum(`'android'`, `'ios'`) |

***

### `Version`[​](#version "Direct link to version")

React TSX

```
static Version: 'number' | 'string';
```

Returns the version of the OS.

| Type                      |
| ------------------------- |
| numberAndroid***stringiOS |

## Methods[​](#methods "Direct link to Methods")

### `select()`[​](#select "Direct link to select")

React TSX

```
static select(config: Record<string, T>): T;
```

Returns the most fitting value for the platform you are currently running on.

#### Parameters:[​](#parameters "Direct link to Parameters:")

| Name   | Type   | Required | Description                   |
| ------ | ------ | -------- | ----------------------------- |
| config | object | Yes      | See config description below. |

```
import {Platform, StyleSheet} from 'react-native';



const styles = StyleSheet.create({

  container: {

    flex: 1,

    ...Platform.select({

      android: {

        backgroundColor: 'green',

      },

      ios: {

        backgroundColor: 'red',

      },

      default: {

        // other platforms, web for example

        backgroundColor: 'blue',

      },

    }),

  },

});
```

This will result in a container having `flex: 1` on all platforms, a green background color on Android, a red background color on iOS, and a blue background color on other platforms.

Since the value of the corresponding platform key can be of type `any`, [`select`](/docs/next/platform#select) method can also be used to return platform-specific components, like below:

React TSX

```
const Component = Platform.select({

  ios: () => require('ComponentIOS'),

  android: () => require('ComponentAndroid'),

})();



<Component />;
```

React TSX

```
const Component = Platform.select({

  native: () => require('ComponentForNative'),

  default: () => require('ComponentForWeb'),

})();



<Component />;
```

* [Example](#example)

* [Properties](#properties)

  * [`constants`](#constants)
  * [`isDisableAnimations`](#isdisableanimations)
  * [`isPad`](#ispad-ios)

    [iOS](#ispad-ios)

----
url: https://reactnative.dev/docs/next/environment-setup
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/environment-setup)** (0.87).

Version: Next

If your app has unusual constraints that are not served well by a Framework, or you prefer to solve these problems yourself, you can make a React Native app without a Framework using Android Studio, Xcode. If you’re interested in this path, learn how to [set up your environment](/docs/next/set-up-your-environment) and how to [get started without a framework](/docs/next/getting-started-without-a-framework).

```
npx create-expo-app@latest
```

Once you’ve created your app, check out the rest of Expo’s getting started guide to start developing your app.

[Continue with Expo](https://docs.expo.dev/get-started/set-up-your-environment)

----
url: https://reactnative.dev/docs/the-new-architecture/native-modules-custom-events
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
+import type {TurboModule, CodegenTypes} from 'react-native';

import {TurboModuleRegistry} from 'react-native';



+export type KeyValuePair = {

+  key: string,

+  value: string,

+}



export interface Spec extends TurboModule {

  setItem(value: string, key: string): void;

  getItem(key: string): string | null;

  removeItem(key: string): void;

  clear(): void;



+ readonly onKeyAdded: CodegenTypes.EventEmitter<KeyValuePair>;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeLocalStorage',

);
```

Open the `NativeLocalStorage.js` file and update it as it follows:

NativeLocalStorage.js

```


// @flow

+import type {TurboModule, CodegenTypes} from 'react-native';

import {TurboModule, TurboModuleRegistry} from 'react-native';



+export type KeyValuePair = {

+  key: string,

+  value: string,

+}



export interface Spec extends TurboModule {

  setItem(value: string, key: string): void;

  getItem(key: string): ?string;

  removeItem(key: string): void;

  clear(): void;

+ onKeyAdded: CodegenTypes.EventEmitter<KeyValuePair>

}

export default (TurboModuleRegistry.get<Spec>(

  'NativeLocalStorage'

): ?Spec);
```

```
cd android

./gradlew generateCodegenArtifactsFromSchema



BUILD SUCCESSFUL in 837ms

14 actionable tasks: 3 executed, 11 up-to-date
```

This is automatically run when you build your Android application.

Codegen is run as part of the script phases that's automatically added to the project generated by CocoaPods.

```
cd ios

bundle install

bundle exec pod install
```

The output will look like this:

```
...

Framework build type is static library

[Codegen] Adding script_phases to ReactCodegen.

[Codegen] Generating ./build/generated/ios/ReactCodegen.podspec.json

[Codegen] Analyzing /Users/me/src/TurboModuleExample/package.json

[Codegen] Searching for Codegen-enabled libraries in the app.

[Codegen] Found TurboModuleExample

[Codegen] Searching for Codegen-enabled libraries in the project dependencies.

[Codegen] Found react-native

...
```

## Step 3: Update the App code[​](#step-3-update-the-app-code "Direct link to Step 3: Update the App code")

Now, it's time to update the code of the App to handle the new event.

Open the `App.tsx` file and modify it as it follows:

App.tsx

```
import {

+ Alert,

+ EventSubscription,

  SafeAreaView,

  StyleSheet,

  Text,

  TextInput,

  Button,

} from 'react-native';



import NativeLocalStorage from './specs/NativeLocalStorage';



const EMPTY = '<empty>';



function App(): React.JSX.Element {

  const [value, setValue] = React.useState<string | null>(null);

+ const [key, setKey] = React.useState<string | null>(null);

+ const listenerSubscription = React.useRef<null | EventSubscription>(null);



+ React.useEffect(() => {

+   listenerSubscription.current = NativeLocalStorage?.onKeyAdded((pair) => Alert.alert(`New key added: ${pair.key} with value: ${pair.value}`));



+   return  () => {

+     listenerSubscription.current?.remove();

+     listenerSubscription.current = null;

+   }

+ }, [])



  const [editingValue, setEditingValue] = React.useState<

    string | null

  >(null);



- React.useEffect(() => {

-   const storedValue = NativeLocalStorage?.getItem('myKey');

-   setValue(storedValue ?? '');

- }, []);



  function saveValue() {

+   if (key == null) {

+     Alert.alert('Please enter a key');

+     return;

+   }

    NativeLocalStorage?.setItem(editingValue ?? EMPTY, key);

    setValue(editingValue);

  }



  function clearAll() {

    NativeLocalStorage?.clear();

    setValue('');

  }



  function deleteValue() {

+   if (key == null) {

+     Alert.alert('Please enter a key');

+     return;

+   }

    NativeLocalStorage?.removeItem(key);

    setValue('');

  }



+ function retrieveValue() {

+   if (key == null) {

+     Alert.alert('Please enter a key');

+     return;

+   }

+   const val = NativeLocalStorage?.getItem(key);

+   setValue(val);

+ }



  return (

    <SafeAreaView style={{flex: 1}}>

      <Text style={styles.text}>

        Current stored value is: {value ?? 'No Value'}

      </Text>

+     <Text>Key:</Text>

+      <TextInput

+       placeholder="Enter the key you want to store"

+       style={styles.textInput}

+       onChangeText={setKey}

+     />

+     <Text>Value:</Text>

      <TextInput

        placeholder="Enter the text you want to store"

        style={styles.textInput}

        onChangeText={setEditingValue}

      />

      <Button title="Save" onPress={saveValue} />

+     <Button title="Retrieve" onPress={retrieveValue} />

      <Button title="Delete" onPress={deleteValue} />

      <Button title="Clear" onPress={clearAll} />

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  text: {

    margin: 10,

    fontSize: 20,

  },

  textInput: {

    margin: 10,

    height: 40,

    borderColor: 'black',

    borderWidth: 1,

    paddingLeft: 5,

    paddingRight: 5,

    borderRadius: 5,

  },

});



export default App;
```

```
package com.nativelocalstorage



import android.content.Context

import android.content.SharedPreferences

import com.nativelocalstorage.NativeLocalStorageSpec

+import com.facebook.react.bridge.Arguments

import com.facebook.react.bridge.ReactApplicationContext

+import com.facebook.react.bridge.WritableMap



class NativeLocalStorageModule(reactContext: ReactApplicationContext) : NativeLocalStorageSpec(reactContext) {



  override fun getName() = NAME



  override fun setItem(value: String, key: String) {

+   var shouldEmit = false

+   if (getItem(key) != null) {

+       shouldEmit = true

+   }

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.putString(key, value)

    editor.apply()



+   if (shouldEmit == true) {

+       val eventData = Arguments.createMap().apply {

+           putString("key", key)

+           putString("value", value)

+       }

+       emitOnKeyAdded(eventData)

+   }

  }



  override fun getItem(key: String): String? {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val username = sharedPref.getString(key, null)

    return username.toString()

  }
```

```
#import <Foundation/Foundation.h>

#import <NativeLocalStorageSpec/NativeLocalStorageSpec.h>



NS_ASSUME_NONNULL_BEGIN



-@interface RCTNativeLocalStorage : NSObject <NativeLocalStorageSpec>

+@interface RCTNativeLocalStorage : NativeLocalStorageSpecBase <NativeLocalStorageSpec>



@end



NS_ASSUME_NONNULL_END
```

3. Open the `RCTNativeLocalStorage.mm` file.
4. Modify it to emit the events when needed, for example:

RCTNativeLocalStorage.mm

```
 - (void)setItem:(NSString *)value key:(NSString *)key {

+  BOOL shouldEmitEvent = NO;

+  if (![self getItem:key]) {

+    shouldEmitEvent = YES;

+  }

   [self.localStorage setObject:value forKey:key];



+  if (shouldEmitEvent) {

+    [self emitOnKeyAdded:@{@"key": key, @"value": value}];

+  }

}
```

The `NativeLocalStorageSpecBase` is a base class that provides the `emitOnKeyAdded` method and its basic implementation and boilerplate. Thanks to this class, you don't have to handle all the conversion between Objective-C and JSI that is required to send the event to JS.

In case of complex types, like the `KeyValuePair` defined in the specs, Codegen will generate a generic dictionary that you can populate on the native side. It's your responsibility to make sure that the the keys you are using in the dictionary are the same properties that are defined in the spec type in JS.

## Step 5: Run Your App[​](#step-5-run-your-app "Direct link to Step 5: Run Your App")

If you now try to run your app, you should see this behavior.

| Android | iOS |
| ------- | --- |
|         |     |

* [Emitting an Event when a new key added to the storage](#emitting-an-event-when-a-new-key-added-to-the-storage)
* [Step 1: Update the Specs of NativeLocalStorage](#step-1-update-the-specs-of-nativelocalstorage)
* [Step 2: Generate Codegen](#step-2-generate-codegen)
* [Step 3: Update the App code](#step-3-update-the-app-code)
* [Step 4: Write your Native Code](#step-4-write-your-native-code)
* [Step 5: Run Your App](#step-5-run-your-app)

----
url: https://reactnative.dev/docs/next/global-URLSearchParams
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-URLSearchParams)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) for more information.\\

The global `URLSearchParams` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/linking
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/linking)** (0.87).

Version: Next

| Scheme           | Description                                  | iOS | Android |
| ---------------- | -------------------------------------------- | --- | ------- |
| `mailto`         | Open mail app, eg: mailto: <hello@world.dev> | ✅   | ✅       |
| `tel`            | Open phone app, eg: tel:+123456789           | ✅   | ✅       |
| `sms`            | Open SMS app, eg: sms:+123456789             | ✅   | ✅       |
| `https` / `http` | Open web browser app, eg: <https://expo.dev> | ✅   | ✅       |

```
<activity

  android:name=".MainActivity"

  android:launchMode="singleTask">
```

On iOS, you'll need to add the `LinkingIOS` folder into your header search paths as described in step 3 [here](/docs/next/linking-libraries-ios#step-3). If you also want to listen to incoming app links during your app's execution, forward deep links from your `SceneDelegate`. If your app declares `UIApplicationSceneManifest` in `Info.plist`, `RCTLinkingManager` ignores the `AppDelegate` linking methods below - you must forward links from `SceneDelegate` instead.

* ObjectiveC
* Swift

SceneDelegate.m

```
#import <React/RCTLinkingManager.h>



- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts

{

  [RCTLinkingManager scene:scene openURLContexts:URLContexts];

}
```

If your app is using [Universal Links](https://developer.apple.com/ios/universal-links/), add the following as well:

SceneDelegate.m

```
- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity

{

  [RCTLinkingManager scene:scene continueUserActivity:userActivity];

}
```

SceneDelegate.swift

```
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

  RCTLinkingManager.scene(scene, openURLContexts: URLContexts)

}
```

If your app is using [Universal Links](https://developer.apple.com/ios/universal-links/), add the following as well:

SceneDelegate.swift

```
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {

  RCTLinkingManager.scene(scene, continue: userActivity)

}
```

These callbacks only cover links that arrive while the scene is connected. To handle linking in a cold-start (the app being launched by a custom URL scheme or a Universal Link), you also need to hand the scene's `UIScene.ConnectionOptions` to React Native when you bootstrap it, otherwise [`getInitialURL()`](#getinitialurl) resolves to `null`:

* ObjectiveC
* Swift

SceneDelegate.m

```
- (void)scene:(UIScene *)scene

    willConnectToSession:(UISceneSession *)session

                 options:(UISceneConnectionOptions *)connectionOptions

{

  // ...

  [self.reactNativeFactory startReactNativeWithModuleName:@"HelloWorld"

                                                 inWindow:self.window

                                        connectionOptions:connectionOptions];

}
```

SceneDelegate.swift

```
func scene(

  _ scene: UIScene,

  willConnectTo session: UISceneSession,

  options connectionOptions: UIScene.ConnectionOptions

) {

  // ...

  reactNativeFactory?.startReactNative(

    withModuleName: "HelloWorld",

    in: window,

    connectionOptions: connectionOptions

  )

}
```

See [Bootstrapping with SceneDelegate](/docs/next/integration-with-existing-apps#6-bootstrapping-with-scenedelegate) for the full `SceneDelegate` setup.

Apps without UIScene lifecycle

If your app does not use `SceneDelegate`, add the following lines to your `AppDelegate` instead:

* ObjectiveC
* Swift

AppDelegate.mm

```
// iOS 9.x or newer

#import <React/RCTLinkingManager.h>



- (BOOL)application:(UIApplication *)application

   openURL:(NSURL *)url

   options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options

{

  return [RCTLinkingManager application:application openURL:url options:options];

}
```

If your app is using [Universal Links](https://developer.apple.com/ios/universal-links/), you'll need to add the following code as well:

AppDelegate.mm

```
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity

 restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler

{

 return [RCTLinkingManager application:application

                  continueUserActivity:userActivity

                    restorationHandler:restorationHandler];

}
```

AppDelegate.swift

```
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

  return RCTLinkingManager.application(app, open: url, options: options)

}
```

If your app is using [Universal Links](https://developer.apple.com/ios/universal-links/), you'll need to add the following code as well:

AppDelegate.swift

```
func application(

  _ application: UIApplication,

  continue userActivity: NSUserActivity,

  restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {

    return RCTLinkingManager.application(

      application,

      continue: userActivity,

      restorationHandler: restorationHandler

    )

  }
```

***

### Handling Deep Links[​](#handling-deep-links "Direct link to Handling Deep Links")

There are two ways to handle URLs that open your app.

#### 1. If the app is already open, the app is foregrounded and a Linking 'url' event is fired[​](#1-if-the-app-is-already-open-the-app-is-foregrounded-and-a-linking-url-event-is-fired "Direct link to 1. If the app is already open, the app is foregrounded and a Linking 'url' event is fired")

You can handle these events with `Linking.addEventListener('url', callback)` - it calls `callback({url})` with the linked URL

#### 2. If the app is not already open, it is opened and the url is passed in as the initialURL[​](#2-if-the-app-is-not-already-open-it-is-opened-and-the-url-is-passed-in-as-the-initialurl "Direct link to 2. If the app is not already open, it is opened and the url is passed in as the initialURL")

You can handle these events with `Linking.getInitialURL()` - it returns a Promise that resolves to the URL, if there is one.

***

```
static addEventListener(

  type: 'url',

  handler: (event: {url: string}) => void,

): EventSubscription;
```

Add a handler to Linking changes by listening to the `url` event type and providing the handler.

***

### `canOpenURL()`[​](#canopenurl "Direct link to canopenurl")

React TSX

```
static canOpenURL(url: string): Promise<boolean>;
```

Determine whether or not an installed app can handle a given URL.

The method returns a `Promise` object. When it is determined whether or not the given URL can be handled, the promise is resolved and the first parameter is whether or not it can be opened.

The `Promise` will reject on Android if it was impossible to check if the URL can be opened or when targeting Android 11 (SDK 30) if you didn't specify the relevant intent queries in `AndroidManifest.xml`. Similarly on iOS, the promise will reject if you didn't add the specific scheme in the `LSApplicationQueriesSchemes` key inside `Info.plist` (see bellow).

**Parameters:**

| Name        | Type   | Description      |
| ----------- | ------ | ---------------- |
| urlRequired | string | The URL to open. |

```
<manifest ...>

  <queries>

    <intent>

      <action android:name="android.intent.action.VIEW" />

      <data android:scheme="https"/>

    </intent>

  </queries>

</manifest>
```

***

### `getInitialURL()`[​](#getinitialurl "Direct link to getinitialurl")

React TSX

```
static getInitialURL(): Promise<string | null>;
```

If the app launch was triggered by an app link, it will give the link url, otherwise it will give `null`.

info

To support deep linking on Android, refer <https://developer.android.com/training/app-indexing/deep-linking.html#handling-intents>.

tip

`getInitialURL` may return `null` when Remote JS Debugging is active. Disable the debugger to ensure it gets passed.

***

### `openSettings()`[​](#opensettings "Direct link to opensettings")

React TSX

```
static openSettings(): Promise<void>;
```

Open the Settings app and displays the app’s custom settings, if it has any.

***

### `openURL()`[​](#openurl "Direct link to openurl")

React TSX

```
static openURL(url: string): Promise<any>;
```

Try to open the given `url` with any of the installed apps.

You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386" on Android or "<https://maps.apple.com/?ll=37.484847,-122.148386>" on iOS), a contact, or any other URL that can be opened with the installed apps.

The method returns a `Promise` object. If the user confirms the open dialog or the url automatically opens, the promise is resolved. If the user cancels the open dialog or there are no registered applications for the url, the promise is rejected.

**Parameters:**

| Name        | Type   | Description      |
| ----------- | ------ | ---------------- |
| urlRequired | string | The URL to open. |

note

This method will fail if the system doesn't know how to open the specified URL. If you're passing in a non-http(s) URL, it's best to check `canOpenURL()` first. For web URLs, the protocol (`"http://"`, `"https://"`) must be set accordingly!

warning

This method may behave differently in a simulator e.g. `"tel:"` links are not able to be handled in the iOS simulator as there's no access to the dialer app.

***

### `sendIntent()`Android[​](#sendintent-android "Direct link to sendintent-android")

React TSX

```
static sendIntent(

  action: string,

  extras?: Array<{key: string; value: string | number | boolean}>,

): Promise<void>;
```

Launch an Android intent with extras.

**Parameters:**

| Name           | Type                                                     |
| -------------- | -------------------------------------------------------- |
| actionRequired | string                                                   |
| extras         | `Array<{key: string, value: string ｜ number ｜ boolean}>` |

    [Android](#sendintent-android)

----
url: https://reactnative.dev/docs/legacy/native-modules-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

Welcome to Native Modules for Android. Please start by reading the [Native Modules Intro](/docs/legacy/native-modules-intro) for an intro to what native modules are.

```
package com.your-apps-package-name; // replace your-apps-package-name with your app’s package name

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.bridge.ReactContext;

import com.facebook.react.bridge.ReactContextBaseJavaModule;

import com.facebook.react.bridge.ReactMethod;

import java.util.Map;

import java.util.HashMap;



public class CalendarModule extends ReactContextBaseJavaModule {

   CalendarModule(ReactApplicationContext context) {

       super(context);

   }

}
```

Kotlin

```
package com.your-apps-package-name; // replace your-apps-package-name with your app’s package name

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.bridge.ReactContext

import com.facebook.react.bridge.ReactContextBaseJavaModule

import com.facebook.react.bridge.ReactMethod



class CalendarModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {...}
```

```
// add to CalendarModule.java

@Override

public String getName() {

   return "CalendarModule";

}
```

Kotlin

```
// add to CalendarModule.kt

override fun getName() = "CalendarModule"
```

The native module can then be accessed in JS like this:

React TSX

```
const {CalendarModule} = ReactNative.NativeModules;
```

### Export a Native Method to JavaScript[​](#export-a-native-method-to-javascript "Direct link to Export a Native Method to JavaScript")

Next you will need to add a method to your native module that will create calendar events and can be invoked in JavaScript. All native module methods meant to be invoked from JavaScript must be annotated with `@ReactMethod`.

Set up a method `createCalendarEvent()` for `CalendarModule` that can be invoked in JS through `CalendarModule.createCalendarEvent()`. For now, the method will take in a name and location as strings. Argument type options will be covered shortly.

* Java
* Kotlin

Java

```
@ReactMethod

public void createCalendarEvent(String name, String location) {

}
```

Kotlin

```
@ReactMethod fun createCalendarEvent(name: String, location: String) {}
```

Add a debug log in the method to confirm it has been invoked when you call it from your application. Below is an example of how you can import and use the [Log](https://developer.android.com/reference/android/util/Log) class from the Android util package:

* Java
* Kotlin

Java

```
import android.util.Log;



@ReactMethod

public void createCalendarEvent(String name, String location) {

   Log.d("CalendarModule", "Create event called with name: " + name

   + " and location: " + location);

}
```

Kotlin

```
import android.util.Log



@ReactMethod

fun createCalendarEvent(name: String, location: String) {

    Log.d("CalendarModule", "Create event called with name: $name and location: $location")

}
```

Once you finish implementing the native module and hook it up in JavaScript, you can follow [these steps](https://developer.android.com/studio/debug/am-logcat.html) to view the logs from your app.

### Synchronous Methods[​](#synchronous-methods "Direct link to Synchronous Methods")

You can pass `isBlockingSynchronousMethod = true` to a native method to mark it as a synchronous method.

* Java
* Kotlin

Java

```
@ReactMethod(isBlockingSynchronousMethod = true)
```

Kotlin

```
@ReactMethod(isBlockingSynchronousMethod = true)
```

```
package com.your-app-name; // replace your-app-name with your app’s name

import com.facebook.react.ReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.uimanager.ViewManager;



import java.util.ArrayList;

import java.util.Collections;

import java.util.List;



public class MyAppPackage implements ReactPackage {



   @Override

   public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {

       return Collections.emptyList();

   }



   @Override

   public List<NativeModule> createNativeModules(

           ReactApplicationContext reactContext) {

       List<NativeModule> modules = new ArrayList<>();



       modules.add(new CalendarModule(reactContext));



       return modules;

   }



}
```

Kotlin

```
package com.your-app-name // replace your-app-name with your app’s name



import android.view.View

import com.facebook.react.ReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.uimanager.ReactShadowNode

import com.facebook.react.uimanager.ViewManager



class MyAppPackage : ReactPackage {



    override fun createViewManagers(

        reactContext: ReactApplicationContext

    ): MutableList<ViewManager<View, ReactShadowNode<*>>> = mutableListOf()



    override fun createNativeModules(

        reactContext: ReactApplicationContext

    ): MutableList<NativeModule> = listOf(CalendarModule(reactContext)).toMutableList()

}
```

```
@Override

protected List<ReactPackage> getPackages() {

    List<ReactPackage> packages = new PackageList(this).getPackages();

    // Packages that cannot be autolinked yet can be added manually here, for example:

    // packages.add(new MyReactNativePackage());

    packages.add(new MyAppPackage());

    return packages;

}
```

Kotlin

```
override fun getPackages(): List<ReactPackage> =

    PackageList(this).packages.apply {

        // Packages that cannot be autolinked yet can be added manually here, for example:

        // add(MyReactNativePackage())

        add(MyAppPackage())

    }
```

You have now successfully registered your native module for Android!

### Test What You Have Built[​](#test-what-you-have-built "Direct link to Test What You Have Built")

At this point, you have set up the basic scaffolding for your native module in Android. Test that out by accessing the native module and invoking its exported method in JavaScript.

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.

React TSX

```
import {NativeModules, Button} from 'react-native';



const NewModuleButton = () => {

  const onPress = () => {

    console.log('We will invoke the native module here!');

  };



  return (

    <Button

      title="Click to invoke your native module!"

      color="#841584"

      onPress={onPress}

    />

  );

};



export default NewModuleButton;
```

In order to access your native module from JavaScript you need to first import `NativeModules` from React Native:

React TSX

```
import {NativeModules} from 'react-native';
```

You can then access the `CalendarModule` native module off of `NativeModules`.

React 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`:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent('testName', 'testLocation');

};
```

The final step is to rebuild the React Native app so that you can have the latest native code (with your new native module!) available. In your command line, where the react native application is located, run the following:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

```
/**

* This exposes the native CalendarModule module as a JS module. This has a

* function 'createCalendarEvent' which takes the following parameters:



* 1. String name: A string representing the name of the event

* 2. String location: A string representing the location of the event

*/

import {NativeModules} from 'react-native';

const {CalendarModule} = NativeModules;

export default CalendarModule;
```

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:

React TSX

```
/**

 * This exposes the native CalendarModule module as a JS module. This has a

 * function 'createCalendarEvent' which takes the following parameters:

 *

 * 1. String name: A string representing the name of the event

 * 2. String location: A string representing the location of the event

 */

import {NativeModules} from 'react-native';

const {CalendarModule} = NativeModules;

interface CalendarInterface {

  createCalendarEvent(name: string, location: string): void;

}

export default CalendarModule as CalendarInterface;
```

In your other JavaScript files you can access the native module and invoke its method like this:

React TSX

```
import CalendarModule from './CalendarModule';

CalendarModule.createCalendarEvent('foo', 'bar');
```

note

This assumes that the place you are importing `CalendarModule` is in the same hierarchy as `CalendarModule.js`. Please update the relative import as necessary.

### Argument Types[​](#argument-types "Direct link to Argument Types")

When a native module method is invoked in JavaScript, React Native converts the arguments from JS objects to their Java/Kotlin object analogues. So for example, if your Java Native Module method accepts a double, in JS you need to call the method with a number. React Native will handle the conversion for you. Below is a list of the argument types supported for native module methods and the JavaScript equivalents they map to.

| Java          | Kotlin        | JavaScript |
| ------------- | ------------- | ---------- |
| Boolean       | Boolean       | ?boolean   |
| boolean       |               | boolean    |
| Double        | Double        | ?number    |
| double        |               | number     |
| String        | String        | string     |
| Callback      | Callback      | Function   |
| Promise       | Promise       | Promise    |
| ReadableMap   | ReadableMap   | Object     |
| ReadableArray | ReadableArray | Array      |

```
    String dateFormat = "yyyy-MM-dd";

    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

    Calendar eStartDate = Calendar.getInstance();

    try {

        eStartDate.setTime(sdf.parse(startDate));

    }
```

Kotlin

```
    val dateFormat = "yyyy-MM-dd"

    val sdf = SimpleDateFormat(dateFormat, Locale.US)

    val eStartDate = Calendar.getInstance()

    try {

        sdf.parse(startDate)?.let {

            eStartDate.time = it

        }

    }
```

### Exporting Constants[​](#exporting-constants "Direct link to Exporting Constants")

A native module can export constants by implementing the native method `getConstants()`, which is available in JS. Below you will implement `getConstants()` and return a Map that contains a `DEFAULT_EVENT_NAME` constant you can access in JavaScript:

* Java
* Kotlin

Java

```
@Override

public Map<String, Object> getConstants() {

   final Map<String, Object> constants = new HashMap<>();

   constants.put("DEFAULT_EVENT_NAME", "New Event");

   return constants;

}
```

Kotlin

```
override fun getConstants(): MutableMap<String, Any> =

    hashMapOf("DEFAULT_EVENT_NAME" to "New Event")
```

The constant can then be accessed by invoking `getConstants` on the native module in JS:

React TSX

```
const {DEFAULT_EVENT_NAME} = CalendarModule.getConstants();

console.log(DEFAULT_EVENT_NAME);
```

```
import com.facebook.react.bridge.Callback;



@ReactMethod

public void createCalendarEvent(String name, String location, Callback callBack) {

}
```

Kotlin

```
import com.facebook.react.bridge.Callback



@ReactMethod fun createCalendarEvent(name: String, location: String, callback: Callback) {}
```

You can invoke the callback in your Java/Kotlin method, providing whatever data you want to pass to JavaScript. Please note that you can only pass serializable data from native code to JavaScript. If you need to pass back a native object you can use `WriteableMaps`, if you need to use a collection use `WritableArrays`. It is also important to highlight that the callback is not invoked immediately after the native function completes. Below the ID of an event created in an earlier call is passed to the callback.

* Java
* Kotlin

Java

```
  @ReactMethod

   public void createCalendarEvent(String name, String location, Callback callBack) {

       Integer eventId = ...

       callBack.invoke(eventId);

   }
```

Kotlin

```
  @ReactMethod

  fun createCalendarEvent(name: String, location: String, callback: Callback) {

      val eventId = ...

      callback.invoke(eventId)

  }
```

This method could then be accessed in JavaScript using:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent(

    'Party',

    'My House',

    eventId => {

      console.log(`Created a new event with id ${eventId}`);

    },

  );

};
```

Another important detail to note is that a native module method can only invoke one callback, one time. This means that you can either call a success callback or a failure callback, but not both, and each callback can only be invoked at most one time. A native module can, however, store the callback and invoke it later.

There are two approaches to error handling with callbacks. The first is to follow Node’s convention and treat the first argument passed to the callback as an error object.

* Java
* Kotlin

Java

```
  @ReactMethod

   public void createCalendarEvent(String name, String location, Callback callBack) {

       Integer eventId = ...

       callBack.invoke(null, eventId);

   }
```

Kotlin

```
  @ReactMethod

  fun createCalendarEvent(name: String, location: String, callback: Callback) {

      val eventId = ...

      callback.invoke(null, eventId)

  }
```

In JavaScript, you can then check the first argument to see if an error was passed through:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent(

    'testName',

    'testLocation',

    (error, eventId) => {

      if (error) {

        console.error(`Error found! ${error}`);

      }

      console.log(`event id ${eventId} returned`);

    },

  );

};
```

Another option is to use an onSuccess and onFailure callback:

* Java
* Kotlin

Java

```
@ReactMethod

public void createCalendarEvent(String name, String location, Callback myFailureCallback, Callback mySuccessCallback) {

}
```

Kotlin

```
@ReactMethod

  fun createCalendarEvent(

      name: String,

      location: String,

      myFailureCallback: Callback,

      mySuccessCallback: Callback

  ) {}
```

Then in JavaScript you can add a separate callback for error and success responses:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent(

    'testName',

    'testLocation',

    error => {

      console.error(`Error found! ${error}`);

    },

    eventId => {

      console.log(`event id ${eventId} returned`);

    },

  );

};
```

### Promises[​](#promises "Direct link to Promises")

Native modules can also fulfill a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), which can simplify your JavaScript, especially when using ES2016's [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) syntax. When the last parameter of a native module Java/Kotlin method is a Promise, its corresponding JS method will return a JS Promise object.

Refactoring the above code to use a promise instead of callbacks looks like this:

* Java
* Kotlin

Java

```
import com.facebook.react.bridge.Promise;



@ReactMethod

public void createCalendarEvent(String name, String location, Promise promise) {

    try {

        Integer eventId = ...

        promise.resolve(eventId);

    } catch(Exception e) {

        promise.reject("Create Event Error", e);

    }

}
```

Kotlin

```
import com.facebook.react.bridge.Promise



@ReactMethod

fun createCalendarEvent(name: String, location: String, promise: Promise) {

    try {

        val eventId = ...

        promise.resolve(eventId)

    } catch (e: Throwable) {

        promise.reject("Create Event Error", e)

    }

}
```

note

Similar to callbacks, a native module method can either reject or resolve a promise (but not both) and can do so at most once. This means that you can either call a success callback or a failure callback, but not both, and each callback can only be invoked at most one time. A native module can, however, store the callback and invoke it later.

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:

React TSX

```
const onSubmit = async () => {

  try {

    const eventId = await CalendarModule.createCalendarEvent(

      'Party',

      'My House',

    );

    console.log(`Created a new event with id ${eventId}`);

  } catch (e) {

    console.error(e);

  }

};
```

The reject method takes different combinations of the following arguments:

* Java
* Kotlin

Java

```
String code, String message, WritableMap userInfo, Throwable throwable
```

Kotlin

```
code: String, message: String, userInfo: WritableMap, throwable: Throwable
```

For more detail, you can find the `Promise.java` interface [here](https://github.com/react/react-native/blob/main/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/Promise.kt). If `userInfo` is not provided, ReactNative will set it to null. For the rest of the parameters React Native will use a default value. The `message` argument provides the error `message` shown at the top of an error call stack. Below is an example of the error message shown in JavaScript from the following reject call in Java/Kotlin.

Java/Kotlin reject call:

* Java
* Kotlin

Java

```
promise.reject("Create Event error", "Error parsing date", e);
```

Kotlin

```
promise.reject("Create Event error", "Error parsing date", e)
```

```
...

import com.facebook.react.modules.core.DeviceEventManagerModule;

import com.facebook.react.bridge.WritableMap;

import com.facebook.react.bridge.Arguments;

...

private void sendEvent(ReactContext reactContext,

                      String eventName,

                      @Nullable WritableMap params) {

 reactContext

     .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)

     .emit(eventName, params);

}



private int listenerCount = 0;



@ReactMethod

public void addListener(String eventName) {

  if (listenerCount == 0) {

    // Set up any upstream listeners or background tasks as necessary

  }



  listenerCount += 1;

}



@ReactMethod

public void removeListeners(Integer count) {

  listenerCount -= count;

  if (listenerCount == 0) {

    // Remove upstream listeners, stop unnecessary background tasks

  }

}

...

WritableMap params = Arguments.createMap();

params.putString("eventProperty", "someValue");

...

sendEvent(reactContext, "EventReminder", params);
```

Kotlin

```
...

import com.facebook.react.bridge.WritableMap

import com.facebook.react.bridge.Arguments

import com.facebook.react.modules.core.DeviceEventManagerModule

...



private fun sendEvent(reactContext: ReactContext, eventName: String, params: WritableMap?) {

    reactContext

      .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)

      .emit(eventName, params)

}



private var listenerCount = 0



@ReactMethod

fun addListener(eventName: String) {

  if (listenerCount == 0) {

    // Set up any upstream listeners or background tasks as necessary

  }



  listenerCount += 1

}



@ReactMethod

fun removeListeners(count: Int) {

  listenerCount -= count

  if (listenerCount == 0) {

    // Remove upstream listeners, stop unnecessary background tasks

  }

}

...

val params = Arguments.createMap().apply {

    putString("eventProperty", "someValue")

}

...

sendEvent(reactContext, "EventReminder", params)
```

JavaScript modules can then register to receive events by `addListener` on the [NativeEventEmitter](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/EventEmitter/NativeEventEmitter.js) class.

React TSX

```
import {NativeEventEmitter, NativeModules} from 'react-native';

...

useEffect(() => {

    const eventEmitter = new NativeEventEmitter(NativeModules.ToastExample);

    let eventListener = eventEmitter.addListener('EventReminder', event => {

      console.log(event.eventProperty) // "someValue"

    });



    // Removes the listener once unmounted

    return () => {

      eventListener.remove();

    };

  }, []);
```

### Getting Activity Result from startActivityForResult[​](#getting-activity-result-from-startactivityforresult "Direct link to Getting Activity Result from startActivityForResult")

You'll need to listen to `onActivityResult` if you want to get results from an activity you started with `startActivityForResult`. To do this, you must extend `BaseActivityEventListener` or implement `ActivityEventListener`. The former is preferred as it is more resilient to API changes. Then, you need to register the listener in the module's constructor like so:

* Java
* Kotlin

Java

```
reactContext.addActivityEventListener(mActivityResultListener);
```

Kotlin

```
reactContext.addActivityEventListener(mActivityResultListener);
```

Now you can listen to `onActivityResult` by implementing the following method:

* Java
* Kotlin

Java

```
@Override

public void onActivityResult(

 final Activity activity,

 final int requestCode,

 final int resultCode,

 final Intent intent) {

 // Your logic here

}
```

Kotlin

```
override fun onActivityResult(

    activity: Activity?,

    requestCode: Int,

    resultCode: Int,

    intent: Intent?

) {

    // Your logic here

}
```

Let's implement a basic image picker to demonstrate this. The image picker will expose the method `pickImage` to JavaScript, which will return the path of the image when called.

* Java
* Kotlin

Kotlin

```
public class ImagePickerModule extends ReactContextBaseJavaModule {



  private static final int IMAGE_PICKER_REQUEST = 1;

  private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST";

  private static final String E_PICKER_CANCELLED = "E_PICKER_CANCELLED";

  private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER";

  private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND";



  private Promise mPickerPromise;



  private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {



    @Override

    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) {

      if (requestCode == IMAGE_PICKER_REQUEST) {

        if (mPickerPromise != null) {

          if (resultCode == Activity.RESULT_CANCELED) {

            mPickerPromise.reject(E_PICKER_CANCELLED, "Image picker was cancelled");

          } else if (resultCode == Activity.RESULT_OK) {

            Uri uri = intent.getData();



            if (uri == null) {

              mPickerPromise.reject(E_NO_IMAGE_DATA_FOUND, "No image data found");

            } else {

              mPickerPromise.resolve(uri.toString());

            }

          }



          mPickerPromise = null;

        }

      }

    }

  };



  ImagePickerModule(ReactApplicationContext reactContext) {

    super(reactContext);



    // Add the listener for `onActivityResult`

    reactContext.addActivityEventListener(mActivityEventListener);

  }



  @Override

  public String getName() {

    return "ImagePickerModule";

  }



  @ReactMethod

  public void pickImage(final Promise promise) {

    Activity currentActivity = getCurrentActivity();



    if (currentActivity == null) {

      promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");

      return;

    }



    // Store the promise to resolve/reject when picker returns data

    mPickerPromise = promise;



    try {

      final Intent galleryIntent = new Intent(Intent.ACTION_PICK);



      galleryIntent.setType("image/*");



      final Intent chooserIntent = Intent.createChooser(galleryIntent, "Pick an image");



      currentActivity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST);

    } catch (Exception e) {

      mPickerPromise.reject(E_FAILED_TO_SHOW_PICKER, e);

      mPickerPromise = null;

    }

  }

}
```

Kotlin

```
class ImagePickerModule(reactContext: ReactApplicationContext) :

    ReactContextBaseJavaModule(reactContext) {



    private var pickerPromise: Promise? = null



    private val activityEventListener =

        object : BaseActivityEventListener() {

            override fun onActivityResult(

                activity: Activity?,

                requestCode: Int,

                resultCode: Int,

                intent: Intent?

            ) {

                if (requestCode == IMAGE_PICKER_REQUEST) {

                    pickerPromise?.let { promise ->

                        when (resultCode) {

                            Activity.RESULT_CANCELED ->

                                promise.reject(E_PICKER_CANCELLED, "Image picker was cancelled")

                            Activity.RESULT_OK -> {

                                val uri = intent?.data



                                uri?.let { promise.resolve(uri.toString())}

                                    ?: promise.reject(E_NO_IMAGE_DATA_FOUND, "No image data found")

                            }

                        }



                        pickerPromise = null

                    }

                }

            }

        }



    init {

        reactContext.addActivityEventListener(activityEventListener)

    }



    override fun getName() = "ImagePickerModule"



    @ReactMethod

    fun pickImage(promise: Promise) {

        val activity = currentActivity



        if (activity == null) {

            promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist")

            return

        }



        pickerPromise = promise



        try {

            val galleryIntent = Intent(Intent.ACTION_PICK).apply { type = "image\/*" }



            val chooserIntent = Intent.createChooser(galleryIntent, "Pick an image")



            activity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST)

        } catch (t: Throwable) {

            pickerPromise?.reject(E_FAILED_TO_SHOW_PICKER, t)

            pickerPromise = null

        }

    }



    companion object {

        const val IMAGE_PICKER_REQUEST = 1

        const val E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST"

        const val E_PICKER_CANCELLED = "E_PICKER_CANCELLED"

        const val E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER"

        const val E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND"

    }

}
```

### Listening to Lifecycle Events[​](#listening-to-lifecycle-events "Direct link to Listening to Lifecycle Events")

Listening to the activity's LifeCycle events such as `onResume`, `onPause` etc. is very similar to how `ActivityEventListener` was implemented. The module must implement `LifecycleEventListener`. Then, you need to register a listener in the module's constructor like so:

* Java
* Kotlin

Java

```
reactContext.addLifecycleEventListener(this);
```

Kotlin

```
reactContext.addLifecycleEventListener(this)
```

Now you can listen to the activity's LifeCycle events by implementing the following methods:

* Java
* Kotlin

Java

```
@Override

public void onHostResume() {

   // Activity `onResume`

}

@Override

public void onHostPause() {

   // Activity `onPause`

}

@Override

public void onHostDestroy() {

   // Activity `onDestroy`

}
```

Kotlin

```
override fun onHostResume() {

    // Activity `onResume`

}



override fun onHostPause() {

    // Activity `onPause`

}



override fun onHostDestroy() {

    // Activity `onDestroy`

}
```

----
url: https://reactnative.dev/docs/getting-started-without-a-framework
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

To do so, you'll first need to [set up your environment](/docs/set-up-your-environment). Once you're set up, continue with the steps below to create an application and start developing.

### Step 1: Creating a new application[​](#step-1-creating-a-new-application "Direct link to Step 1: Creating a new application")

warning

If you previously installed a global `react-native-cli` package, please remove it as it may cause unexpected issues:

```
npm uninstall -g react-native-cli @react-native-community/cli
```

You can use [React Native Community CLI](https://github.com/react-native-community/cli) to generate a new project. Let's create a new React Native project called "AwesomeProject":

```
npx @react-native-community/cli@latest init AwesomeProject
```

This is not necessary if you are integrating React Native into an existing application, or if you've installed [Expo](https://docs.expo.dev/bare/installing-expo-modules/) in your project, or if you're adding Android support to an existing React Native project (see [Integration with Existing Apps](/docs/integration-with-existing-apps)). You can also use a third-party CLI to set up your React Native app, such as [Ignite CLI](https://github.com/infinitered/ignite).

```
npx @react-native-community/cli@X.XX.X init AwesomeProject --version X.XX.X
```

You can also start a project with a custom React Native template with the `--template` argument, read more [here](https://github.com/react-native-community/cli/blob/main/docs/init.md#initializing-project-with-custom-template).

### Step 2: Start Metro[​](#step-2-start-metro "Direct link to Step 2: Start Metro")

[**Metro**](https://metrobundler.dev/) is the JavaScript build tool for React Native. To start the Metro development server, run the following from your project folder:

* npm
* Yarn

```
npm start
```

```
yarn start
```

note

If you're familiar with web development, Metro is similar to bundlers such as Vite and webpack, but is designed end-to-end for React Native. For instance, Metro uses [Babel](https://babel.dev/) to transform syntax such as JSX into executable JavaScript.

### Step 3: Start your application[​](#step-3-start-your-application "Direct link to Step 3: Start your application")

Let Metro Bundler run in its own terminal. Open a new terminal inside your React Native project folder. Run the following:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

If everything is set up correctly, you should see your new app running in your Android emulator shortly.

This is one way to run your app - you can also run it directly from within Android Studio.

tip

If you can't get this to work, see the [Troubleshooting](/docs/troubleshooting) page.

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/getting-started).

----
url: https://reactnative.dev/docs/react-native-gradle-plugin
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
apply plugin: "com.facebook.react"



/**

 * This is the configuration block to customize your React Native Android app.

 * By default you don't need to apply any configuration, just uncomment the lines you need.

 */

react {

  // Custom configuration goes here.

}
```

Each configuration key is described below:

### `root`[​](#root "Direct link to root")

This is the root folder of your React Native project, i.e. where the `package.json` file lives. Default is `..`. You can customize it as follows:

Groovy

```
root = file("../")
```

### `reactNativeDir`[​](#reactnativedir "Direct link to reactnativedir")

This is the folder where the `react-native` package lives. Default is `../node_modules/react-native`. If you're in a monorepo or using a different package manager, you can use adjust `reactNativeDir` to your setup.

You can customize it as follows:

Groovy

```
reactNativeDir = file("../node_modules/react-native")
```

### `codegenDir`[​](#codegendir "Direct link to codegendir")

This is the folder where the `react-native-codegen` package lives. Default is `../node_modules/react-native-codegen`. If you're in a monorepo or using a different package manager, you can adjust `codegenDir` to your setup.

You can customize it as follows:

Groovy

```
codegenDir = file("../node_modules/@react-native/codegen")
```

### `cliFile`[​](#clifile "Direct link to clifile")

This is the entrypoint file for the React Native CLI. Default is `../node_modules/react-native/cli.js`. The entrypoint file is needed as the plugin needs to invoke the CLI for bundling and creating your app.

If you're in a monorepo or using a different package manager, you can adjust `cliFile` to your setup. You can customize it as follows:

Groovy

```
cliFile = file("../node_modules/react-native/cli.js")
```

### `debuggableVariants`[​](#debuggablevariants "Direct link to debuggablevariants")

This is the list of variants that are debuggable (see [using variants](#using-flavors--build-variants) for more context on variants).

By default the plugin is considering as `debuggableVariants` only `debug`, while `release` is not. If you have other variants (like `staging`, `lite`, etc.) you'll need to adjust this accordingly.

Variants that are listed as `debuggableVariants` will not come with a shipped bundle, so you'll need Metro to run them.

You can customize it as follows:

Groovy

```
debuggableVariants = ["liteDebug", "prodDebug"]
```

### `nodeExecutableAndArgs`[​](#nodeexecutableandargs "Direct link to nodeexecutableandargs")

This is the list of node command and arguments that should be invoked for all the scripts. By default is `[node]` but can be customized to add extra flags as follows:

Groovy

```
nodeExecutableAndArgs = ["node"]
```

### `bundleCommand`[​](#bundlecommand "Direct link to bundlecommand")

This is the name of the `bundle` command to be invoked when creating the bundle for your app. That's useful if you're using [RAM Bundles](https://reactnative.dev/docs/0.74/ram-bundles-inline-requires). By default is `bundle` but can be customized to add extra flags as follows:

Groovy

```
bundleCommand = "ram-bundle"
```

### `bundleConfig`[​](#bundleconfig "Direct link to bundleconfig")

This is the path to a configuration file that will be passed to `bundle --config <file>` if provided. Default is empty (no config file will be probided). More information on bundling config files can be found [on the CLI documentation](https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle). Can be customized as follow:

Groovy

```
bundleConfig = file(../rn-cli.config.js)
```

### `bundleAssetName`[​](#bundleassetname "Direct link to bundleassetname")

This is the name of the bundle file that should be generated. Default is `index.android.bundle`. Can be customized as follow:

Groovy

```
bundleAssetName = "MyApplication.android.bundle"
```

### `entryFile`[​](#entryfile "Direct link to entryfile")

The entry file used for bundle generation. The default is to search for `index.android.js` or `index.js`. Can be customized as follow:

Groovy

```
entryFile = file("../js/MyApplication.android.js")
```

### `extraPackagerArgs`[​](#extrapackagerargs "Direct link to extrapackagerargs")

A list of extra flags that will be passed to the `bundle` command. The list of available flags is in [the CLI documentation](https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle). Default is empty. Can be customized as follows:

Groovy

```
extraPackagerArgs = []
```

### `hermesCommand`[​](#hermescommand "Direct link to hermescommand")

The path to the `hermesc` command (the Hermes Compiler). React Native comes with a version of the Hermes compiler bundled with it, so you generally won't be needing to customize this. The plugin will use the correct compiler for your system by default.

### `hermesFlags`[​](#hermesflags "Direct link to hermesflags")

The list of flags to pass to `hermesc`. By default is `["-O", "-output-source-map"]`. You can customize it as follows

Groovy

```
hermesFlags = ["-O", "-output-source-map"]
```

```
apply plugin: "com.facebook.react"



react {

+ debuggableVariants = ["fullStaging", "fullDebug"]

}
```

----
url: https://reactnative.dev/docs/platformcolor
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

JavaScript

```
PlatformColor(color1, [color2, ...colorN]);
```

You can use the `PlatformColor` function to access native colors on the target platform by supplying the native color’s corresponding string value. You pass a string to the `PlatformColor` function and, provided it exists on that platform, it will return the corresponding native color, which you can apply in any part of your application.

If you pass more than one string value to the `PlatformColor` function, it will treat the first value as the default and the rest as fallback.

JavaScript

```
PlatformColor('bogusName', 'linkColor');
```

----
url: https://reactnative.dev/docs/usecolorscheme
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React TSX

```
import {useColorScheme} from 'react-native';
```

The `useColorScheme` React hook provides and subscribes to color scheme updates from the [`Appearance`](/docs/appearance) module. The return value indicates the active color scheme. The value may be updated later, either through direct user action (e.g. theme selection in device settings or application-level selected user interface style via [`setColorScheme`](/docs/appearance#setcolorscheme)) or on a schedule (e.g. light and dark themes that follow the day/night cycle).

### Return values[​](#return-values "Direct link to Return values")

* `'light'`: The light color scheme is applied.
* `'dark'`: The dark color scheme is applied.
* `null`: May be returned if the native Appearance module is not available.

***

## Example[​](#example "Direct link to Example")

You can find a complete example that demonstrates the use of this hook alongside a React context to add support for light and dark themes to your application in [`AppearanceExample.js`](https://github.com/react/react-native/blob/main/packages/rn-tester/js/examples/Appearance/AppearanceExample.js).

* [Return values](#return-values)
* [Example](#example)

----
url: https://reactnative.dev/docs/accessibility
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
<View>

  <View accessible={true} />

  <View />

</View>
```

In the above example, accessibility focus is only available on the first child view with the `accessible` property, and not for the parent or sibling without `accessible`.

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

When a view is marked as accessible, it is a good practice to set an `accessibilityLabel` on the view, so that people who use VoiceOver or TalkBack know what element they have selected. A screen reader will verbalize this string when the associated element is selected.

To use, set the `accessibilityLabel` property to a custom string on your View, Text, or Touchable:

React TSX

```
<TouchableOpacity

  accessible={true}

  accessibilityLabel="Tap me!"

  onPress={onPress}>

  <View style={styles.button}>

    <Text style={styles.buttonText}>Press me!</Text>

  </View>

</TouchableOpacity>
```

In the above example, the `accessibilityLabel` on the TouchableOpacity element would default to "Press me!". The label is constructed by concatenating all Text node children separated by spaces.

### `accessibilityLabelledBy`Android[​](#accessibilitylabelledby-android "Direct link to accessibilitylabelledby-android")

A reference to another element [nativeID](/docs/view#nativeid) used to build complex forms. The value of `accessibilityLabelledBy` should match the `nativeID` of the related element:

React TSX

```
<View>

  <Text nativeID="formLabel">Label for Input Field</Text>

  <TextInput

    accessibilityLabel="input"

    accessibilityLabelledBy="formLabel"

  />

</View>
```

In the above example, the screen reader announces `Input, Edit Box for Label for Input Field` when focusing on the TextInput.

### `accessibilityHint`[​](#accessibilityhint "Direct link to accessibilityhint")

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:

React TSX

```
<TouchableOpacity

  accessible={true}

  accessibilityLabel="Go back"

  accessibilityHint="Navigates to the previous screen"

  onPress={onPress}>

  <View style={styles.button}>

    <Text style={styles.buttonText}>Back</Text>

  </View>

</TouchableOpacity>
```

```
<View

  accessible={true}

  accessibilityLabel="Pizza"

  accessibilityLanguage="it-IT">

  <Text>🍕</Text>

</View>
```

```
<TouchableWithoutFeedback onPress={addOne}>

  <View style={styles.embedded}>

    <Text>Click me</Text>

  </View>

</TouchableWithoutFeedback>

<Text accessibilityLiveRegion="polite">

  Clicked {count} times

</Text>
```

```
<View

  accessibilityShowsLargeContentViewer={true}

  accessibilityLargeContentTitle="Home Tab">

  <Text>Home</Text>

</View>
```

### `accessibilityState`[​](#accessibilitystate "Direct link to accessibilitystate")

Describes the current state of a component to the assistive technology user.

`accessibilityState` is an object. It contains the following fields:

| Name     | Description                                                                                                                           | Type               | Required |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | -------- |
| disabled | Indicates whether the element is disabled or not.                                                                                     | boolean            | No       |
| selected | Indicates whether a selectable element is currently selected or not.                                                                  | boolean            | No       |
| checked  | Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes. | boolean or 'mixed' | No       |
| busy     | Indicates whether an element is currently busy or not.                                                                                | boolean            | No       |
| expanded | Indicates whether an expandable element is currently expanded or collapsed.                                                           | boolean            | No       |

To use, set the `accessibilityState` to an object with a specific definition.

### `accessibilityValue`[​](#accessibilityvalue "Direct link to accessibilityvalue")

Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, it contains range information (minimum, current, and maximum).

`accessibilityValue` is an object. It contains the following fields:

| Name | Description                                                                                    | Type    | Required                  |
| ---- | ---------------------------------------------------------------------------------------------- | ------- | ------------------------- |
| min  | The minimum value of this component's range.                                                   | integer | Required if `now` is set. |
| max  | The maximum value of this component's range.                                                   | integer | Required if `now` is set. |
| now  | The current value of this component's range.                                                   | integer | No                        |
| text | A textual description of this component's value. Will override `min`, `now`, and `max` if set. | string  | No                        |

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-checked`[​](#aria-checked "Direct link to aria-checked")

Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

| Type             | Default |
| ---------------- | ------- |
| boolean, 'mixed' | false   |

### `aria-disabled`[​](#aria-disabled "Direct link to aria-disabled")

Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-expanded`[​](#aria-expanded "Direct link to aria-expanded")

Indicates whether an expandable element is currently expanded or collapsed.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-hidden`[​](#aria-hidden "Direct link to aria-hidden")

Indicates whether the element is hidden from assistive technologies.

For example, in a window that contains sibling views `A` and `B`, setting `aria-hidden` to `true` on view `B` causes VoiceOver to ignore the `B` element and its children.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-label`[​](#aria-label "Direct link to aria-label")

Defines a string value that can be used to name an element.

| Type   |
| ------ |
| string |

### `aria-labelledby`Android[​](#aria-labelledby-android "Direct link to aria-labelledby-android")

Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the [`nativeID`](/docs/view#nativeid) of the related element:

React TSX

```
<View>

  <Text nativeID="formLabel">Label for Input Field</Text>

  <TextInput aria-label="input" aria-labelledby="formLabel" />

</View>
```

| Type   |
| ------ |
| string |

### `aria-live`Android[​](#aria-live-android "Direct link to aria-live-android")

Indicates that an element will be updated and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

* **off** 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.

| Type                                     | Default |
| ---------------------------------------- | ------- |
| enum(`'assertive'`, `'off'`, `'polite'`) | `'off'` |

***

### `aria-modal`iOS[​](#aria-modal-ios "Direct link to aria-modal-ios")

Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

### `aria-selected`[​](#aria-selected "Direct link to aria-selected")

Indicates whether a selectable element is currently selected or not.

| Type    |
| ------- |
| boolean |

### `experimental_accessibilityOrder`[​](#experimental_accessibilityorder "Direct link to experimental_accessibilityorder")

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

note

For the sake of brevity, layout is excluded in the following examples even though it dictates the default focus order. Assume the document order matches the layout order.

`experimental_accessibilityOrder` lets you define the order in which assistive technologies focus descendant components. It is an array of [`nativeIDs`](/docs/view#nativeid) that are set on the components whose order you are controlling. For example:

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View accessible={true} nativeID="C"/>

</View>
```

Assistive technologies will focus the `View` with `nativeID` of `B`, then `C`, then `A`.

`experimental_accessibilityOrder` will not “turn on” accessibility for the components it references, that still needs to be done. So if we remove `accessible={true}` on `C` above like so

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View nativeID="C"/>

</View>
```

then the new order will be `B` then `A`, even though `C` is still in `experimental_accessibilityOrder`.

`experimental_accessibilityOrder` will “turn off” accessibility of components it doesn’t reference, however.

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View accessible={true} nativeID="C"/>

  <View accessible={true} nativeID="D"/>

</View>
```

The order of the above example would be `B`, `C`, `A`. `D` will never get focused. In this sense `experimental_accessibilityOrder` is *exhaustive*.

There are still valid reasons to include an non-accessible component in `experimental_accessibilityOrder`. Consider

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View nativeID="C">

    <View accessible={true} nativeID="D"/>

    <View accessible={true} nativeID="E"/>

    <View accessible={true} nativeID="F"/>

  </View>

</View>
```

The focus order will be `B`, `D`, `E`, `F`, `A`. Even though `D`, `E`, and `F` are not directly referenced in `experimental_accessibilityOrder`, `C` is directly referenced. In this instance `C` in an *accessibility container* - it contains accessible elements, but is not accessible itself. If an accessibility container is referenced in `experimental_accessibilityOrder` then the default order of the elements it contains is applied. In this sense `experimental_accessibilityOrder` is *nestable*.

`experimental_accessibilityOrder` can also reference another component with `experimental_accessibilityOrder`

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View nativeID="C" experimental_accessibilityOrder={['F', 'E', 'D']}>

    <View accessible={true} nativeID="D"/>

    <View accessible={true} nativeID="E"/>

    <View accessible={true} nativeID="F"/>

  </View>

</View>
```

The focus order will be `B`, `F`, `E`, `D`, `A`.

A component cannot be both an accessibility container and an accessibility element (`accessible={true}`). So if we have

```
<View experimental_accessibilityOrder={['B', 'C', 'A']}>

  <View accessible={true} nativeID="A"/>

  <View accessible={true} nativeID="B"/>

  <View accessible={true} nativeID="C" experimental_accessibilityOrder={['F', 'E', 'D']}>

    <View accessible={true} nativeID="D"/>

    <View accessible={true} nativeID="E"/>

    <View accessible={true} nativeID="F"/>

  </View>

</View>
```

The focus order would be `B`, `C`, `A`. `D`, `E`, and `F` are no longer in a container, so the exhaustive nature of `experimental_accessibilityOrder` means they will be excluded.

### `importantForAccessibility`Android[​](#importantforaccessibility-android "Direct link to 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).

React TSX

```
<View style={styles.container}>

  <View

    style={[styles.layout, {backgroundColor: 'green'}]}

    importantForAccessibility="yes">

    <Text>First layout</Text>

  </View>

  <View

    style={[styles.layout, {backgroundColor: 'yellow'}]}

    importantForAccessibility="no-hide-descendants">

    <Text>Second layout</Text>

  </View>

</View>
```

`role` communicates the purpose of a component and has precedence over the [`accessibilityRole`](/docs/accessibility#accessibilityrole) prop.

| Name  | Type   | Required |
| ----- | ------ | -------- |
| name  | string | Yes      |
| label | string | No       |

```
<View

  accessible={true}

  accessibilityActions={[

    {name: 'cut', label: 'cut'},

    {name: 'copy', label: 'copy'},

    {name: 'paste', label: 'paste'},

  ]}

  onAccessibilityAction={event => {

    switch (event.nativeEvent.actionName) {

      case 'cut':

        Alert.alert('Alert', 'cut action success');

        break;

      case 'copy':

        Alert.alert('Alert', 'copy action success');

        break;

      case 'paste':

        Alert.alert('Alert', 'paste action success');

        break;

    }

  }}

/>
```

## Checking if a Screen Reader is Enabled[​](#checking-if-a-screen-reader-is-enabled "Direct link to Checking if a Screen Reader is Enabled")

The `AccessibilityInfo` API allows you to determine whether or not a screen reader is currently active. See the [AccessibilityInfo documentation](/docs/accessibilityinfo) for details.

## Sending Accessibility EventsAndroid[​](#sending-accessibility-events-android "Direct link to sending-accessibility-events-android")

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`.

React TSX

```
import {Platform, UIManager, findNodeHandle} from 'react-native';



if (Platform.OS === 'android') {

  UIManager.sendAccessibilityEvent(

    findNodeHandle(this),

    UIManager.AccessibilityEventTypes.typeViewFocused,

  );

}
```

## Testing TalkBack SupportAndroid[​](#testing-talkback-support-android "Direct link to testing-talkback-support-android")

To enable TalkBack, go to the Settings app on your Android device or emulator. Tap Accessibility, then TalkBack. Toggle the "Use service" switch to enable or disable it.

Android emulators don't have TalkBack installed by default. You can install TalkBack on your emulator via the Google Play Store. Make sure to choose an emulator with the Google Play store installed. These are available in Android Studio.

You can use the volume key shortcut to toggle TalkBack. To turn on the volume key shortcut, go to the Settings app, then Accessibility. At the top, turn on the volume key shortcut.

To use the volume key shortcut, press both volume keys for 3 seconds to start an accessibility tool.

Additionally, if you prefer, you can toggle TalkBack via the command line with:

```
# disable

adb shell settings put secure enabled_accessibility_services com.android.talkback/com.google.android.marvin.talkback.TalkBackService



# enable

adb shell settings put secure enabled_accessibility_services com.google.android.marvin.talkback/com.google.android.marvin.talkback.TalkBackService
```

    [Android](#accessibilitylabelledby-android)
  * [`accessibilityHint`](#accessibilityhint)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)
  * [`accessibilityIgnoresInvertColors`](#accessibilityignoresinvertcolors-ios)

    [iOS](#accessibilityignoresinvertcolors-ios)
  * [`accessibilityLiveRegion`](#accessibilityliveregion-android)

    [Android](#accessibilityliveregion-android)
  * [`accessibilityRole`](#accessibilityrole)
  * [`accessibilityShowsLargeContentViewer`](#accessibilityshowslargecontentviewer-ios)

    [iOS](#accessibilityshowslargecontentviewer-ios)
  * [`accessibilityLargeContentTitle`](#accessibilitylargecontenttitle-ios)

    [iOS](#accessibilitylargecontenttitle-ios)
  * [`accessibilityState`](#accessibilitystate)
  * [`accessibilityValue`](#accessibilityvalue)
  * [`accessibilityViewIsModal`](#accessibilityviewismodal-ios)

    [iOS](#accessibilityviewismodal-ios)
  * [`accessibilityElementsHidden`](#accessibilityelementshidden-ios)

    [iOS](#accessibilityelementshidden-ios)

    [Android](#aria-labelledby-android)
  * [`aria-live`](#aria-live-android)

    [Android](#aria-live-android)
  * [`aria-modal`](#aria-modal-ios)

    [iOS](#aria-modal-ios)
  * [`aria-selected`](#aria-selected)
  * [`experimental_accessibilityOrder`](#experimental_accessibilityorder)
  * [`importantForAccessibility`](#importantforaccessibility-android)

    [Android](#importantforaccessibility-android)
  * [`onAccessibilityEscape`](#onaccessibilityescape-ios)

    [iOS](#onaccessibilityescape-ios)
  * [`onAccessibilityTap`](#onaccessibilitytap-ios)

    [iOS](#onaccessibilitytap-ios)
  * [`onMagicTap`](#onmagictap-ios)

    [iOS](#onmagictap-ios)

----
url: https://reactnative.dev/docs/next/react-node
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/react-node)** (0.87).

Version: Next

----
url: https://reactnative.dev/docs/global-cancelAnimationFrame
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame) for more information.

The global `cancelAnimationFrame` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/running-on-device
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/running-on-device)** (0.87).

Version: Next

```
$ adb devices

List of devices attached

emulator-5554 offline   # Google emulator

14ed2fcc device         # Physical device
```

```
npm run android
```

```
yarn android
```

note

If you get a "bridge configuration isn't available" error, see [Using adb reverse](/docs/next/running-on-device#method-1-using-adb-reverse-recommended).

```
$ adb -s <device name> reverse tcp:8081 tcp:8081
```

To find the device name, run the following adb command:

```
$ adb devices
```

You can now enable Fast Refresh from the [Dev Menu](/docs/next/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

### Method 2: Connect via Wi-Fi[​](#method-2-connect-via-wi-fi "Direct link to Method 2: Connect via Wi-Fi")

You can also connect to the development server over Wi-Fi. You'll first need to install the app on your device using a USB cable, but once that has been done you can debug wirelessly by following these instructions. You'll need your development machine's current IP address before proceeding.

You can find the IP address in **System Settings (or System Preferences)** → **Network**.

1. Make sure your laptop and your phone are on the **same** Wi-Fi network.
2. Open your React Native app on your device.
3. You'll see a [red screen with an error](/docs/next/debugging#logbox). This is OK. The following steps will fix that.
4. Open the in-app [Dev Menu](/docs/next/debugging#opening-the-dev-menu).
5. Go to **Dev Settings** → **Debug server host & port for device**.
6. Type in your machine's IP address and the port of the local dev server (e.g. `10.0.1.1:8081`).
7. Go back to the **Dev Menu** and select **Reload JS**.

You can now enable Fast Refresh from the [Dev Menu](/docs/next/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

## Building your app for production[​](#building-your-app-for-production "Direct link to Building your app for production")

You have built a great app using React Native, and you are now itching to release it in the Play Store. The process is the same as any other native Android app, with some additional considerations to take into account. Follow the guide for [generating a signed APK](/docs/next/signed-apk-android) to learn more.

### 1. Enable Debugging over USB[​](#1-enable-debugging-over-usb-1 "Direct link to 1. Enable Debugging over USB")

Most Android devices can only install and run apps downloaded from Google Play, by default. You will need to enable USB Debugging on your device in order to install your app during development.

To enable USB debugging on your device, you will first need to enable the "Developer options" menu by going to **Settings** → **About phone** → **Software information** and then tapping the `Build number` row at the bottom seven times. You can then go back to **Settings** → **Developer options** to enable "USB debugging".

### 2. Plug in your device via USB[​](#2-plug-in-your-device-via-usb-1 "Direct link to 2. Plug in your device via USB")

Let's now set up an Android device to run our React Native projects. Go ahead and plug in your device via USB to your development machine.

Now check that your device is properly connecting to ADB, the Android Debug Bridge, by running `adb devices`.

```
$ adb devices

List of devices attached

emulator-5554 offline   # Google emulator

14ed2fcc device         # Physical device
```

Seeing `device` in the right column means the device is connected. You must have **only one device connected** at a time.

### 3. Run your app[​](#3-run-your-app-1 "Direct link to 3. Run your app")

From the root of your project, run the following in your command prompt to install and launch your app on the device:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

```
$ adb -s <device name> reverse tcp:8081 tcp:8081
```

To find the device name, run the following adb command:

```
$ adb devices
```

You can now enable Fast Refresh from the [Dev Menu](/docs/next/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

### Method 2: Connect via Wi-Fi[​](#method-2-connect-via-wi-fi-1 "Direct link to Method 2: Connect via Wi-Fi")

You can also connect to the development server over Wi-Fi. You'll first need to install the app on your device using a USB cable, but once that has been done you can debug wirelessly by following these instructions. You'll need your development machine's current IP address before proceeding.

Open the command prompt and type `ipconfig` to find your machine's IP address ([more info](https://windows.microsoft.com/en-us/windows/using-command-line-tools-networking-information)).

1. Make sure your laptop and your phone are on the **same** Wi-Fi network.
2. Open your React Native app on your device.
3. You'll see a [red screen with an error](/docs/next/debugging#logbox). This is OK. The following steps will fix that.
4. Open the in-app [Dev Menu](/docs/next/debugging#opening-the-dev-menu).
5. Go to **Dev Settings** → **Debug server host & port for device**.
6. Type in your machine's IP address and the port of the local dev server (e.g. `10.0.1.1:8081`).
7. Go back to the **Dev Menu** and select **Reload JS**.

You can now enable Fast Refresh from the [Dev Menu](/docs/next/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

## Building your app for production[​](#building-your-app-for-production-1 "Direct link to Building your app for production")

You have built a great app using React Native, and you are now itching to release it in the Play Store. The process is the same as any other native Android app, with some additional considerations to take into account. Follow the guide for [generating a signed APK](/docs/next/signed-apk-android) to learn more.

### 1. Enable Debugging over USB[​](#1-enable-debugging-over-usb-2 "Direct link to 1. Enable Debugging over USB")

Most Android devices can only install and run apps downloaded from Google Play, by default. You will need to enable USB Debugging on your device in order to install your app during development.

To enable USB debugging on your device, you will first need to enable the "Developer options" menu by going to **Settings** → **About phone** → **Software information** and then tapping the `Build number` row at the bottom seven times. You can then go back to **Settings** → **Developer options** to enable "USB debugging".

### 2. Plug in your device via USB[​](#2-plug-in-your-device-via-usb-2 "Direct link to 2. Plug in your device via USB")

Let's now set up an Android device to run our React Native projects. Go ahead and plug in your device via USB to your development machine.

Next, check the manufacturer code by using `lsusb` (on mac, you must first [install lsusb](https://github.com/jlhonora/lsusb)). `lsusb` should output something like this:

```
$ lsusb

Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub

Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 001 Device 003: ID 22b8:2e76 Motorola PCS

Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub

Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub

Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
```

These lines represent the USB devices currently connected to your machine.

You want the line that represents your phone. If you're in doubt, try unplugging your phone and running the command again:

```
$ lsusb

Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub

Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub

Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub

Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
```

You'll see that after removing the phone, the line which has the phone model ("Motorola PCS" in this case) disappeared from the list. This is the line that we care about.

`Bus 001 Device 003: ID 22b8:2e76 Motorola PCS`

From the above line, you want to grab the first four digits from the device ID:

`22b8:2e76`

In this case, it's `22b8`. That's the identifier for Motorola.

You'll need to input this into your udev rules in order to get up and running:

```
echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", MODE="0666", GROUP="plugdev"' | sudo tee /etc/udev/rules.d/51-android-usb.rules
```

Make sure that you replace `22b8` with the identifier you get in the above command.

Now check that your device is properly connecting to ADB, the Android Debug Bridge, by running `adb devices`.

```
$ adb devices

List of devices attached

emulator-5554 offline   # Google emulator

14ed2fcc device         # Physical device
```

Seeing `device` in the right column means the device is connected. You must have **only one device connected** at a time.

### 3. Run your app[​](#3-run-your-app-2 "Direct link to 3. Run your app")

From the root of your project, type the following in your command prompt to install and launch your app on the device:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

note

If you get a "bridge configuration isn't available" error, see [Using adb reverse](/docs/next/running-on-device#method-1-using-adb-reverse-recommended).

```
$ adb -s <device name> reverse tcp:8081 tcp:8081
```

To find the device name, run the following adb command:

```
$ adb devices
```

You can now enable Fast Refresh from the [Dev Menu](/docs/next/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

### Method 2: Connect via Wi-Fi[​](#method-2-connect-via-wi-fi-2 "Direct link to Method 2: Connect via Wi-Fi")

You can also connect to the development server over Wi-Fi. You'll first need to install the app on your device using a USB cable, but once that has been done you can debug wirelessly by following these instructions. You'll need your development machine's current IP address before proceeding.

Open a terminal and type `/sbin/ifconfig` to find your machine's IP address.

1. Make sure your laptop and your phone are on the **same** Wi-Fi network.
2. Open your React Native app on your device.
3. You'll see a [red screen with an error](/docs/next/debugging#logbox). This is OK. The following steps will fix that.
4. Open the in-app [Dev Menu](/docs/next/debugging#opening-the-dev-menu).
5. Go to **Dev Settings** → **Debug server host & port for device**.
6. Type in your machine's IP address and the port of the local dev server (e.g. `10.0.1.1:8081`).
7. Go back to the **Dev Menu** and select **Reload JS**.

You can now enable Fast Refresh from the [Dev Menu](/docs/next/debugging#opening-the-dev-menu). Your app will reload whenever your JavaScript code has changed.

## Building your app for production[​](#building-your-app-for-production-2 "Direct link to Building your app for production")

You have built a great app using React Native, and you are now itching to release it in the Play Store. The process is the same as any other native Android app, with some additional considerations to take into account. Follow the guide for [generating a signed APK](/docs/next/signed-apk-android) to learn more.

You can also iterate quickly on a device using the development server. You only have to be on the same Wi-Fi network as your computer. Shake your device to open the [Dev Menu](/docs/next/debugging#opening-the-dev-menu), then enable Fast Refresh. Your app will reload whenever your JavaScript code has changed.

### Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting")

tip

If you have any issues, ensure that your Mac and device are on the same network and can reach each other. Many open wireless networks with captive portals are configured to prevent devices from reaching other devices on the network. You may use your device's Personal Hotspot feature in this case. You may also share your internet (Wi-Fi/Ethernet) connection from your Mac to your device via USB and connect to the bundler through this tunnel for very high transfer speeds.

When trying to connect to the development server you might get a [red screen with an error](/docs/next/debugging#logbox) saying:

You have built a great app using React Native, and you are now itching to release it in the App Store. The process is the same as any other native iOS app, with some additional considerations to take into account. Follow the guide for [publishing to the Apple App Store](/docs/next/publishing-to-app-store) to learn more.

info

A Mac is required in order to build your app for iOS devices. Alternatively, you can refer to our [environment setup guide](/docs/next/environment-setup) to learn how to build your app using Expo CLI, which will allow you to run your app using the Expo client app.

info

A Mac is required in order to build your app for iOS devices. Alternatively, you can refer to our [environment setup guide](/docs/next/environment-setup) to learn how to build your app using Expo CLI, which will allow you to run your app using the Expo client app.

----
url: https://reactnative.dev/docs/next/global-fetch
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-fetch)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) for more information.

The global `fetch` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/datepickerandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=datepicker) instead.

----
url: https://reactnative.dev/docs/next/getting-started
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/getting-started)** (0.87).

Version: Next

Welcome to the very start of your React Native journey! If you're looking for getting started instructions, they've moved to [their own section](environment-setup). Continue reading for an introduction to the documentation, Native Components, React, and more!

Many different kinds of people use React Native: from advanced iOS developers to React beginners, to people getting started programming for the first time in their career. These docs were written for all learners, no matter their experience level or background.

## How to use these docs[​](#how-to-use-these-docs "Direct link to How to use these docs")

You can start here and read through these docs linearly like a book; or you can read the specific sections you need. Already familiar with React? You can skip [that section](/docs/next/intro-react)—or read it for a light refresher.

Optionally, if you want to set up a local development environment, [you can follow our guide to setting up your environment on your local machine](/docs/next/set-up-your-environment) and paste the code examples into your project. (If you are a web developer, you may already have a local environment set up for mobile browser testing!)

***

Now that you know how this guide works, it's time to get to know the foundation of React Native: [Native Components](/docs/next/intro-react-native-components).

* [How to use these docs](#how-to-use-these-docs)
* [Prerequisites](#prerequisites)
* [Interactive examples](#interactive-examples)
* [Developer Notes](#developer-notes)
* [Formatting](#formatting)

----
url: https://reactnative.dev/docs/next/asyncstorage
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/asyncstorage)** (0.87).

Version: Next

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=storage) instead.

----
url: https://reactnative.dev/docs/global-process
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress.

The global `process` object, as defined in Node.js.

----
url: https://reactnative.dev/docs/next/targetevent
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/targetevent)** (0.87).

Version: Next

`TargetEvent` object is returned in the callback as a result of focus change, for example `onFocus` or `onBlur` in the [TextInput](/docs/next/textinput) component.

## Example[​](#example "Direct link to Example")

```
{

    target: 1127

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `target`[​](#target "Direct link to target")

The node id of the element receiving the TargetEvent.

| Type                        | Optional |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

## Used by[​](#used-by "Direct link to Used by")

* [`TextInput`](/docs/next/textinput)
* [`TouchableWithoutFeedback`](/docs/next/touchablewithoutfeedback)

- [Example](#example)
- [Keys and values](#keys-and-values)
  * [`target`](#target)
- [Used by](#used-by)

----
url: https://reactnative.dev/docs/global-self
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

[`self`](https://developer.mozilla.org/en-US/docs/Web/API/Window/self) is an alias for [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), as defined in Web specifications.

The use of `globalThis` is recommended over `self`.

----
url: https://reactnative.dev/docs/document-nodes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Document nodes represent a complete native view tree. Apps using native navigation would provide a separate document node for each screen. Apps not using native navigation would generally provide a single document for the whole app (similar to single-page apps on Web).

***

----
url: https://reactnative.dev/docs/publishing-to-app-store
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
 if [ "${CONFIGURATION}" == "Debug" ]; then

  export SKIP_BUNDLING=true

 fi
```

----
url: https://reactnative.dev/docs/global-FormData
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/FormData) for more information.

The global `FormData` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/viewtoken
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/viewtoken)** (0.87).

Version: Next

`ViewToken` object is returned as one of the properties in the `onViewableItemsChanged` callback (for example, in the [FlatList](/docs/next/flatlist) component). It is exported by [`ViewabilityHelper.js`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Lists/ViewabilityHelper.js).

## Example[​](#example "Direct link to Example")

JavaScript

```
{

  item: {key: "key-12"},

  key: "key-12",

  index: 11,

  isViewable: true

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `index`[​](#index "Direct link to index")

Unique numeric identifier assigned to the data element.

This property may be `null` when the viewable element is not an item from the data array, for example when a section header or section footer becomes viewable in [`SectionList`](/docs/next/sectionlist).

| Type   | Optional |
| ------ | -------- |
| number | Yes      |

### `isViewable`[​](#isviewable "Direct link to isviewable")

Specifies if at least some part of list element is visible in the viewport.

| Type    | Optional |
| ------- | -------- |
| boolean | No       |

### `item`[​](#item "Direct link to item")

Item data

| Type | Optional |
| ---- | -------- |
| any  | No       |

### `key`[​](#key "Direct link to key")

Key identifier assigned to the data element extracted to the top level.

| Type   | Optional |
| ------ | -------- |
| string | No       |

### `section`[​](#section "Direct link to section")

Item section data when used with `SectionList`.

| Type | Optional |
| ---- | -------- |
| any  | Yes      |

## Used by[​](#used-by "Direct link to Used by")

* [`FlatList`](/docs/next/flatlist)
* [`SectionList`](/docs/next/sectionlist)
* [`VirtualizedList`](/docs/next/virtualizedlist)

----
url: https://reactnative.dev/docs/next/tutorial
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/tutorial)** (0.87).

Version: Next

The first style that we find is `flex: 1`, the [`flex`](/docs/next/layout-props#flex) prop will define how your items are going to "fill" over the available space along your main axis. Since we only have one container, it will take all the available space of the parent component. In this case, it is the only component, so it will take all the available screen space.

The following style is [`justifyContent`](/docs/next/layout-props#justifycontent): "center". This aligns children of a container in the center of the container's main axis. Finally, we have [`alignItems`](/docs/next/layout-props#alignitems): "center", which aligns children of a container in the center of the container's cross axis.

Some of the things in here might not look like JavaScript to you. Don't panic. *This is the future*.

First of all, ES2015 (also known as ES6) is a set of improvements to JavaScript that is now part of the official standard, but not yet supported by all browsers, so often it isn't used yet in web development. React Native ships with ES2015 support, so you can use this stuff without worrying about compatibility. `import`, `export`, `const` and `from` in the example above are all ES2015 features. If you aren't familiar with ES2015, you can probably pick it up by reading through sample code like this tutorial has. If you want, [this page](https://babeljs.io/learn-es2015/) has a good overview of ES2015 features.

The other unusual thing in this code example is `<View><Text>Hello world!</Text></View>`. This is JSX - a syntax for embedding XML within JavaScript. Many frameworks use a specialized templating language which lets you embed code inside markup language. In React, this is reversed. JSX lets you write your markup language inside code. It looks like HTML on the web, except instead of web things like `<div>` or `<span>`, you use React components. In this case, `<Text>` is a [Core Component](/docs/next/intro-react-native-components) that displays some text and `View` is like the `<div>` or `<span>`.

The other new thing going on here is the [`View`](/docs/next/view) component. A [`View`](/docs/next/view) is useful as a container for other components, to help control style and layout.

With `props` and the basic [`Text`](/docs/next/text), [`Image`](/docs/next/image), and [`View`](/docs/next/view) components, you can build a wide variety of static screens. To learn how to make your app change over time, you need to [learn about State](#state).

## State[​](#state "Direct link to State")

Unlike props [that are read-only](https://react.dev/reference/react/Component#props) and should not be modified, the `state` allows React components to change their output over time in response to user actions, network responses and anything else.

#### What's the difference between state and props in React?[​](#whats-the-difference-between-state-and-props-in-react "Direct link to What's the difference between state and props in React?")

In a React component, the props are the variables that we pass from a parent component to a child component. Similarly, the state are also variables, with the difference that they are not passed as parameters, but rather that the component initializes and manages them internally.

#### Are there differences between React and React Native to handle the state?[​](#are-there-differences-between-react-and-react-native-to-handle-the-state "Direct link to Are there differences between React and React Native to handle the state?")

React TSX

```
// React Counter Example using Hooks!



import {useState} from 'react';







const App = () => {

  const [count, setCount] = useState(0);



  return (

    <div className="container">

      <p>You clicked {count} times</p>

      <button

        onClick={() => setCount(count + 1)}>

        Click me!

      </button>

    </div>

  );

};





// CSS

.container {

  display: flex;

  justify-content: center;

  align-items: center;

}
```

React TSX

```
// React Native Counter Example using Hooks!



import {useState} from 'react';

import {View, Text, Button, StyleSheet} from 'react-native';



const App = () => {

  const [count, setCount] = useState(0);



  return (

    <View style={styles.container}>

      <Text>You clicked {count} times</Text>

      <Button

        onPress={() => setCount(count + 1)}

        title="Click me!"

      />

    </View>

  );

};



// React Native Styles

const styles = StyleSheet.create({

  container: {

    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

  },

});
```

----
url: https://reactnative.dev/docs/activityindicator
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Displays a circular loading indicator.

## Example[​](#example "Direct link to Example")

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### `animating`[​](#animating "Direct link to animating")

Whether to show the indicator (`true`) or hide it (`false`).

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `color`[​](#color "Direct link to color")

The foreground color of the spinner.

| Type                  | Default                                                      |
| --------------------- | ------------------------------------------------------------ |
| [color](/docs/colors) | `null` (system accent default color)Android***`'#999999'`iOS |

***

### `hidesWhenStopped`iOS[​](#hideswhenstopped-ios "Direct link to hideswhenstopped-ios")

Whether the indicator should hide when not animating.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/element-nodes) when mounted.

***

### `size`[​](#size "Direct link to size")

Size of the indicator.

| Type                                       | Default   |
| ------------------------------------------ | --------- |
| enum(`'small'`, `'large'`)***numberAndroid | `'small'` |

* [Example](#example)

* [Props](#props)

  * [View Props](#view-props)
  * [`animating`](#animating)
  * [`color`](#color)
  * [`hidesWhenStopped`](#hideswhenstopped-ios)

    [iOS](#hideswhenstopped-ios)
  * [`ref`](#ref)
  * [`size`](#size)

----
url: https://reactnative.dev/docs/next/view
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/view)** (0.87).

Version: Next

The most fundamental component for building a UI, `View` is a container that supports layout with [flexbox](/docs/next/flexbox), [style](/docs/next/style), [some touch handling](/docs/next/handling-touches), and [accessibility](/docs/next/accessibility) controls. `View` maps directly to the native view equivalent on whatever platform React Native is running on, whether that is a `UIView`, `<div>`, `android.view`, etc.

`View` is designed to be nested inside other views and can have 0 to many children of any type.

This example creates a `View` that wraps two boxes with color and a text component in a row with padding.

note

`View`s are designed to be used with [`StyleSheet`](/docs/next/style) for clarity and performance, although inline styles are also supported.

### Synthetic Touch Events[​](#synthetic-touch-events "Direct link to Synthetic Touch Events")

For `View` responder props (e.g., `onResponderMove`), the synthetic touch event passed to them are in form of [PressEvent](/docs/next/pressevent).

***

# Reference

## Props[​](#props "Direct link to Props")

***

### `accessibilityActions`[​](#accessibilityactions "Direct link to accessibilityactions")

Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The `accessibilityActions` property should contain a list of action objects. Each action object should contain the field name and label.

See the [Accessibility guide](/docs/next/accessibility#accessibility-actions) for more information.

| Type  |
| ----- |
| array |

***

### `accessibilityElementsHidden`iOS[​](#accessibilityelementshidden-ios "Direct link to accessibilityelementshidden-ios")

A boolean value indicating whether the given accessibility element, and any accessibility elements it contains, are hidden. Default is `false`.

See the [Accessibility guide](/docs/next/accessibility#accessibilityelementshidden-ios) for more information.

| Type |
| ---- |
| bool |

***

### `accessibilityHint`[​](#accessibilityhint "Direct link to accessibilityhint")

An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label.

| Type   |
| ------ |
| string |

***

### `accessibilityLanguage`iOS[​](#accessibilitylanguage-ios "Direct link to accessibilitylanguage-ios")

A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the [BCP 47 specification](https://www.rfc-editor.org/info/bcp47).

See the [iOS `accessibilityLanguage` doc](https://developer.apple.com/documentation/objectivec/nsobject/1615192-accessibilitylanguage) for more information.

| Type   |
| ------ |
| string |

***

### `accessibilityIgnoresInvertColors`iOS[​](#accessibilityignoresinvertcolors-ios "Direct link to accessibilityignoresinvertcolors-ios")

A value indicating this view should or should not be inverted when color inversion is turned on. A value of `true` will tell the view to not be inverted even if color inversion is turned on.

See the [Accessibility guide](/docs/next/accessibility#accessibilityignoresinvertcolors-ios) for more information.

| Type |
| ---- |
| bool |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the `Text` nodes separated by space.

| Type   |
| ------ |
| string |

***

### `accessibilityLiveRegion`Android[​](#accessibilityliveregion-android "Direct link to accessibilityliveregion-android")

Indicates to accessibility services whether the user should be notified when this view changes. Works for Android API >= 19 only. Possible values:

* `'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.

See the [Android `View` docs](https://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion) for reference.

| Type                                |
| ----------------------------------- |
| enum('none', 'polite', 'assertive') |

***

| Type   |
| ------ |
| string |

***

### `accessibilityState`[​](#accessibilitystate "Direct link to accessibilitystate")

Describes the current state of a component to the user of an assistive technology.

See the [Accessibility guide](/docs/next/accessibility#accessibilitystate) for more information.

| Type                                                                                             |
| ------------------------------------------------------------------------------------------------ |
| object: `{disabled: bool, selected: bool, checked: bool or 'mixed', busy: bool, expanded: bool}` |

***

### `accessibilityValue`[​](#accessibilityvalue "Direct link to accessibilityvalue")

Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, it contains range information (minimum, current, and maximum).

See the [Accessibility guide](/docs/next/accessibility#accessibilityvalue) for more information.

| Type                                                            |
| --------------------------------------------------------------- |
| object: `{min: number, max: number, now: number, text: string}` |

***

### `accessibilityViewIsModal`iOS[​](#accessibilityviewismodal-ios "Direct link to accessibilityviewismodal-ios")

A value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. Default is `false`.

See the [Accessibility guide](/docs/next/accessibility#accessibilityviewismodal-ios) for more information.

| Type |
| ---- |
| bool |

***

### `accessible`[​](#accessible "Direct link to accessible")

When `true`, indicates that the view is an accessibility element and discoverable by assistive technologies such as screen readers and hardware keyboards. By default, all the touchable elements are accessible.

See the [Accessibility guide](/docs/next/accessibility#accessible) for more information.

***

### `aria-busy`[​](#aria-busy "Direct link to aria-busy")

Indicates an element is being modified and that assistive technologies may want to wait until the changes are complete before informing the user about the update.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-checked`[​](#aria-checked "Direct link to aria-checked")

Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

| Type             | Default |
| ---------------- | ------- |
| boolean, 'mixed' | false   |

***

### `aria-disabled`[​](#aria-disabled "Direct link to aria-disabled")

Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-expanded`[​](#aria-expanded "Direct link to aria-expanded")

Indicates whether an expandable element is currently expanded or collapsed.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-hidden`[​](#aria-hidden "Direct link to aria-hidden")

Indicates whether the element is hidden from assistive technologies.

For example, in a window that contains sibling views `A` and `B`, setting `aria-hidden` to `true` on view `B` causes VoiceOver to ignore the `B` element and its children.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-label`[​](#aria-label "Direct link to aria-label")

Defines a string value that labels an interactive element.

| Type   |
| ------ |
| string |

***

### `aria-labelledby`Android[​](#aria-labelledby-android "Direct link to aria-labelledby-android")

Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the [`nativeID`](/docs/next/view#nativeid) of the related element:

React TSX

```
<View>

  <Text nativeID="formLabel">Label for Input Field</Text>

  <TextInput aria-label="input" aria-labelledby="formLabel" />

</View>
```

| Type   |
| ------ |
| string |

***

### `aria-live`Android[​](#aria-live-android "Direct link to aria-live-android")

Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

* **off** 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.

| Type                                     | Default |
| ---------------------------------------- | ------- |
| enum(`'assertive'`, `'off'`, `'polite'`) | `'off'` |

***

### `aria-modal`iOS[​](#aria-modal-ios "Direct link to aria-modal-ios")

Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. Has precedence over the [`accessibilityViewIsModal`](#accessibilityviewismodal-ios) prop.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-selected`[​](#aria-selected "Direct link to aria-selected")

Indicates whether a selectable element is currently selected or not.

| Type    |
| ------- |
| boolean |

### `aria-valuemax`[​](#aria-valuemax "Direct link to aria-valuemax")

Represents the maximum value for range-based components, such as sliders and progress bars. Has precedence over the `max` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuemin`[​](#aria-valuemin "Direct link to aria-valuemin")

Represents the minimum value for range-based components, such as sliders and progress bars. Has precedence over the `min` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuenow`[​](#aria-valuenow "Direct link to aria-valuenow")

Represents the current value for range-based components, such as sliders and progress bars. Has precedence over the `now` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuetext`[​](#aria-valuetext "Direct link to aria-valuetext")

Represents the textual description of the component. Has precedence over the `text` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| string |

***

### `collapsable`[​](#collapsable "Direct link to collapsable")

Views that are only used to layout their children or otherwise don't draw anything may be automatically removed from the native hierarchy as an optimization. Set this property to `false` to disable this optimization and ensure that this `View` exists in the native view hierarchy.

| Type    | Default |
| ------- | ------- |
| boolean | true    |

***

### `collapsableChildren`[​](#collapsablechildren "Direct link to collapsablechildren")

Setting to false prevents direct children of the view from being removed from the native view hierarchy, similar to the effect of setting `collapsable={false}` on each child.

| Type    | Default |
| ------- | ------- |
| boolean | true    |

***

### `experimental_accessibilityOrder`[​](#experimental_accessibilityorder "Direct link to experimental_accessibilityorder")

Experimental 🧪

**This API is experimental.** Experimental APIs may contain bugs and are likely to change in a future version of React Native. Don't use them in production.

`experimental_accessibilityOrder` indicates the order in which an assistive technology focuses descendants of this `View`. This prop takes an array of strings where each string is a [`nativeID`](/docs/next/view#nativeid) of some descendant component whose order is being defined. This prop does not enable accessibility itself, each referenced component still needs to be accessible by setting [`accessible`](/docs/next/view#accessible) to true. This prop is both **nestable** and **exhaustive** meaning

* If `experimental_accessibilityOrder` contains a reference to some non-accessible component, it will focus the descendants of that component in the default order. Additionally, it can also contain a reference to other components that also have an `experimental_accessibilityOrder`.
* If some component that is otherwise accessible is not directly referenced in `experimental_accessibilityOrder`, or nested within some container directly referenced in `experimental_accessibilityOrder`, then it will not be accessible.

See the [accessibility guide](/docs/next/accessibility#experimental_accessibilityorder) for more information.

| Type             |
| ---------------- |
| array of strings |

***

### `focusable`Android[​](#focusable-android "Direct link to focusable-android")

Whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard.

| Type    |
| ------- |
| boolean |

***

### `hitSlop`[​](#hitslop "Direct link to hitslop")

This defines how far a touch event can start away from the view. Typical interface guidelines recommend touch targets that are at least 30 - 40 points/density-independent pixels.

For example, if a touchable view has a height of 20 the touchable height can be extended to 40 with `hitSlop={{top: 10, bottom: 10, left: 0, right: 0}}`

note

The touch area never extends past the parent view bounds, and the Z-index of sibling views always takes precedence if a touch hits two overlapping views.

| Type                                                                 |
| -------------------------------------------------------------------- |
| object: `{top: number, left: number, bottom: number, right: number}` |

***

### `id`[​](#id "Direct link to id")

Used to locate this view from native classes. Has precedence over `nativeID` prop.

warning

This disables the 'layout-only view removal' optimization for this view!

| Type   |
| ------ |
| string |

***

| Type                                             |
| ------------------------------------------------ |
| enum('auto', 'yes', 'no', 'no-hide-descendants') |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

Used to locate this view from native classes.

warning

This disables the 'layout-only view removal' optimization for this view!

| Type   |
| ------ |
| string |

***

### `needsOffscreenAlphaCompositing`[​](#needsoffscreenalphacompositing "Direct link to needsoffscreenalphacompositing")

Whether this `View` needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior. The default (`false`) falls back to drawing the component and its children with an alpha applied to the paint used to draw each element instead of rendering the full component offscreen and compositing it back with an alpha value. This default may be noticeable and undesired in the case where the `View` you are setting an opacity on has multiple overlapping elements (e.g. multiple overlapping `View`s, or text and a background).

Rendering offscreen to preserve correct alpha behavior is extremely expensive and hard to debug for non-native developers, which is why it is not turned on by default. If you do need to enable this property for an animation, consider combining it with renderToHardwareTextureAndroid if the view **contents** are static (i.e. it doesn't need to be redrawn each frame). If that property is enabled, this View will be rendered off-screen once, saved in a hardware texture, and then composited onto the screen with an alpha each frame without having to switch rendering targets on the GPU.

| Type |
| ---- |
| bool |

***

### `nextFocusDown`Android[​](#nextfocusdown-android "Direct link to nextfocusdown-android")

Designates the next view to receive focus when the user navigates down. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusDown).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`Android[​](#nextfocusforward-android "Direct link to nextfocusforward-android")

Designates the next view to receive focus when the user navigates forward. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusForward).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`Android[​](#nextfocusleft-android "Direct link to nextfocusleft-android")

Designates the next view to receive focus when the user navigates left. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusLeft).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`Android[​](#nextfocusright-android "Direct link to nextfocusright-android")

Designates the next view to receive focus when the user navigates right. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusRight).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`Android[​](#nextfocusup-android "Direct link to nextfocusup-android")

Designates the next view to receive focus when the user navigates up. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusUp).

| Type   |
| ------ |
| number |

***

### `onAccessibilityAction`[​](#onaccessibilityaction "Direct link to onaccessibilityaction")

Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

See the [Accessibility guide](/docs/next/accessibility#accessibility-actions) for more information.

| Type     |
| -------- |
| function |

***

### `onAccessibilityEscape`iOS[​](#onaccessibilityescape-ios "Direct link to onaccessibilityescape-ios")

When `accessible` is `true`, the system will invoke this function when the user performs the escape gesture.

| Type     |
| -------- |
| function |

***

### `onAccessibilityTap`iOS[​](#onaccessibilitytap-ios "Direct link to onaccessibilitytap-ios")

When `accessible` is true, the system will try to invoke this function when the user performs accessibility tap gesture.

| Type     |
| -------- |
| function |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

This event is fired immediately once the layout has been calculated, but the new layout may not yet be reflected on the screen at the time the event is received, especially if a layout animation is in progress.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: LayoutEvent}) => void` |

***

### `onMagicTap`iOS[​](#onmagictap-ios "Direct link to onmagictap-ios")

When `accessible` is `true`, the system will invoke this function when the user performs the magic tap gesture.

| Type     |
| -------- |
| function |

***

### `onMoveShouldSetResponder`[​](#onmoveshouldsetresponder "Direct link to onmoveshouldsetresponder")

Does this view want to "claim" touch responsiveness? This is called for every touch move on the `View` when it is not the responder.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onMoveShouldSetResponderCapture`[​](#onmoveshouldsetrespondercapture "Direct link to onmoveshouldsetrespondercapture")

If a parent `View` wants to prevent a child `View` from becoming responder on a move, it should have this handler which returns `true`.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onResponderGrant`[​](#onrespondergrant "Direct link to onrespondergrant")

The View is now responding for touch events. This is the time to highlight and show the user what is happening.

On Android, return true from this callback to prevent any other native components from becoming responder until this responder terminates.

| Type                                            |
| ----------------------------------------------- |
| `({nativeEvent: PressEvent}) => void ｜ boolean` |

***

### `onResponderMove`[​](#onrespondermove "Direct link to onrespondermove")

The user is moving their finger.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderReject`[​](#onresponderreject "Direct link to onresponderreject")

Another responder is already active and will not release it to that `View` asking to be the responder.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderRelease`[​](#onresponderrelease "Direct link to onresponderrelease")

Fired at the end of the touch.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderTerminate`[​](#onresponderterminate "Direct link to onresponderterminate")

The responder has been taken from the `View`. Might be taken by other views after a call to `onResponderTerminationRequest`, or might be taken by the OS without asking (e.g., happens with control center/ notification center on iOS)

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderTerminationRequest`[​](#onresponderterminationrequest "Direct link to onresponderterminationrequest")

Some other `View` wants to become responder and is asking this `View` to release its responder. Returning `true` allows its release.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onStartShouldSetResponder`[​](#onstartshouldsetresponder "Direct link to onstartshouldsetresponder")

Does this view want to become responder on the start of a touch?

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onStartShouldSetResponderCapture`[​](#onstartshouldsetrespondercapture "Direct link to onstartshouldsetrespondercapture")

If a parent `View` wants to prevent a child `View` from becoming responder on a touch start, it should have this handler which returns `true`.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `pointerEvents`[​](#pointerevents "Direct link to pointerevents")

Controls whether the `View` can be the target of touch events.

* `'auto'`: The View can be the target of touch events.
* `'none'`: The View is never the target of touch events.
* `'box-none'`: The View is never the target of touch events but its subviews can be. It behaves like if the view had the following classes in CSS:

CSS

```
.box-none {

  pointer-events: none;

}

.box-none * {

  pointer-events: auto;

}
```

* `'box-only'`: The view can be the target of touch events but its subviews cannot be. It behaves like if the view had the following classes in CSS:

CSS

```
.box-only {

  pointer-events: auto;

}

.box-only * {

  pointer-events: none;

}
```

| Type                                         |
| -------------------------------------------- |
| enum('box-none', 'none', 'box-only', 'auto') |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/next/element-nodes) when mounted.

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

This is a reserved performance property exposed by `RCTView` and is useful for scrolling content when there are many subviews, most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. The subviews must also have `overflow: hidden`, as should the containing view (or one of its superviews).

| Type |
| ---- |
| bool |

***

### `renderToHardwareTextureAndroid`Android[​](#rendertohardwaretextureandroid-android "Direct link to rendertohardwaretextureandroid-android")

Whether this `View` should render itself (and all of its children) into a single hardware texture on the GPU.

On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can be re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation.

| Type |
| ---- |
| bool |

***

### `role`[​](#role "Direct link to role")

`role` communicates the purpose of a component to the user of an assistive technology. Has precedence over the [`accessibilityRole`](/docs/next/view#accessibilityrole) prop.

| Type                                  |
| ------------------------------------- |
| [Role](/docs/next/accessibility#role) |

***

### `shouldRasterizeIOS`iOS[​](#shouldrasterizeios-ios "Direct link to shouldrasterizeios-ios")

Whether this `View` should be rendered as a bitmap before compositing.

On iOS, this is useful for animations and interactions that do not modify this component's dimensions nor its children; for example, when translating the position of a static view, rasterization allows the renderer to reuse a cached bitmap of a static view and quickly composite it during each frame.

Rasterization incurs an off-screen drawing pass and the bitmap consumes memory. Test and measure when using this property.

| Type |
| ---- |
| bool |

***

### `style`[​](#style "Direct link to style")

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

***

### `tabIndex`Android[​](#tabindex-android "Direct link to tabindex-android")

Whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. Supports the following values:

* `0` - View is focusable
* `-1` - View is not focusable

| Type        |
| ----------- |
| enum(0, -1) |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

warning

This disables the 'layout-only view removal' optimization for this view!

| Type   |
| ------ |
| string |

* [Synthetic Touch Events](#synthetic-touch-events)

* [Props](#props)

  * [`accessibilityActions`](#accessibilityactions)
  * [`accessibilityElementsHidden`](#accessibilityelementshidden-ios)

    [iOS](#accessibilityelementshidden-ios)
  * [`accessibilityHint`](#accessibilityhint)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)
  * [`accessibilityIgnoresInvertColors`](#accessibilityignoresinvertcolors-ios)

    [iOS](#accessibilityignoresinvertcolors-ios)
  * [`accessibilityLabel`](#accessibilitylabel)
  * [`accessibilityLiveRegion`](#accessibilityliveregion-android)

    [Android](#accessibilityliveregion-android)
  * [`accessibilityRole`](#accessibilityrole)
  * [`accessibilityState`](#accessibilitystate)
  * [`accessibilityValue`](#accessibilityvalue)
  * [`accessibilityViewIsModal`](#accessibilityviewismodal-ios)

    [iOS](#accessibilityviewismodal-ios)

    [Android](#aria-labelledby-android)
  * [`aria-live`](#aria-live-android)

    [Android](#aria-live-android)
  * [`aria-modal`](#aria-modal-ios)

    [iOS](#aria-modal-ios)

    [Android](#focusable-android)
  * [`hitSlop`](#hitslop)
  * [`id`](#id)
  * [`importantForAccessibility`](#importantforaccessibility-android)

    [Android](#importantforaccessibility-android)
  * [`nativeID`](#nativeid)
  * [`needsOffscreenAlphaCompositing`](#needsoffscreenalphacompositing)
  * [`nextFocusDown`](#nextfocusdown-android)

    [Android](#nextfocusdown-android)
  * [`nextFocusForward`](#nextfocusforward-android)

    [Android](#nextfocusforward-android)
  * [`nextFocusLeft`](#nextfocusleft-android)

    [Android](#nextfocusleft-android)
  * [`nextFocusRight`](#nextfocusright-android)

    [Android](#nextfocusright-android)
  * [`nextFocusUp`](#nextfocusup-android)

    [Android](#nextfocusup-android)
  * [`onAccessibilityAction`](#onaccessibilityaction)
  * [`onAccessibilityEscape`](#onaccessibilityescape-ios)

    [iOS](#onaccessibilityescape-ios)
  * [`onAccessibilityTap`](#onaccessibilitytap-ios)

    [iOS](#onaccessibilitytap-ios)
  * [`onLayout`](#onlayout)
  * [`onMagicTap`](#onmagictap-ios)

    [iOS](#onmagictap-ios)

    [Android](#rendertohardwaretextureandroid-android)
  * [`role`](#role)
  * [`shouldRasterizeIOS`](#shouldrasterizeios-ios)

    [iOS](#shouldrasterizeios-ios)
  * [`style`](#style)
  * [`tabIndex`](#tabindex-android)

    [Android](#tabindex-android)
  * [`testID`](#testid)

----
url: https://reactnative.dev/docs/imagebackground
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Deprecated

Use a [`View`](/docs/view) with an absolutely positioned [`Image`](/docs/image) instead.

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 [source code](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Image/ImageBackground.js) for more insight, and create your own custom component when needed.

Note that you must specify some width and height style attributes.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [Image Props](/docs/image#props)[​](#image-props "Direct link to image-props")

Inherits [Image Props](/docs/image#props).

***

### `imageStyle`[​](#imagestyle "Direct link to imagestyle")

| Type                                   |
| -------------------------------------- |
| [Image Style](/docs/image-style-props) |

***

### `imageRef`[​](#imageref "Direct link to imageref")

A ref setter that will be assigned the [element node](/docs/element-nodes) of the inner `Image` component when mounted.

***

### `style`[​](#style "Direct link to style")

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

* [Example](#example)

* [Props](#props)

  * [Image Props](#image-props)
  * [`imageStyle`](#imagestyle)
  * [`imageRef`](#imageref)
  * [`style`](#style)

----
url: https://reactnative.dev/docs/typescript
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

[TypeScript](https://www.typescriptlang.org/) is a language which extends JavaScript by adding type definitions. New React Native projects target TypeScript by default, but also support JavaScript and Flow.

## Getting Started with TypeScript[​](#getting-started-with-typescript "Direct link to Getting Started with TypeScript")

New projects created by the [React Native CLI](/docs/getting-started-without-a-framework#step-1-creating-a-new-application) or popular templates like [Ignite](https://github.com/infinitered/ignite) will use TypeScript by default.

TypeScript may also be used with [Expo](https://expo.io), which maintains TypeScript templates, or will prompt you to automatically install and configure TypeScript when a `.ts` or `.tsx` file is added to your project.

```
npx create-expo-app --template
```

## Adding TypeScript to an Existing Project[​](#adding-typescript-to-an-existing-project "Direct link to Adding TypeScript to an Existing Project")

1. Add TypeScript, types, and ESLint plugins to your project.

* npm
* Yarn

```
npm install -D typescript @react-native/typescript-config @types/jest @types/react @types/react-test-renderer
```

```
yarn add --dev typescript @react-native/typescript-config @types/jest @types/react @types/react-test-renderer
```

note

This command adds the latest version of every dependency. The versions may need to be changed to match the existing packages used by your project. You can use a tool like [React Native Upgrade Helper](https://react-native-community.github.io/upgrade-helper/) to see the versions shipped by React Native.

2. Add a TypeScript config file. Create a `tsconfig.json` in the root of your project:

tsconfig.json

```
{

  "extends": "@react-native/typescript-config"

}
```

3. Rename a JavaScript file to be `*.tsx`

warning

You should leave the `./index.js` entrypoint file as it is otherwise you may run into an issue when it comes to bundling a production build.

4. Run `tsc` to type-check your new TypeScript files.

* npm
* Yarn

```
npx tsc
```

```
yarn tsc
```

## Using JavaScript Instead of TypeScript[​](#using-javascript-instead-of-typescript "Direct link to Using JavaScript Instead of TypeScript")

React Native defaults new applications to TypeScript, but JavaScript may still be used. Files with a `.jsx` extension are treated as JavaScript instead of TypeScript, and will not be typechecked. JavaScript modules may still be imported by TypeScript modules, along with the reverse.

## How TypeScript and React Native works[​](#how-typescript-and-react-native-works "Direct link to How TypeScript and React Native works")

Out of the box, TypeScript sources are transformed by [Babel](/docs/javascript-environment#javascript-syntax-transformers) during bundling. We recommend that you use the TypeScript compiler only for type checking. This is the default behavior of `tsc` for newly created applications. If you have existing TypeScript code being ported to React Native, there are [one or two caveats](https://babeljs.io/docs/en/next/babel-plugin-transform-typescript) to using Babel instead of TypeScript.

## What does React Native + TypeScript look like[​](#what-does-react-native--typescript-look-like "Direct link to What does React Native + TypeScript look like")

You can provide an interface for a React Component's [Props](/docs/props) and [State](/docs/state) via `React.Component<Props, State>` which will provide type-checking and editor auto-completing when working with that component in JSX.

components/Hello.tsx

```
import {useState} from 'react';

import {Button, StyleSheet, Text, View} from 'react-native';



export type Props = {

  name: string;

  baseEnthusiasmLevel?: number;

};



function Hello({name, baseEnthusiasmLevel = 0}: Props) {

  const [enthusiasmLevel, setEnthusiasmLevel] = useState(

    baseEnthusiasmLevel,

  );



  const onIncrement = () =>

    setEnthusiasmLevel(enthusiasmLevel + 1);

  const onDecrement = () =>

    setEnthusiasmLevel(

      enthusiasmLevel > 0 ? enthusiasmLevel - 1 : 0,

    );



  const getExclamationMarks = (numChars: number) =>

    numChars > 0 ? Array(numChars + 1).join('!') : '';



  return (

    <View style={styles.container}>

      <Text style={styles.greeting}>

        Hello {name}

        {getExclamationMarks(enthusiasmLevel)}

      </Text>

      <View>

        <Button

          title="Increase enthusiasm"

          accessibilityLabel="increment"

          onPress={onIncrement}

          color="blue"

        />

        <Button

          title="Decrease enthusiasm"

          accessibilityLabel="decrement"

          onPress={onDecrement}

          color="red"

        />

      </View>

    </View>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    alignItems: 'center',

    justifyContent: 'center',

  },

  greeting: {

    fontSize: 20,

    fontWeight: 'bold',

    margin: 16,

  },

});



export default Hello;
```

```
{

-  "extends": "@react-native/typescript-config"

+  "extends": "@react-native/typescript-config",

+  "compilerOptions": {

+    "baseUrl": ".",

+    "paths": {

+      "*": ["src/*"],

+      "tests": ["tests/*"],

+      "@components/*": ["src/components/*"],

+    },

+  }

}
```

2. Add [`babel-plugin-module-resolver`](https://github.com/tleunen/babel-plugin-module-resolver) as a development package to your project:

* npm
* Yarn

```
npm install --save-dev babel-plugin-module-resolver
```

```
yarn add --dev babel-plugin-module-resolver
```

3. Finally, configure your `babel.config.js` (note that the syntax for your `babel.config.js` is different from your `tsconfig.json`):

Diff

```
{

   presets: ['module:metro-react-native-babel-preset'],

+  plugins: [

+    [

+       'module-resolver',

+       {

+         root: ['./src'],

+         extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],

+         alias: {

+           tests: ['./tests/'],

+           "@components": "./src/components",

+         }

+       }

+    ]

+  ]

}
```

----
url: https://reactnative.dev/docs/using-a-scrollview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The [ScrollView](/docs/scrollview) is a generic scrolling container that can contain multiple components and views. The scrollable items can be heterogeneous, and you can scroll both vertically and horizontally (by setting the `horizontal` property).

This example creates a vertical `ScrollView` with both images and text mixed together.

ScrollViews can be configured to allow paging through views using swiping gestures by using the `pagingEnabled` props. Swiping horizontally between views can also be implemented on Android using the [ViewPager](https://github.com/react-native-community/react-native-viewpager) component.

On iOS a ScrollView with a single item can be used to allow the user to zoom content. Set up the `maximumZoomScale` and `minimumZoomScale` props and your user will be able to use pinch and expand gestures to zoom in and out.

The ScrollView works best to present a small number of things of a limited size. All the elements and views of a `ScrollView` are rendered, even if they are not currently shown on the screen. If you have a long list of items which cannot fit on the screen, you should use a `FlatList` instead. So let's [learn about list views](/docs/using-a-listview) next.

----
url: https://reactnative.dev/docs/next/gesture-responder-system
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/gesture-responder-system)** (0.87).

Version: Next

For higher-level gesture interpretation, check out [PanResponder](/docs/next/panresponder).

* [Best Practices](#best-practices)

* [TouchableHighlight and Touchable\*](#touchablehighlight-and-touchable)

* [Responder Lifecycle](#responder-lifecycle)

  * [Capture ShouldSet Handlers](#capture-shouldset-handlers)
  * [PanResponder](#panresponder)

----
url: https://reactnative.dev/docs/global-cancelIdleCallback
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelIdleCallback) for more information.

The global `cancelIdleCallback` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-alert
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert) for more information.

The global `alert` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/statusbarios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use [`StatusBar`](/docs/statusbar) for mutating the status bar.

***

----
url: https://reactnative.dev/docs/next/appregistry
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/appregistry)** (0.87).

Version: Next

### Project with Native Code Required

If you are using the managed Expo workflow there is only ever one entry component registered with `AppRegistry` and it is handled automatically (or through [registerRootComponent](https://docs.expo.dev/versions/latest/sdk/register-root-component/)). You do not need to use this API.

`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`.

React TSX

```
import {Text, AppRegistry} from 'react-native';



const App = () => (

  <View>

    <Text>App1</Text>

  </View>

);



AppRegistry.registerComponent('Appname', () => App);
```

To "stop" an application when a view should be destroyed, call `AppRegistry.unmountApplicationComponentAtRootTag` with the tag that was passed into `runApplication`. These should always be used as a pair.

`AppRegistry` should be required early in the `require` sequence to make sure the JS execution environment is setup before other modules are required.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `getAppKeys()`[​](#getappkeys "Direct link to getappkeys")

React TSX

```
static getAppKeys(): string[];
```

Returns an array of strings.

***

### `getRegistry()`[​](#getregistry "Direct link to getregistry")

React TSX

```
static getRegistry(): {sections: string[]; runnables: Runnable[]};
```

Returns a [Registry](/docs/next/appregistry#registry) object.

***

### `getRunnable()`[​](#getrunnable "Direct link to getrunnable")

React TSX

```
static getRunnable(appKey: string): : Runnable | undefined;
```

Returns a [Runnable](/docs/next/appregistry#runnable) object.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| appKeyRequired | string |

***

### `getSectionKeys()`[​](#getsectionkeys "Direct link to getsectionkeys")

React TSX

```
static getSectionKeys(): string[];
```

Returns an array of strings.

***

### `getSections()`[​](#getsections "Direct link to getsections")

React TSX

```
static getSections(): Record<string, Runnable>;
```

Returns a [Runnables](/docs/next/appregistry#runnables) object.

***

### `registerCancellableHeadlessTask()`[​](#registercancellableheadlesstask "Direct link to registercancellableheadlesstask")

React TSX

```
static registerCancellableHeadlessTask(

  taskKey: string,

  taskProvider: TaskProvider,

  taskCancelProvider: TaskCancelProvider,

);
```

Register a headless task which can be cancelled. A headless task is a bit of code that runs without a UI.

**Parameters:**

| Name                        | Type                                                            | Description                                                                                                                                                                                                                         |
| --------------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| taskKey Required            | string                                                          | The native id for this task instance that was used when startHeadlessTask was called.                                                                                                                                               |
| taskProvider Required       | [TaskProvider](/docs/next/appregistry#taskprovider)             | A promise returning function that takes some data passed from the native side as the only argument. When the promise is resolved or rejected the native side is notified of this event and it may decide to destroy the JS context. |
| taskCancelProvider Required | [TaskCancelProvider](/docs/next/appregistry#taskcancelprovider) | a void returning function that takes no arguments; when a cancellation is requested, the function being executed by taskProvider should wrap up and return ASAP.                                                                    |

***

### `registerComponent()`[​](#registercomponent "Direct link to registercomponent")

React TSX

```
static registerComponent(

  appKey: string,

  getComponentFunc: ComponentProvider,

  section?: boolean,

): string;
```

**Parameters:**

| Name                      | Type              |
| ------------------------- | ----------------- |
| appKeyRequired            | string            |
| componentProviderRequired | ComponentProvider |
| section                   | boolean           |

***

### `registerConfig()`[​](#registerconfig "Direct link to registerconfig")

React TSX

```
static registerConfig(config: AppConfig[]);
```

**Parameters:**

| Name           | Type                                             |
| -------------- | ------------------------------------------------ |
| configRequired | [AppConfig](/docs/next/appregistry#appconfig)\[] |

***

### `registerHeadlessTask()`[​](#registerheadlesstask "Direct link to registerheadlesstask")

React TSX

```
static registerHeadlessTask(

  taskKey: string,

  taskProvider: TaskProvider,

);
```

Register a headless task. A headless task is a bit of code that runs without a UI.

This is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.

**Parameters:**

| Name                 | Type                                                | Description                                                                                                                                                                                                                         |
| -------------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| taskKeyRequired      | string                                              | The native id for this task instance that was used when startHeadlessTask was called.                                                                                                                                               |
| taskProviderRequired | [TaskProvider](/docs/next/appregistry#taskprovider) | A promise returning function that takes some data passed from the native side as the only argument. When the promise is resolved or rejected the native side is notified of this event and it may decide to destroy the JS context. |

***

### `registerRunnable()`[​](#registerrunnable "Direct link to registerrunnable")

React TSX

```
static registerRunnable(appKey: string, func: Runnable): string;
```

**Parameters:**

| Name           | Type     |
| -------------- | -------- |
| appKeyRequired | string   |
| runRequired    | function |

***

### `registerSection()`[​](#registersection "Direct link to registersection")

React TSX

```
static registerSection(

  appKey: string,

  component: ComponentProvider,

);
```

**Parameters:**

| Name              | Type              |
| ----------------- | ----------------- |
| appKeyRequired    | string            |
| componentRequired | ComponentProvider |

***

### `runApplication()`[​](#runapplication "Direct link to runapplication")

React TSX

```
static runApplication(appKey: string, appParameters: any): void;
```

Loads the JavaScript bundle and runs the app.

**Parameters:**

| Name                  | Type   |
| --------------------- | ------ |
| appKeyRequired        | string |
| appParametersRequired | any    |

***

### `setComponentProviderInstrumentationHook()`[​](#setcomponentproviderinstrumentationhook "Direct link to setcomponentproviderinstrumentationhook")

React TSX

```
static setComponentProviderInstrumentationHook(

  hook: ComponentProviderInstrumentationHook,

);
```

**Parameters:**

| Name         | Type     |
| ------------ | -------- |
| hookRequired | function |

A valid `hook` function accepts the following as arguments:

| Name                            | Type               |
| ------------------------------- | ------------------ |
| componentRequired               | ComponentProvider  |
| scopedPerformanceLoggerRequired | IPerformanceLogger |

The function must also return a React Component.

***

### `setWrapperComponentProvider()`[​](#setwrappercomponentprovider "Direct link to setwrappercomponentprovider")

React TSX

```
static setWrapperComponentProvider(

  provider: WrapperComponentProvider,

);
```

**Parameters:**

| Name             | Type              |
| ---------------- | ----------------- |
| providerRequired | ComponentProvider |

***

### `startHeadlessTask()`[​](#startheadlesstask "Direct link to startheadlesstask")

React TSX

```
static startHeadlessTask(

  taskId: number,

  taskKey: string,

  data: any,

);
```

Only called from native code. Starts a headless task.

**Parameters:**

| Name            | Type   | Description                                                          |
| --------------- | ------ | -------------------------------------------------------------------- |
| taskIdRequired  | number | The native id for this task instance to keep track of its execution. |
| taskKeyRequired | string | The key for the task to start.                                       |
| dataRequired    | any    | The data to pass to the task.                                        |

***

### `unmountApplicationComponentAtRootTag()`[​](#unmountapplicationcomponentatroottag "Direct link to unmountapplicationcomponentatroottag")

React TSX

```
static unmountApplicationComponentAtRootTag(rootTag: number);
```

Stops an application when a view should be destroyed.

**Parameters:**

| Name            | Type   |
| --------------- | ------ |
| rootTagRequired | number |

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### AppConfig[​](#appconfig "Direct link to AppConfig")

Application configuration for the `registerConfig` method.

| Type   |
| ------ |
| object |

**Properties:**

| Name           | Type              |
| -------------- | ----------------- |
| appKeyRequired | string            |
| component      | ComponentProvider |
| run            | function          |
| section        | boolean           |

note

Every config is expected to set either `component` or `run` function.

### Registry[​](#registry "Direct link to Registry")

| Type   |
| ------ |
| object |

**Properties:**

| Name      | Type                                                  |
| --------- | ----------------------------------------------------- |
| runnables | array of [Runnables](/docs/next/appregistry#runnable) |
| sections  | array of strings                                      |

### Runnable[​](#runnable "Direct link to Runnable")

| Type   |
| ------ |
| object |

**Properties:**

| Name      | Type              |
| --------- | ----------------- |
| component | ComponentProvider |
| run       | function          |

### Runnables[​](#runnables "Direct link to Runnables")

An object with key of `appKey` and value of type of [`Runnable`](/docs/next/appregistry#runnable).

| Type   |
| ------ |
| object |

### Task[​](#task "Direct link to Task")

A `Task` is a function that accepts any data as argument and returns a Promise that resolves to `undefined`.

| Type     |
| -------- |
| function |

### TaskCanceller[​](#taskcanceller "Direct link to TaskCanceller")

A `TaskCanceller` is a function that accepts no argument and returns void.

| Type     |
| -------- |
| function |

### TaskCancelProvider[​](#taskcancelprovider "Direct link to TaskCancelProvider")

A valid `TaskCancelProvider` is a function that returns a [`TaskCanceller`](/docs/next/appregistry#taskcanceller).

| Type     |
| -------- |
| function |

### TaskProvider[​](#taskprovider "Direct link to TaskProvider")

A valid `TaskProvider` is a function that returns a [`Task`](/docs/next/appregistry#task).

| Type     |
| -------- |
| function |

----
url: https://reactnative.dev/docs/touchablewithoutfeedback
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

tip

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the [Pressable](/docs/pressable) API.

Do not use unless you have a very good reason. All elements that respond to press should have a visual feedback when touched.

`TouchableWithoutFeedback` supports only one child. If you wish to have several child components, wrap them in a View. Importantly, `TouchableWithoutFeedback` works by cloning its child and applying responder props to it. It is therefore required that any intermediary components pass through those props to the underlying React Native component.

## Usage Pattern[​](#usage-pattern "Direct link to Usage Pattern")

React TSX

```
function MyComponent(props: MyComponentProps) {

  return (

    <View {...props} style={{flex: 1, backgroundColor: '#fff'}}>

      <Text>My Component</Text>

    </View>

  );

}



<TouchableWithoutFeedback onPress={() => alert('Pressed!')}>

  <MyComponent />

</TouchableWithoutFeedback>;
```

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### `accessibilityIgnoresInvertColors`iOS[​](#accessibilityignoresinvertcolors-ios "Direct link to accessibilityignoresinvertcolors-ios")

A value indicating this view should or should not be inverted when color inversion is turned on. A value of `true` will tell the view to not be inverted even if color inversion is turned on.

See the [Accessibility guide](/docs/accessibility#accessibilityignoresinvertcolors-ios) for more information.

| Type    |
| ------- |
| Boolean |

***

### `accessible`[​](#accessible "Direct link to accessible")

When `true`, indicates that the view is an accessibility element. By default, all the touchable elements are accessible.

| Type |
| ---- |
| bool |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the `Text` nodes separated by space.

| Type   |
| ------ |
| string |

***

### `accessibilityLanguage`iOS[​](#accessibilitylanguage-ios "Direct link to accessibilitylanguage-ios")

A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the [BCP 47 specification](https://www.rfc-editor.org/info/bcp47).

See the [iOS `accessibilityLanguage` doc](https://developer.apple.com/documentation/objectivec/nsobject/1615192-accessibilitylanguage) for more information.

| Type   |
| ------ |
| string |

***

### `accessibilityHint`[​](#accessibilityhint "Direct link to accessibilityhint")

An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label.

| Type   |
| ------ |
| string |

***

| Type   |
| ------ |
| string |

***

### `accessibilityState`[​](#accessibilitystate "Direct link to accessibilitystate")

Describes the current state of a component to the user of an assistive technology.

See the [Accessibility guide](/docs/accessibility#accessibilitystate) for more information.

| Type                                                                                             |
| ------------------------------------------------------------------------------------------------ |
| object: `{disabled: bool, selected: bool, checked: bool or 'mixed', busy: bool, expanded: bool}` |

***

### `accessibilityActions`[​](#accessibilityactions "Direct link to accessibilityactions")

Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The `accessibilityActions` property should contain a list of action objects. Each action object should contain the field name and label.

See the [Accessibility guide](/docs/accessibility#accessibility-actions) for more information.

| Type  |
| ----- |
| array |

***

### `aria-busy`[​](#aria-busy "Direct link to aria-busy")

Indicates an element is being modified and that assistive technologies may want to wait until the changes are complete before informing the user about the update.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-checked`[​](#aria-checked "Direct link to aria-checked")

Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

| Type             | Default |
| ---------------- | ------- |
| boolean, 'mixed' | false   |

***

### `aria-disabled`[​](#aria-disabled "Direct link to aria-disabled")

Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-expanded`[​](#aria-expanded "Direct link to aria-expanded")

Indicates whether an expandable element is currently expanded or collapsed.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-hidden`[​](#aria-hidden "Direct link to aria-hidden")

Indicates whether the element is hidden from assistive technologies.

For example, in a window that contains sibling views `A` and `B`, setting `aria-hidden` to `true` on view `B` causes VoiceOver to ignore the `B` element and its children.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-label`[​](#aria-label "Direct link to aria-label")

Defines a string value that labels an interactive element.

| Type   |
| ------ |
| string |

***

### `aria-live`Android[​](#aria-live-android "Direct link to aria-live-android")

Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

* **off** 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.

| Type                                     | Default |
| ---------------------------------------- | ------- |
| enum(`'assertive'`, `'off'`, `'polite'`) | `'off'` |

***

### `aria-modal`iOS[​](#aria-modal-ios "Direct link to aria-modal-ios")

Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. Has precedence over the [`accessibilityViewIsModal`](/docs/accessibility#accessibilityviewismodal-ios) prop.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-selected`[​](#aria-selected "Direct link to aria-selected")

Indicates whether a selectable element is currently selected or not.

| Type    |
| ------- |
| boolean |

### `onAccessibilityAction`[​](#onaccessibilityaction "Direct link to onaccessibilityaction")

Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

See the [Accessibility guide](/docs/accessibility#accessibility-actions) for more information.

| Type     |
| -------- |
| function |

***

### `accessibilityValue`[​](#accessibilityvalue "Direct link to accessibilityvalue")

Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, it contains range information (minimum, current, and maximum).

See the [Accessibility guide](/docs/accessibility#accessibilityvalue) for more information.

| Type                                                            |
| --------------------------------------------------------------- |
| object: `{min: number, max: number, now: number, text: string}` |

***

### `aria-valuemax`[​](#aria-valuemax "Direct link to aria-valuemax")

Represents the maximum value for range-based components, such as sliders and progress bars. Has precedence over the `max` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuemin`[​](#aria-valuemin "Direct link to aria-valuemin")

Represents the minimum value for range-based components, such as sliders and progress bars. Has precedence over the `min` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuenow`[​](#aria-valuenow "Direct link to aria-valuenow")

Represents the current value for range-based components, such as sliders and progress bars. Has precedence over the `now` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuetext`[​](#aria-valuetext "Direct link to aria-valuetext")

Represents the textual description of the component. Has precedence over the `text` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| string |

***

### `delayLongPress`[​](#delaylongpress "Direct link to delaylongpress")

Duration (in milliseconds) from `onPressIn` before `onLongPress` is called.

| Type   |
| ------ |
| number |

***

### `delayPressIn`[​](#delaypressin "Direct link to delaypressin")

Duration (in milliseconds), from the start of the touch, before `onPressIn` is called.

| Type   |
| ------ |
| number |

***

### `delayPressOut`[​](#delaypressout "Direct link to delaypressout")

Duration (in milliseconds), from the release of the touch, before `onPressOut` is called.

| Type   |
| ------ |
| number |

***

### `disabled`[​](#disabled "Direct link to disabled")

If true, disable all interactions for this component.

| Type |
| ---- |
| bool |

***

### `hitSlop`[​](#hitslop "Direct link to hitslop")

This defines how far your touch can start away from the button. This is added to `pressRetentionOffset` when moving off of the button.

note

The touch area never extends past the parent view bounds and the Z-index of sibling views always takes precedence if a touch hits two overlapping views.

| Type                         |
| ---------------------------- |
| [Rect](/docs/rect) or number |

### `id`[​](#id "Direct link to id")

Used to locate this view from native code. Has precedence over `nativeID` prop.

| Type   |
| ------ |
| string |

***

### `onBlur`[​](#onblur "Direct link to onblur")

Invoked when the item loses focus.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: TargetEvent}) => void` |

***

### `onFocus`[​](#onfocus "Direct link to onfocus")

Invoked when the item receives focus.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: TargetEvent}) => void` |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: LayoutEvent}) => void` |

***

### `onLongPress`[​](#onlongpress "Direct link to onlongpress")

Called if the time after `onPressIn` lasts longer than 370 milliseconds. This time period can be customized with [`delayLongPress`](#delaylongpress).

| Type     |
| -------- |
| function |

***

### `onPress`[​](#onpress "Direct link to onpress")

Called when the touch is released, but not if cancelled (e.g. by a scroll that steals the responder lock). The first function argument is an event in form of [PressEvent](/docs/pressevent).

| Type     |
| -------- |
| function |

***

### `onPressIn`[​](#onpressin "Direct link to onpressin")

Called as soon as the touchable element is pressed and invoked even before onPress. This can be useful when making network requests. The first function argument is an event in form of [PressEvent](/docs/pressevent).

| Type     |
| -------- |
| function |

***

### `onPressOut`[​](#onpressout "Direct link to onpressout")

Called as soon as the touch is released even before onPress. The first function argument is an event in form of [PressEvent](/docs/pressevent).

| Type     |
| -------- |
| function |

***

### `pressRetentionOffset`[​](#pressretentionoffset "Direct link to pressretentionoffset")

When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view is disabled. Ensure you pass in a constant to reduce memory allocations.

| Type                         |
| ---------------------------- |
| [Rect](/docs/rect) or number |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

| Type   |
| ------ |
| string |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

| Type   |
| ------ |
| string |

***

### `touchSoundDisabled`Android[​](#touchsounddisabled-android "Direct link to touchsounddisabled-android")

If true, doesn't play a system sound on touch.

| Type    |
| ------- |
| Boolean |

* [Usage Pattern](#usage-pattern)

* [Example](#example)

* [Props](#props)

  * [`accessibilityIgnoresInvertColors`](#accessibilityignoresinvertcolors-ios)

    [iOS](#accessibilityignoresinvertcolors-ios)
  * [`accessible`](#accessible)
  * [`accessibilityLabel`](#accessibilitylabel)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)

    [Android](#aria-live-android)
  * [`aria-modal`](#aria-modal-ios)

    [iOS](#aria-modal-ios)

    [Android](#touchsounddisabled-android)

----
url: https://reactnative.dev/docs/next/backhandler
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/backhandler)** (0.87).

Version: Next

The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds. It is Android-only.

The event subscriptions are called in reverse order (i.e. the last registered subscription is called first).

* **If one subscription returns true,** then subscriptions registered earlier will not be called.
* **If no subscription returns true or none are registered,** it programmatically invokes the default back button functionality to exit the app.

Warning for modal users

If your app shows an opened `Modal`, `BackHandler` will not publish any events ([see `Modal` docs](/docs/next/modal#onrequestclose)).

## Pattern[​](#pattern "Direct link to Pattern")

React TSX

```
const subscription = BackHandler.addEventListener(

  'hardwareBackPress',

  function () {

    /**

     * this.onMainScreen and this.goBack are just examples,

     * you need to use your own implementation here.

     *

     * Typically you would use the navigator here to go to the last state.

     */



    if (!this.onMainScreen()) {

      this.goBack();

      /**

       * When true is returned the event will not be bubbled up

       * & no other back action will execute

       */

      return true;

    }

    /**

     * Returning false will let the event to bubble up & let other event listeners

     * or the system's default back action to be executed.

     */

    return false;

  },

);



// Unsubscribe the listener on unmount

subscription.remove();
```

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `addEventListener()`[​](#addeventlistener "Direct link to addeventlistener")

React TSX

```
static addEventListener(

  eventName: BackPressEventName,

  handler: () => boolean | null | undefined,

): EventSubscription;
```

***

### `exitApp()`[​](#exitapp "Direct link to exitapp")

React TSX

```
static exitApp();
```

----
url: https://reactnative.dev/docs/next/using-a-scrollview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/using-a-scrollview)** (0.87).

Version: Next

The [ScrollView](/docs/next/scrollview) is a generic scrolling container that can contain multiple components and views. The scrollable items can be heterogeneous, and you can scroll both vertically and horizontally (by setting the `horizontal` property).

This example creates a vertical `ScrollView` with both images and text mixed together.

ScrollViews can be configured to allow paging through views using swiping gestures by using the `pagingEnabled` props. Swiping horizontally between views can also be implemented on Android using the [ViewPager](https://github.com/react-native-community/react-native-viewpager) component.

On iOS a ScrollView with a single item can be used to allow the user to zoom content. Set up the `maximumZoomScale` and `minimumZoomScale` props and your user will be able to use pinch and expand gestures to zoom in and out.

The ScrollView works best to present a small number of things of a limited size. All the elements and views of a `ScrollView` are rendered, even if they are not currently shown on the screen. If you have a long list of items which cannot fit on the screen, you should use a `FlatList` instead. So let's [learn about list views](/docs/next/using-a-listview) next.

----
url: https://reactnative.dev/docs/release-levels
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
DefaultNewArchitectureEntryPoint.releaseLevel = ReleaseLevel.CANARY

DefaultNewArchitectureEntryPoint.load()
```

The build system generates different feature flag override classes for each release level, ensuring the correct features are enabled for each stage.

### iOS[​](#ios "Direct link to iOS")

The `RCTReactNativeFactory` class now has an initializer that accepts a `releaseLevel` parameter. The feature flag setup uses this parameter to select the correct feature flag overrides.

* ObjectiveC
* Swift

AppDelegate.mm

```
[[RCTReactNativeFactory alloc] initWithDelegate:delegate releaseLevel:Canary];
```

AppDelegate.swift

```
let factory = RCTReactNativeFactory(delegate: delegate, releaseLevel: RCTReleaseLevel.Canary)
```

The system ensures that only one release level is active per app instance, and will crash if multiple factories are created with different release levels.

* [When to Use Each Release Level](#when-to-use-each-release-level)

* [How to initialize React Native using Canary & Experimental](#how-to-initialize-react-native-using-canary--experimental)

  * [Android](#android)
  * [iOS](#ios)

----
url: https://reactnative.dev/docs/next/legacy/direct-manipulation
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/legacy/direct-manipulation)** (0.87).

Version: Next

```
const viewRef = useRef<View>();

const setOpacityTo = useCallback(value => {

  // Redacted: animation related code

  viewRef.current.setNativeProps({

    opacity: 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:

React TSX

```
<TouchableOpacity onPress={handlePress}>

  <View>

    <Text>Press me!</Text>

  </View>

</TouchableOpacity>
```

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:

React TSX

```
const [buttonOpacity, setButtonOpacity] = useState(1);

return (

  <TouchableOpacity

    onPressIn={() => setButtonOpacity(0.5)}

    onPressOut={() => setButtonOpacity(1)}>

    <View style={{opacity: buttonOpacity}}>

      <Text>Press me!</Text>

    </View>

  </TouchableOpacity>

);
```

You may have noticed that we passed all of the props down to the child view using `{...props}`. The reason for this is that `TouchableOpacity` is actually a composite component, and so in addition to depending on `setNativeProps` on its child, it also requires that the child perform touch handling. To do this, it passes on [various props](/docs/next/view#onmoveshouldsetresponder) that call back to the `TouchableOpacity` component. `TouchableHighlight`, in contrast, is backed by a native view and only requires that we implement `setNativeProps`.

## setNativeProps to edit TextInput value[​](#setnativeprops-to-edit-textinput-value "Direct link to setNativeProps to edit TextInput value")

Another very common use case of `setNativeProps` is to edit the value of the TextInput. The `controlled` prop of TextInput can sometimes drop characters when the `bufferDelay` is low and the user types very quickly. Some developers prefer to skip this prop entirely and instead use `setNativeProps` to directly manipulate the TextInput value when necessary. For example, the following code demonstrates editing the input when you tap a button:

* TypeScript
* JavaScript

You can use the [`clear`](/docs/next/textinput#clear) method to clear the `TextInput` which clears the current input text using the same approach.

Note that these measurements are not available until after the rendering has been completed in native. If you need the measurements as soon as possible and you don't need `pageX` and `pageY`, consider using the [`onLayout`](/docs/next/view#onlayout) property instead.

Also the width and height returned by `measure()` are the width and height of the component in the viewport. If you need the actual size of the component, consider using the [`onLayout`](/docs/next/view#onlayout) property instead.

----
url: https://reactnative.dev/docs/next/legacy/native-modules-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/legacy/native-modules-ios)** (0.87).

Version: Next

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

Welcome to Native Modules for iOS. Please start by reading the [Native Modules Intro](/docs/next/legacy/native-modules-intro) for an intro to what native modules are.

```
//  RCTCalendarModule.h

#import <React/RCTBridgeModule.h>

@interface RCTCalendarModule : NSObject <RCTBridgeModule>

@end
```

You can use any name that fits the native module you are building. Name the class `RCTCalendarModule` since you are creating a calendar native module. Since ObjC does not have language-level support for namespaces like Java or C++, convention is to prepend the class name with a substring. This could be an abbreviation of your application name or your infra name. RCT, in this example, refers to React.

As you can see below, the CalendarModule class implements the `RCTBridgeModule` protocol. A native module is an Objective-C class that implements the `RCTBridgeModule` protocol.

Next up, let’s start implementing the native module. Create the corresponding implementation file using cocoa touch class in xcode, `RCTCalendarModule.m`, in the same folder and include the following content:

Objective-C

```
// RCTCalendarModule.m

#import "RCTCalendarModule.h"



@implementation RCTCalendarModule



// To export a module named RCTCalendarModule

RCT_EXPORT_MODULE();



@end
```

### Module Name[​](#module-name "Direct link to Module Name")

For now, your `RCTCalendarModule.m` native module only includes a `RCT_EXPORT_MODULE` macro, which exports and registers the native module class with React Native. The `RCT_EXPORT_MODULE` macro also takes an optional argument that specifies the name that the module will be accessible as in your JavaScript code.

This argument is not a string literal. In the example below `RCT_EXPORT_MODULE(CalendarModuleFoo)` is passed, not `RCT_EXPORT_MODULE("CalendarModuleFoo")`.

Objective-C

```
// To export a module named CalendarModuleFoo

RCT_EXPORT_MODULE(CalendarModuleFoo);
```

The native module can then be accessed in JS like this:

React TSX

```
const {CalendarModuleFoo} = ReactNative.NativeModules;
```

If you do not specify a name, the JavaScript module name will match the Objective-C class name, with any "RCT" or "RK" prefixes removed.

Let's follow the example below and call `RCT_EXPORT_MODULE` without any arguments. As a result, the module will be exposed to React Native using the name `CalendarModule`, since that is the Objective-C class name, with RCT removed.

Objective-C

```
// Without passing in a name this will export the native module name as the Objective-C class name with “RCT” removed

RCT_EXPORT_MODULE();
```

The native module can then be accessed in JS like this:

React TSX

```
const {CalendarModule} = ReactNative.NativeModules;
```

### Export a Native Method to JavaScript[​](#export-a-native-method-to-javascript "Direct link to Export a Native Method to JavaScript")

React Native will not expose any methods in a native module to JavaScript unless explicitly told to. This can be done using the `RCT_EXPORT_METHOD` macro. Methods written in the `RCT_EXPORT_METHOD` macro are asynchronous and the return type is therefore always void. In order to pass a result from a `RCT_EXPORT_METHOD` method to JavaScript you can use callbacks or emit events (covered below). Let’s go ahead and set up a native method for our `CalendarModule` native module using the `RCT_EXPORT_METHOD` macro. Call it `createCalendarEvent()` and for now have it take in name and location arguments as strings. Argument type options will be covered shortly.

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)name location:(NSString *)location)

{

}
```

note

Please note that the `RCT_EXPORT_METHOD` macro will not be necessary with TurboModules unless your method relies on RCT argument conversion (see argument types below). Ultimately, React Native will remove `RCT_EXPORT_MACRO,` so we discourage people from using `RCTConvert`. Instead, you can do the argument conversion within the method body.

Before you build out the `createCalendarEvent()` method’s functionality, add a console log in the method so you can confirm it has been invoked from JavaScript in your React Native application. Use the `RCTLog` APIs from React. Let’s import that header at the top of your file and then add the log call.

Objective-C

```
#import <React/RCTLog.h>

RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)name location:(NSString *)location)

{

 RCTLogInfo(@"Pretending to create an event %@ at %@", name, location);

}
```

### Synchronous Methods[​](#synchronous-methods "Direct link to Synchronous Methods")

You can use the `RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD` to create a synchronous native method.

Objective-C

```
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getName)

{

return [[UIDevice currentDevice] name];

}
```

The return type of this method must be of object type (id) and should be serializable to JSON. This means that the hook can only return nil or JSON values (e.g. NSNumber, NSString, NSArray, NSDictionary).

At the moment, we do not recommend using synchronous methods, since calling methods synchronously can have strong performance penalties and introduce threading-related bugs to your native modules. Additionally, please note that if you choose to use `RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD`, your app can no longer use the Google Chrome debugger. This is because synchronous methods require the JS VM to share memory with the app. For the Google Chrome debugger, React Native runs inside the JS VM in Google Chrome, and communicates asynchronously with the mobile devices via WebSockets.

### Test What You Have Built[​](#test-what-you-have-built "Direct link to Test What You Have Built")

At this point you have set up the basic scaffolding for your native module in iOS. Test that out by accessing the native module and invoking it’s exported method in JavaScript.

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.

React TSX

```
import {Button} from 'react-native';



const NewModuleButton = () => {

  const onPress = () => {

    console.log('We will invoke the native module here!');

  };



  return (

    <Button

      title="Click to invoke your native module!"

      color="#841584"

      onPress={onPress}

    />

  );

};



export default NewModuleButton;
```

In order to access your native module from JavaScript you need to first import `NativeModules` from React Native:

React TSX

```
import {NativeModules} from 'react-native';
```

You can then access the `CalendarModule` native module off of `NativeModules`.

React 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`:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent('testName', 'testLocation');

};
```

The final step is to rebuild the React Native app so that you can have the latest native code (with your new native module!) available. In your command line, where the react native application is located, run the following :

* npm
* Yarn

```
npm run ios
```

```
yarn ios
```

```
/**

* This exposes the native CalendarModule module as a JS module. This has a

* function 'createCalendarEvent' which takes the following parameters:



* 1. String name: A string representing the name of the event

* 2. String location: A string representing the location of the event

*/

import {NativeModules} from 'react-native';

const {CalendarModule} = NativeModules;

export default CalendarModule;
```

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:

React TSX

```
/**

 * This exposes the native CalendarModule module as a JS module. This has a

 * function 'createCalendarEvent' which takes the following parameters:

 *

 * 1. String name: A string representing the name of the event

 * 2. String location: A string representing the location of the event

 */

import {NativeModules} from 'react-native';

const {CalendarModule} = NativeModules;

interface CalendarInterface {

  createCalendarEvent(name: string, location: string): void;

}

export default CalendarModule as CalendarInterface;
```

In your other JavaScript files you can access the native module and invoke its method like this:

React TSX

```
import NativeCalendarModule from './NativeCalendarModule';

NativeCalendarModule.createCalendarEvent('foo', 'bar');
```

note

This assumes that the place you are importing `CalendarModule` is in the same hierarchy as `NativeCalendarModule.js`. Please update the relative import as necessary.

### Argument Types[​](#argument-types "Direct link to Argument Types")

When a native module method is invoked in JavaScript, React Native converts the arguments from JS objects to their Objective-C/Swift object analogues. So for example, if your Objective-C Native Module method accepts a NSNumber, in JS you need to call the method with a number. React Native will handle the conversion for you. Below is a list of the argument types supported for native module methods and the JavaScript equivalents they map to.

| Objective-C                                   | JavaScript         |
| --------------------------------------------- | ------------------ |
| NSString                                      | string, ?string    |
| BOOL                                          | boolean            |
| double                                        | number             |
| NSNumber                                      | ?number            |
| NSArray                                       | Array, ?Array      |
| NSDictionary                                  | Object, ?Object    |
| RCTResponseSenderBlock                        | Function (success) |
| RCTResponseSenderBlock, RCTResponseErrorBlock | Function (failure) |
| RCTPromiseResolveBlock, RCTPromiseRejectBlock | Promise            |

```
- (NSDictionary *)constantsToExport

{

 return @{ @"DEFAULT_EVENT_NAME": @"New Event" };

}
```

The constant can then be accessed by invoking `getConstants()` on the native module in JS like so:

React TSX

```
const {DEFAULT_EVENT_NAME} = CalendarModule.getConstants();

console.log(DEFAULT_EVENT_NAME);
```

```
RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)title

                location:(NSString *)location

                myCallback:(RCTResponseSenderBlock)callback)
```

You can then invoke the callback in your native function, providing whatever result you want to pass to JavaScript in an array. Note that `RCTResponseSenderBlock` accepts only one argument - an array of parameters to pass to the JavaScript callback. Below you will pass back the ID of an event created in an earlier call.

info

It is important to highlight that the callback is not invoked immediately after the native function completes—remember the communication is asynchronous.

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)title location:(NSString *)location callback: (RCTResponseSenderBlock)callback)

{

 NSInteger eventId = ...

 callback(@[@(eventId)]);



 RCTLogInfo(@"Pretending to create an event %@ at %@", title, location);

}
```

This method could then be accessed in JavaScript using the following:

React TSX

```
const onSubmit = () => {

  CalendarModule.createCalendarEvent(

    'Party',

    '04-12-2020',

    eventId => {

      console.log(`Created a new event with id ${eventId}`);

    },

  );

};
```

A native module is supposed to invoke its callback only once. It can, however, store the callback and invoke it later. This pattern is often used to wrap iOS APIs that require delegates— see [`RCTAlertManager`](https://github.com/react/react-native/blob/main/packages/react-native/React/CoreModules/RCTAlertManager.mm) for an example. If the callback is never invoked, some memory is leaked.

There are two approaches to error handling with callbacks. The first is to follow Node’s convention and treat the first argument passed to the callback array as an error object.

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEventCallback:(NSString *)title location:(NSString *)location callback: (RCTResponseSenderBlock)callback)

{

  NSNumber *eventId = [NSNumber numberWithInt:123];

  callback(@[[NSNull null], eventId]);

}
```

In JavaScript, you can then check the first argument to see if an error was passed through:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEventCallback(

    'testName',

    'testLocation',

    (error, eventId) => {

      if (error) {

        console.error(`Error found! ${error}`);

      }

      console.log(`event id ${eventId} returned`);

    },

  );

};
```

Another option is to use two separate callbacks: onFailure and onSuccess.

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEventCallback:(NSString *)title

                  location:(NSString *)location

                  errorCallback: (RCTResponseSenderBlock)errorCallback

                  successCallback: (RCTResponseSenderBlock)successCallback)

{

  @try {

    NSNumber *eventId = [NSNumber numberWithInt:123];

    successCallback(@[eventId]);

  }



  @catch ( NSException *e ) {

    errorCallback(@[e]);

  }

}
```

Then in JavaScript you can add a separate callback for error and success responses:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEventCallback(

    'testName',

    'testLocation',

    error => {

      console.error(`Error found! ${error}`);

    },

    eventId => {

      console.log(`event id ${eventId} returned`);

    },

  );

};
```

If you want to pass error-like objects to JavaScript, use `RCTMakeError` from [`RCTUtils.h.`](https://github.com/react/react-native/blob/main/packages/react-native/React/Base/RCTUtils.h) Right now this only passes an Error-shaped dictionary to JavaScript, but React Native aims to automatically generate real JavaScript Error objects in the future. You can also provide a `RCTResponseErrorBlock` argument, which is used for error callbacks and accepts an `NSError \* object`. Please note that this argument type will not be supported with TurboModules.

### Promises[​](#promises "Direct link to Promises")

Native modules can also fulfill a promise, which can simplify your JavaScript, especially when using ES2016's `async/await` syntax. When the last parameter of a native module method is a `RCTPromiseResolveBlock` and `RCTPromiseRejectBlock`, its corresponding JS method will return a JS Promise object.

Refactoring the above code to use a promise instead of callbacks looks like this:

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)title

                 location:(NSString *)location

                 resolver:(RCTPromiseResolveBlock)resolve

                 rejecter:(RCTPromiseRejectBlock)reject)

{

 NSInteger eventId = createCalendarEvent();

 if (eventId) {

    resolve(@(eventId));

  } else {

    reject(@"event_failure", @"no event id returned", nil);

  }

}
```

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:

React TSX

```
const onSubmit = async () => {

  try {

    const eventId = await CalendarModule.createCalendarEvent(

      'Party',

      'my house',

    );

    console.log(`Created a new event with id ${eventId}`);

  } catch (e) {

    console.error(e);

  }

};
```

### Sending Events to JavaScript[​](#sending-events-to-javascript "Direct link to Sending Events to JavaScript")

Native modules can signal events to JavaScript without being invoked directly. For example, you might want to signal to JavaScript a reminder that a calendar event from the native iOS calendar app will occur soon. The preferred way to do this is to subclass `RCTEventEmitter`, implement `supportedEvents` and call self `sendEventWithName`:

Update your header class to import `RCTEventEmitter` and subclass `RCTEventEmitter`:

Objective-C

```
//  CalendarModule.h



#import <React/RCTBridgeModule.h>

#import <React/RCTEventEmitter.h>



@interface CalendarModule : RCTEventEmitter <RCTBridgeModule>

@end
```

JavaScript code can subscribe to these events by creating a new `NativeEventEmitter` instance around your module.

You will receive a warning if you expend resources unnecessarily by emitting an event while there are no listeners. To avoid this, and to optimize your module's workload (e.g. by unsubscribing from upstream notifications or pausing background tasks), you can override `startObserving` and `stopObserving` in your `RCTEventEmitter` subclass.

Objective-C

```
@implementation CalendarModule

{

  bool hasListeners;

}



// Will be called when this module's first listener is added.

-(void)startObserving {

    hasListeners = YES;

    // Set up any upstream listeners or background tasks as necessary

}



// Will be called when this module's last listener is removed, or on dealloc.

-(void)stopObserving {

    hasListeners = NO;

    // Remove upstream listeners, stop unnecessary background tasks

}



- (void)calendarEventReminderReceived:(NSNotification *)notification

{

  NSString *eventName = notification.userInfo[@"name"];

  if (hasListeners) {// Only send events if anyone is listening

    [self sendEventWithName:@"EventReminder" body:@{@"name": eventName}];

  }

}
```

### Threading[​](#threading "Direct link to Threading")

Unless the native module provides its own method queue, it shouldn't make any assumptions about what thread it's being called on. Currently, if a native module doesn't provide a method queue, React Native will create a separate GCD queue for it and invoke its methods there. Please note that this is an implementation detail and might change. If you want to explicitly provide a method queue for a native module, override the `(dispatch_queue_t) methodQueue` method in the native module. For example, if it needs to use a main-thread-only iOS API, it should specify this via:

Objective-C

```
- (dispatch_queue_t)methodQueue

{

  return dispatch_get_main_queue();

}
```

Similarly, if an operation may take a long time to complete, the native module can specify its own queue to run operations on. Again, currently React Native will provide a separate method queue for your native module, but this is an implementation detail you should not rely on. If you don't provide your own method queue, in the future, your native module's long running operations may end up blocking async calls being executed on other unrelated native modules. The `RCTAsyncLocalStorage` module here, for example, creates its own queue so the React queue isn't blocked waiting on potentially slow disk access.

Objective-C

```
- (dispatch_queue_t)methodQueue

{

 return dispatch_queue_create("com.facebook.React.AsyncLocalStorageQueue", DISPATCH_QUEUE_SERIAL);

}
```

The specified `methodQueue` will be shared by all of the methods in your module. If only one of your methods is long-running (or needs to be run on a different queue than the others for some reason), you can use `dispatch_async` inside the method to perform that particular method's code on another queue, without affecting the others:

Objective-C

```
RCT_EXPORT_METHOD(doSomethingExpensive:(NSString *)param callback:(RCTResponseSenderBlock)callback)

{

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

   // Call long-running code on background thread

   ...

   // You can invoke callback from any thread/queue

   callback(@[...]);

 });

}
```

Sharing dispatch queues between modules

The `methodQueue` method will be called once when the module is initialized, and then retained by React Native, so there is no need to keep a reference to the queue yourself, unless you wish to make use of it within your module. However, if you wish to share the same queue between multiple modules then you will need to ensure that you retain and return the same queue instance for each of them.

### Dependency Injection[​](#dependency-injection "Direct link to Dependency Injection")

React Native will create and initialize any registered native modules automatically. However, you may wish to create and initialize your own module instances to, for example, inject dependencies.

You can do this by creating a class that implements the `RCTBridgeDelegate` Protocol, initializing an `RCTBridge` with the delegate as an argument and initialising a `RCTRootView` with the initialized bridge.

Objective-C

```
id<RCTBridgeDelegate> moduleInitialiser = [[classThatImplementsRCTBridgeDelegate alloc] init];



RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:moduleInitialiser launchOptions:nil];



RCTRootView *rootView = [[RCTRootView alloc]

                        initWithBridge:bridge

                            moduleName:kModuleName

                     initialProperties:nil];
```

### Exporting Swift[​](#exporting-swift "Direct link to Exporting Swift")

Swift doesn't have support for macros, so exposing native modules and their methods to JavaScript inside React Native requires a bit more setup. However, it works relatively the same. Let's say you have the same `CalendarModule` but as a Swift class:

Swift

```
// CalendarModule.swift



@objc(CalendarModule)

class CalendarModule: NSObject {



 @objc(addEvent:location:date:)

 func addEvent(_ name: String, location: String, date: NSNumber) -> Void {

   // Date is ready to use!

 }



 @objc

 func constantsToExport() -> [String: Any]! {

   return ["someKey": "someValue"]

 }



}
```

note

It is important to use the `@objc` modifiers to ensure the class and functions are exported properly to the Objective-C runtime.

Then create a private implementation file that will register the required information with React Native:

Objective-C

```
// CalendarModuleBridge.m

#import <React/RCTBridgeModule.h>



@interface RCT_EXTERN_MODULE(CalendarModule, NSObject)



RCT_EXTERN_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(nonnull NSNumber *)date)



@end
```

For those of you new to Swift and Objective-C, whenever you [mix the two languages in an iOS project](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html), you will also need an additional bridging file, known as a bridging header, to expose the Objective-C files to Swift. Xcode will offer to create this header file for you if you add your Swift file to your app through the Xcode `File>New File` menu option. You will need to import `RCTBridgeModule.h` in this header file.

Objective-C

```
// CalendarModule-Bridging-Header.h

#import <React/RCTBridgeModule.h>
```

----
url: https://reactnative.dev/docs/panresponder
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`PanResponder` reconciles several touches into a single gesture. It makes single-touch gestures resilient to extra touches, and can be used to recognize basic multi-touch gestures.

By default, `PanResponder` holds an interaction handle to block long-running JS events from interrupting active gestures.

It provides a predictable wrapper of the responder handlers provided by the [gesture responder system](/docs/gesture-responder-system). For each handler, it provides a new `gestureState` object alongside the native event object:

```
onPanResponderMove: (event, gestureState) => {}
```

A native event is a synthetic touch event with form of [PressEvent](/docs/pressevent).

```
const ExampleComponent = () => {

  const panResponder = useRef(

    PanResponder.create({

      // Ask to be the responder:

      onStartShouldSetPanResponder: (evt, gestureState) => true,

      onStartShouldSetPanResponderCapture: (evt, gestureState) =>

        true,

      onMoveShouldSetPanResponder: (evt, gestureState) => true,

      onMoveShouldSetPanResponderCapture: (evt, gestureState) =>

        true,



      onPanResponderGrant: (evt, gestureState) => {

        // The gesture has started. Show visual feedback so the user knows

        // what is happening!

        // gestureState.d{x,y} will be set to zero now

      },

      onPanResponderMove: (evt, gestureState) => {

        // The most recent move distance is gestureState.move{X,Y}

        // The accumulated gesture distance since becoming responder is

        // gestureState.d{x,y}

      },

      onPanResponderTerminationRequest: (evt, gestureState) =>

        true,

      onPanResponderRelease: (evt, gestureState) => {

        // The user has released all touches while this view is the

        // responder. This typically means a gesture has succeeded

      },

      onPanResponderTerminate: (evt, gestureState) => {

        // Another component has become the responder, so this gesture

        // should be cancelled

      },

      onShouldBlockNativeResponder: (evt, gestureState) => {

        // Returns whether this component should block native components from becoming the JS

        // responder. Returns true by default. Is currently only supported on android.

        return true;

      },

    }),

  ).current;



  return <View {...panResponder.panHandlers} />;

};
```

## Example[​](#example "Direct link to Example")

`PanResponder` works with `Animated` API to help build complex gestures in the UI. The following example contains an animated `View` component which can be dragged freely across the screen

Try the [PanResponder example in RNTester](https://github.com/react/react-native/blob/main/packages/rn-tester/js/examples/PanResponder/PanResponderExample.js).

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `create()`[​](#create "Direct link to create")

React TSX

```
static create(config: PanResponderCallbacks): PanResponderInstance;
```

**Parameters:**

| Name           | Type   | Description |
| -------------- | ------ | ----------- |
| configRequired | object | Refer below |

The `config` object provides enhanced versions of all of the responder callbacks that provide not only the [`PressEvent`](/docs/pressevent), but also the `PanResponder` gesture state, by replacing the word `Responder` with `PanResponder` in each of the typical `onResponder*` callbacks. For example, the `config` object would look like:

----
url: https://reactnative.dev/docs/next/global-cancelAnimationFrame
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-cancelAnimationFrame)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame) for more information.

The global `cancelAnimationFrame` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/text-nodes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/text-nodes)** (0.87).

Version: Next

Text nodes represent raw text content on the tree (similar to [`Text`](https://developer.mozilla.org/en-US/docs/Web/API/Text) nodes on Web). They are not directly accessible via `refs`, but can be accessed using methods like [`childNodes`](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes) on element refs.

***

    * ℹ️ Will return the [document node](/docs/next/document-nodes) where this component was rendered.

    * ℹ️ Will return a reference to itself if the component is not mounted.
  * [`hasChildNodes()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes)

- [Reference](#reference)
  * [Web-compatible API](#web-compatible-api)

----
url: https://reactnative.dev/docs/keyboard
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`Keyboard` module to control keyboard events.

### Usage[​](#usage "Direct link to Usage")

The Keyboard module allows you to listen for native events and react to them, as well as make changes to the keyboard, like dismissing it.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `addListener()`[​](#addlistener "Direct link to addlistener")

React TSX

```
static addListener: (

  eventType: KeyboardEventName,

  listener: KeyboardEventListener,

) => EventSubscription;
```

The `addListener` function connects a JavaScript function to an identified native keyboard notification event.

This function then returns the reference to the listener.

**Parameters:**

| Name              | Type     | Description                                                                    |
| ----------------- | -------- | ------------------------------------------------------------------------------ |
| eventNameRequired | string   | The string that identifies the event you're listening for. See the list below. |
| callbackRequired  | function | The function to be called when the event fires                                 |

***

### `dismiss()`[​](#dismiss "Direct link to dismiss")

React TSX

```
static dismiss();
```

Dismisses the active keyboard and removes focus.

***

### `scheduleLayoutAnimation`[​](#schedulelayoutanimation "Direct link to schedulelayoutanimation")

React TSX

```
static scheduleLayoutAnimation(event: KeyboardEvent);
```

Useful for syncing TextInput (or other keyboard accessory view) size of position changes with keyboard movements.

***

### `isVisible()`[​](#isvisible "Direct link to isvisible")

React TSX

```
static isVisible(): boolean;
```

Whether the keyboard is last known to be visible.

***

### `metrics()`[​](#metrics "Direct link to metrics")

React TSX

```
static metrics(): KeyboardMetrics | undefined;
```

----
url: https://reactnative.dev/docs/timers
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

----
url: https://reactnative.dev/docs/global-AbortController
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) for more information.

The global `AbortController` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-PerformanceMark
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`PerformanceMark`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMark) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/getting-started
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Welcome to the very start of your React Native journey! If you're looking for getting started instructions, they've moved to [their own section](environment-setup). Continue reading for an introduction to the documentation, Native Components, React, and more!

Many different kinds of people use React Native: from advanced iOS developers to React beginners, to people getting started programming for the first time in their career. These docs were written for all learners, no matter their experience level or background.

## How to use these docs[​](#how-to-use-these-docs "Direct link to How to use these docs")

You can start here and read through these docs linearly like a book; or you can read the specific sections you need. Already familiar with React? You can skip [that section](/docs/intro-react)—or read it for a light refresher.

Optionally, if you want to set up a local development environment, [you can follow our guide to setting up your environment on your local machine](/docs/set-up-your-environment) and paste the code examples into your project. (If you are a web developer, you may already have a local environment set up for mobile browser testing!)

***

Now that you know how this guide works, it's time to get to know the foundation of React Native: [Native Components](/docs/intro-react-native-components).

* [How to use these docs](#how-to-use-these-docs)
* [Prerequisites](#prerequisites)
* [Interactive examples](#interactive-examples)
* [Developer Notes](#developer-notes)
* [Formatting](#formatting)

----
url: https://reactnative.dev/docs/next/touchablewithoutfeedback
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/touchablewithoutfeedback)** (0.87).

Version: Next

tip

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the [Pressable](/docs/next/pressable) API.

Do not use unless you have a very good reason. All elements that respond to press should have a visual feedback when touched.

`TouchableWithoutFeedback` supports only one child. If you wish to have several child components, wrap them in a View. Importantly, `TouchableWithoutFeedback` works by cloning its child and applying responder props to it. It is therefore required that any intermediary components pass through those props to the underlying React Native component.

## Usage Pattern[​](#usage-pattern "Direct link to Usage Pattern")

React TSX

```
function MyComponent(props: MyComponentProps) {

  return (

    <View {...props} style={{flex: 1, backgroundColor: '#fff'}}>

      <Text>My Component</Text>

    </View>

  );

}



<TouchableWithoutFeedback onPress={() => alert('Pressed!')}>

  <MyComponent />

</TouchableWithoutFeedback>;
```

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### `accessibilityIgnoresInvertColors`iOS[​](#accessibilityignoresinvertcolors-ios "Direct link to accessibilityignoresinvertcolors-ios")

A value indicating this view should or should not be inverted when color inversion is turned on. A value of `true` will tell the view to not be inverted even if color inversion is turned on.

See the [Accessibility guide](/docs/next/accessibility#accessibilityignoresinvertcolors-ios) for more information.

| Type    |
| ------- |
| Boolean |

***

### `accessible`[​](#accessible "Direct link to accessible")

When `true`, indicates that the view is an accessibility element. By default, all the touchable elements are accessible.

| Type |
| ---- |
| bool |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the `Text` nodes separated by space.

| Type   |
| ------ |
| string |

***

### `accessibilityLanguage`iOS[​](#accessibilitylanguage-ios "Direct link to accessibilitylanguage-ios")

A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the [BCP 47 specification](https://www.rfc-editor.org/info/bcp47).

See the [iOS `accessibilityLanguage` doc](https://developer.apple.com/documentation/objectivec/nsobject/1615192-accessibilitylanguage) for more information.

| Type   |
| ------ |
| string |

***

### `accessibilityHint`[​](#accessibilityhint "Direct link to accessibilityhint")

An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label.

| Type   |
| ------ |
| string |

***

| Type   |
| ------ |
| string |

***

### `accessibilityState`[​](#accessibilitystate "Direct link to accessibilitystate")

Describes the current state of a component to the user of an assistive technology.

See the [Accessibility guide](/docs/next/accessibility#accessibilitystate) for more information.

| Type                                                                                             |
| ------------------------------------------------------------------------------------------------ |
| object: `{disabled: bool, selected: bool, checked: bool or 'mixed', busy: bool, expanded: bool}` |

***

### `accessibilityActions`[​](#accessibilityactions "Direct link to accessibilityactions")

Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The `accessibilityActions` property should contain a list of action objects. Each action object should contain the field name and label.

See the [Accessibility guide](/docs/next/accessibility#accessibility-actions) for more information.

| Type  |
| ----- |
| array |

***

### `aria-busy`[​](#aria-busy "Direct link to aria-busy")

Indicates an element is being modified and that assistive technologies may want to wait until the changes are complete before informing the user about the update.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-checked`[​](#aria-checked "Direct link to aria-checked")

Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

| Type             | Default |
| ---------------- | ------- |
| boolean, 'mixed' | false   |

***

### `aria-disabled`[​](#aria-disabled "Direct link to aria-disabled")

Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-expanded`[​](#aria-expanded "Direct link to aria-expanded")

Indicates whether an expandable element is currently expanded or collapsed.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-hidden`[​](#aria-hidden "Direct link to aria-hidden")

Indicates whether the element is hidden from assistive technologies.

For example, in a window that contains sibling views `A` and `B`, setting `aria-hidden` to `true` on view `B` causes VoiceOver to ignore the `B` element and its children.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-label`[​](#aria-label "Direct link to aria-label")

Defines a string value that labels an interactive element.

| Type   |
| ------ |
| string |

***

### `aria-live`Android[​](#aria-live-android "Direct link to aria-live-android")

Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

* **off** 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.

| Type                                     | Default |
| ---------------------------------------- | ------- |
| enum(`'assertive'`, `'off'`, `'polite'`) | `'off'` |

***

### `aria-modal`iOS[​](#aria-modal-ios "Direct link to aria-modal-ios")

Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. Has precedence over the [`accessibilityViewIsModal`](/docs/next/accessibility#accessibilityviewismodal-ios) prop.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-selected`[​](#aria-selected "Direct link to aria-selected")

Indicates whether a selectable element is currently selected or not.

| Type    |
| ------- |
| boolean |

### `onAccessibilityAction`[​](#onaccessibilityaction "Direct link to onaccessibilityaction")

Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

See the [Accessibility guide](/docs/next/accessibility#accessibility-actions) for more information.

| Type     |
| -------- |
| function |

***

### `accessibilityValue`[​](#accessibilityvalue "Direct link to accessibilityvalue")

Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, it contains range information (minimum, current, and maximum).

See the [Accessibility guide](/docs/next/accessibility#accessibilityvalue) for more information.

| Type                                                            |
| --------------------------------------------------------------- |
| object: `{min: number, max: number, now: number, text: string}` |

***

### `aria-valuemax`[​](#aria-valuemax "Direct link to aria-valuemax")

Represents the maximum value for range-based components, such as sliders and progress bars. Has precedence over the `max` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuemin`[​](#aria-valuemin "Direct link to aria-valuemin")

Represents the minimum value for range-based components, such as sliders and progress bars. Has precedence over the `min` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuenow`[​](#aria-valuenow "Direct link to aria-valuenow")

Represents the current value for range-based components, such as sliders and progress bars. Has precedence over the `now` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| number |

***

### `aria-valuetext`[​](#aria-valuetext "Direct link to aria-valuetext")

Represents the textual description of the component. Has precedence over the `text` value in the `accessibilityValue` prop.

| Type   |
| ------ |
| string |

***

### `delayLongPress`[​](#delaylongpress "Direct link to delaylongpress")

Duration (in milliseconds) from `onPressIn` before `onLongPress` is called.

| Type   |
| ------ |
| number |

***

### `delayPressIn`[​](#delaypressin "Direct link to delaypressin")

Duration (in milliseconds), from the start of the touch, before `onPressIn` is called.

| Type   |
| ------ |
| number |

***

### `delayPressOut`[​](#delaypressout "Direct link to delaypressout")

Duration (in milliseconds), from the release of the touch, before `onPressOut` is called.

| Type   |
| ------ |
| number |

***

### `disabled`[​](#disabled "Direct link to disabled")

If true, disable all interactions for this component.

| Type |
| ---- |
| bool |

***

### `hitSlop`[​](#hitslop "Direct link to hitslop")

This defines how far your touch can start away from the button. This is added to `pressRetentionOffset` when moving off of the button.

note

The touch area never extends past the parent view bounds and the Z-index of sibling views always takes precedence if a touch hits two overlapping views.

| Type                              |
| --------------------------------- |
| [Rect](/docs/next/rect) or number |

### `id`[​](#id "Direct link to id")

Used to locate this view from native code. Has precedence over `nativeID` prop.

| Type   |
| ------ |
| string |

***

### `onBlur`[​](#onblur "Direct link to onblur")

Invoked when the item loses focus.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: TargetEvent}) => void` |

***

### `onFocus`[​](#onfocus "Direct link to onfocus")

Invoked when the item receives focus.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: TargetEvent}) => void` |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: LayoutEvent}) => void` |

***

### `onLongPress`[​](#onlongpress "Direct link to onlongpress")

Called if the time after `onPressIn` lasts longer than 370 milliseconds. This time period can be customized with [`delayLongPress`](#delaylongpress).

| Type     |
| -------- |
| function |

***

### `onPress`[​](#onpress "Direct link to onpress")

Called when the touch is released, but not if cancelled (e.g. by a scroll that steals the responder lock). The first function argument is an event in form of [PressEvent](/docs/next/pressevent).

| Type     |
| -------- |
| function |

***

### `onPressIn`[​](#onpressin "Direct link to onpressin")

Called as soon as the touchable element is pressed and invoked even before onPress. This can be useful when making network requests. The first function argument is an event in form of [PressEvent](/docs/next/pressevent).

| Type     |
| -------- |
| function |

***

### `onPressOut`[​](#onpressout "Direct link to onpressout")

Called as soon as the touch is released even before onPress. The first function argument is an event in form of [PressEvent](/docs/next/pressevent).

| Type     |
| -------- |
| function |

***

### `pressRetentionOffset`[​](#pressretentionoffset "Direct link to pressretentionoffset")

When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view is disabled. Ensure you pass in a constant to reduce memory allocations.

| Type                              |
| --------------------------------- |
| [Rect](/docs/next/rect) or number |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

| Type   |
| ------ |
| string |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

| Type   |
| ------ |
| string |

***

### `touchSoundDisabled`Android[​](#touchsounddisabled-android "Direct link to touchsounddisabled-android")

If true, doesn't play a system sound on touch.

| Type    |
| ------- |
| Boolean |

* [Usage Pattern](#usage-pattern)

* [Example](#example)

* [Props](#props)

  * [`accessibilityIgnoresInvertColors`](#accessibilityignoresinvertcolors-ios)

    [iOS](#accessibilityignoresinvertcolors-ios)
  * [`accessible`](#accessible)
  * [`accessibilityLabel`](#accessibilitylabel)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)

    [Android](#aria-live-android)
  * [`aria-modal`](#aria-modal-ios)

    [iOS](#aria-modal-ios)

    [Android](#touchsounddisabled-android)

----
url: https://reactnative.dev/docs/next/vibration
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/vibration)** (0.87).

Version: Next

Vibrates the device.

## Example[​](#example "Direct link to Example")

info

Android apps should request the `android.permission.VIBRATE` permission by adding `<uses-permission android:name="android.permission.VIBRATE"/>` to `AndroidManifest.xml`.

note

The Vibration API is implemented as a `AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)` call on iOS.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `cancel()`[​](#cancel "Direct link to cancel")

React TSX

```
static cancel();
```

Call this to stop vibrating after having invoked `vibrate()` with repetition enabled.

***

### `vibrate()`[​](#vibrate "Direct link to vibrate")

React TSX

```
static vibrate(

  pattern?: number | number[],

  repeat?: boolean

);
```

Triggers a vibration with a fixed duration.

**On Android,** the vibration duration defaults to 400 milliseconds, and an arbitrary vibration duration can be specified by passing a number as the value for the `pattern` argument. **On iOS,** the vibration duration is fixed at roughly 400 milliseconds.

The `vibrate()` method can take a `pattern` argument with an array of numbers that represent time in milliseconds. You may set `repeat` to true to run through the vibration pattern in a loop until `cancel()` is called.

**On Android,** the odd indices of the `pattern` array represent the vibration duration, while the even ones represent the separation time. **On iOS,** the numbers in the `pattern` array represent the separation time, as the vibration duration is fixed.

**Parameters:**

| Name    | Type                             | Default | Description                                                                                     |
| ------- | -------------------------------- | ------- | ----------------------------------------------------------------------------------------------- |
| pattern | numberAndroid***array of numbers | `400`   | Vibration duration in milliseconds.***Vibration pattern as an array of numbers in milliseconds. |
| repeat  | boolean                          | `false` | Repeat vibration pattern until `cancel()`.                                                      |

* [Example](#example)

* [Methods](#methods)

  * [`cancel()`](#cancel)
  * [`vibrate()`](#vibrate)

----
url: https://reactnative.dev/docs/improvingux
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Check out [`TextInput` docs](/docs/textinput) for more configuration options.

* TypeScript
* JavaScript

## Manage layout when keyboard is visible[​](#manage-layout-when-keyboard-is-visible "Direct link to Manage layout when keyboard is visible")

Software keyboard takes almost half of the screen. If you have interactive elements that can get covered by the keyboard, make sure they are still accessible by using the [`KeyboardAvoidingView` component](/docs/keyboardavoidingview).

* TypeScript
* JavaScript

## Make tappable areas larger[​](#make-tappable-areas-larger "Direct link to Make tappable areas larger")

On mobile phones it's hard to be very precise when pressing buttons. Make sure all interactive elements are 44x44 or larger. One way to do this is to leave enough space for the element, `padding`, `minWidth` and `minHeight` style values can be useful for that. Alternatively, you can use [`hitSlop` prop](/docs/touchablewithoutfeedback#hitslop) to increase interactive area without affecting the layout. Here's a demo:

## Use Android Ripple[​](#use-android-ripple "Direct link to Use Android Ripple")

Android API 21+ uses the material design ripple to provide user with feedback when they touch an interactable area on the screen. React Native exposes this through the [`TouchableNativeFeedback` component](/docs/touchablenativefeedback). Using this touchable effect instead of opacity or highlight will often make your app feel much more fitting on the platform. That said, you need to be careful when using it because it doesn't work on iOS or on Android API < 21, so you will need to fallback to using one of the other Touchable components on iOS. You can use a library like [react-native-platform-touchable](https://github.com/react-community/react-native-platform-touchable) to handle the platform differences for you.

----
url: https://reactnative.dev/docs/systrace
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`Systrace` is a standard Android marker-based profiling tool (and is installed when you install the Android platform-tools package). Profiled code blocks are surrounded by start/end markers which are then visualized in a colorful chart format. Both the Android SDK and React Native framework provide standard markers that you can visualize.

## Example[​](#example "Direct link to Example")

`Systrace` allows you to mark JavaScript (JS) events with a tag and an integer value. Start profiling with an Android profiling tool such as Perfetto or EasyProfiler, then use these markers to identify the events in the captured trace.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `isEnabled()`[​](#isenabled "Direct link to isenabled")

React TSX

```
static isEnabled(): boolean;
```

***

### `beginEvent()`[​](#beginevent "Direct link to beginevent")

React TSX

```
static beginEvent(eventName: string | (() => string), args?: EventArgs);
```

beginEvent/endEvent for starting and then ending a profile within the same call stack frame.

***

### `endEvent()`[​](#endevent "Direct link to endevent")

React TSX

```
static endEvent(args?: EventArgs);
```

***

### `beginAsyncEvent()`[​](#beginasyncevent "Direct link to beginasyncevent")

React TSX

```
static beginAsyncEvent(

  eventName: string | (() => string),

  args?: EventArgs,

): number;
```

beginAsyncEvent/endAsyncEvent for starting and then ending a profile where the end can either occur on another thread or out of the current stack frame, eg await the returned cookie variable should be used as input into the endAsyncEvent call to end the profile.

***

### `endAsyncEvent()`[​](#endasyncevent "Direct link to endasyncevent")

React TSX

```
static endAsyncEvent(

  eventName: EventName,

  cookie: number,

  args?: EventArgs,

);
```

***

### `counterEvent()`[​](#counterevent "Direct link to counterevent")

React TSX

```
static counterEvent(eventName: string | (() => string), value: number);
```

----
url: https://reactnative.dev/docs/text-style-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

### Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

# Reference

## Props[​](#props "Direct link to Props")

### `color`[​](#color "Direct link to color")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `fontFamily`[​](#fontfamily "Direct link to fontfamily")

| Type   |
| ------ |
| string |

The generic font families `system-ui`, `ui-sans-serif`, `ui-serif`, `ui-monospace`, and `ui-rounded` are supported on iOS.

***

### `fontSize`[​](#fontsize "Direct link to fontsize")

| Type   |
| ------ |
| number |

***

### `fontStyle`[​](#fontstyle "Direct link to fontstyle")

| Type                         |
| ---------------------------- |
| enum(`'normal'`, `'italic'`) |

***

### `fontWeight`[​](#fontweight "Direct link to fontweight")

Specifies font weight. The values `'normal'` and `'bold'` are supported for most fonts. Not all fonts have a variant for each of the numeric values, in that case the closest one is chosen.

| Type                                                                                                                  | Default    |
| --------------------------------------------------------------------------------------------------------------------- | ---------- |
| enum(`'normal'`, `'bold'`, `'100'`, `'200'`, `'300'`, `'400'`, `'500'`, `'600'`, `'700'`, `'800'`, `'900'`) or number | `'normal'` |

***

### `includeFontPadding`Android[​](#includefontpadding-android "Direct link to includefontpadding-android")

Set to `false` to remove extra font padding intended to make space for certain ascenders / descenders. With some fonts, this padding can make text look slightly misaligned when centered vertically. For best results also set `textAlignVertical` to `center`.

| Type | Default |
| ---- | ------- |
| bool | `true`  |

***

### `fontVariant`[​](#fontvariant "Direct link to fontvariant")

Allows you to set all the font variants for a font. Can be set by using an array of enums or a space-separated string e.g. `'small-caps common-ligatures'`.

| Type                                                                                                                 | Default |
| -------------------------------------------------------------------------------------------------------------------- | ------- |
| array of enum(`'small-caps'`, `'oldstyle-nums'`, `'lining-nums'`, `'tabular-nums'`, `'proportional-nums'`) or string | `[]`    |

***

### `letterSpacing`[​](#letterspacing "Direct link to letterspacing")

Increase or decrease the spacing between characters. By default there is no extra letter spacing.

| Type   |
| ------ |
| number |

***

### `lineHeight`[​](#lineheight "Direct link to lineheight")

Numeric value that controls the vertical spacing between lines of text within a text element. It specifies the distance between the baselines of consecutive lines of text.

| Type   |
| ------ |
| number |

***

### `textAlign`[​](#textalign "Direct link to textalign")

Specifies text alignment. On Android, the value 'justify' is only supported on Oreo (8.0) or above (API level >= 26). The value will fallback to `left` on lower Android versions.

| Type                                                         | Default  |
| ------------------------------------------------------------ | -------- |
| enum(`'auto'`, `'left'`, `'right'`, `'center'`, `'justify'`) | `'auto'` |

***

### `textAlignVertical`Android[​](#textalignvertical-android "Direct link to textalignvertical-android")

An alias for `verticalAlign` style prop, if you use both properties, `verticalAlign` will take precedence over `textAlignVertical`

| Type                                            | Default  |
| ----------------------------------------------- | -------- |
| enum(`'auto'`, `'top'`, `'bottom'`, `'center'`) | `'auto'` |

***

### `textDecorationColor`iOS[​](#textdecorationcolor-ios "Direct link to textdecorationcolor-ios")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `textDecorationLine`[​](#textdecorationline "Direct link to textdecorationline")

| Type                                                                        | Default  |
| --------------------------------------------------------------------------- | -------- |
| enum(`'none'`, `'underline'`, `'line-through'`, `'underline line-through'`) | `'none'` |

***

### `textDecorationStyle`iOS[​](#textdecorationstyle-ios "Direct link to textdecorationstyle-ios")

| Type                                                | Default   |
| --------------------------------------------------- | --------- |
| enum(`'solid'`, `'double'`, `'dotted'`, `'dashed'`) | `'solid'` |

***

### `textShadowColor`[​](#textshadowcolor "Direct link to textshadowcolor")

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `textShadowOffset`[​](#textshadowoffset "Direct link to textshadowoffset")

| Type                                        |
| ------------------------------------------- |
| object: `{width?: number, height?: number}` |

***

### `textShadowRadius`[​](#textshadowradius "Direct link to textshadowradius")

| Type   |
| ------ |
| number |

***

### `textTransform`[​](#texttransform "Direct link to texttransform")

| Type                                                         | Default  |
| ------------------------------------------------------------ | -------- |
| enum(`'none'`, `'uppercase'`, `'lowercase'`, `'capitalize'`) | `'none'` |

***

### `verticalAlign`Android[​](#verticalalign-android "Direct link to verticalalign-android")

| Type                                            | Default  |
| ----------------------------------------------- | -------- |
| enum(`'auto'`, `'top'`, `'bottom'`, `'middle'`) | `'auto'` |

***

### `writingDirection`iOS[​](#writingdirection-ios "Direct link to writingdirection-ios")

| Type                             | Default  |
| -------------------------------- | -------- |
| enum(`'auto'`, `'ltr'`, `'rtl'`) | `'auto'` |

***

### `userSelect`[​](#userselect "Direct link to userselect")

It allows the user to select text and to use the native copy and paste functionality. Has precedence over the `selectable` prop.

| Type                                                     | Default |
| -------------------------------------------------------- | ------- |
| enum(`'auto'`, `'text'`, `'none'`, `'contain'`, `'all'`) | `none`  |

    [Android](#includefontpadding-android)
  * [`fontVariant`](#fontvariant)
  * [`letterSpacing`](#letterspacing)
  * [`lineHeight`](#lineheight)
  * [`textAlign`](#textalign)
  * [`textAlignVertical`](#textalignvertical-android)

    [Android](#textalignvertical-android)
  * [`textDecorationColor`](#textdecorationcolor-ios)

    [iOS](#textdecorationcolor-ios)
  * [`textDecorationLine`](#textdecorationline)
  * [`textDecorationStyle`](#textdecorationstyle-ios)

    [iOS](#textdecorationstyle-ios)
  * [`textShadowColor`](#textshadowcolor)
  * [`textShadowOffset`](#textshadowoffset)
  * [`textShadowRadius`](#textshadowradius)
  * [`textTransform`](#texttransform)
  * [`verticalAlign`](#verticalalign-android)

    [Android](#verticalalign-android)
  * [`writingDirection`](#writingdirection-ios)

    [iOS](#writingdirection-ios)
  * [`userSelect`](#userselect)

----
url: https://reactnative.dev/docs/next/dimensions
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/dimensions)** (0.87).

Version: Next

info

[`useWindowDimensions`](/docs/next/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.

React TSX

```
import {Dimensions} from 'react-native';
```

You can get the application window's width and height using the following code:

React TSX

```
const windowWidth = Dimensions.get('window').width;

const windowHeight = Dimensions.get('window').height;
```

```
static addEventListener(

  type: 'change',

  handler: ({

    window,

    screen,

  }: DimensionsPayload) => void,

): EventSubscription;
```

Add an event handler. Supported events:

* `change`: Fires when a property within the `Dimensions` object changes. The argument to the event handler is a [`DimensionsPayload`](#dimensionspayload) object.

***

### `get()`[​](#get "Direct link to get")

React TSX

```
static get(dim: string): DisplayMetrics | DisplayMetricsAndroid;
```

Initial dimensions are set before `runApplication` is called so they should be available before any other require's are run, but may be updated later.

Example: `const {height, width} = Dimensions.get('window');`

**Parameters:**

| Name        | Type   | Description                                                                       |
| ----------- | ------ | --------------------------------------------------------------------------------- |
| dimRequired | string | Name of dimension as defined when calling `set`. Returns value for the dimension. |

note

For Android the `window` dimension will be reduced by the size of status bar (if not translucent) and bottom navigation bar.

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### DimensionsPayload[​](#dimensionspayload "Direct link to DimensionsPayload")

**Properties:**

| Name                 | Type                                                                 | Description                             |
| -------------------- | -------------------------------------------------------------------- | --------------------------------------- |
| window               | [DisplayMetrics](/docs/next/dimensions#displaymetrics)               | Size of the visible application window. |
| screen               | [DisplayMetrics](/docs/next/dimensions#displaymetrics)               | Size of the device's screen.            |
| windowPhysicalPixels | [DisplayMetricsAndroid](/docs/next/dimensions#displaymetricsandroid) | Physical pixels for the Android window. |
| screenPhysicalPixels | [DisplayMetricsAndroid](/docs/next/dimensions#displaymetricsandroid) | Physical pixels for the Android screen. |

### DisplayMetrics[​](#displaymetrics "Direct link to DisplayMetrics")

| Type   |
| ------ |
| object |

**Properties:**

| Name      | Type   |
| --------- | ------ |
| width     | number |
| height    | number |
| scale     | number |
| fontScale | number |

### DisplayMetricsAndroid[​](#displaymetricsandroid "Direct link to DisplayMetricsAndroid")

`DisplayMetricsAndroid` includes all [`DisplayMetrics`](/docs/next/dimensions#displaymetrics) properties and the following property:

| Name       | Type   |
| ---------- | ------ |
| densityDpi | number |

----
url: https://reactnative.dev/docs/global-PerformanceEntry
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`PerformanceEntry`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry) class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/signed-apk-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
keytool -genkeypair -v -storetype PKCS12 -keystore my-upload-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
```

This command prompts you for passwords for the keystore and key and for the Distinguished Name fields for your key. It then generates the keystore as a file called `my-upload-key.keystore`.

The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app, so remember to take note of the alias.

### macOS[​](#macos "Direct link to macOS")

On macOS, if you're not sure where your JDK bin folder is, then perform the following command to find it:

```
/usr/libexec/java_home
```

It will output the directory of the JDK, which will look something like this:

```
/Library/Java/JavaVirtualMachines/jdkX.X.X_XXX.jdk/Contents/Home
```

Navigate to that directory by using the command `cd /your/jdk/path` and use the keytool command with sudo permission as shown below.

```
sudo keytool -genkey -v -keystore my-upload-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
```

caution

Remember to keep the keystore file private. In case you've lost upload key or it's been compromised you should [follow these instructions](https://support.google.com/googleplay/android-developer/answer/7384423#reset).

## Setting up Gradle variables[​](#setting-up-gradle-variables "Direct link to Setting up Gradle variables")

1. Place the `my-upload-key.keystore` file under the `android/app` directory in your project folder.
2. Edit the file `~/.gradle/gradle.properties` or `android/gradle.properties`, and add the following (replace `*****` with the correct keystore password, alias and key password),

```
MYAPP_UPLOAD_STORE_FILE=my-upload-key.keystore

MYAPP_UPLOAD_KEY_ALIAS=my-key-alias

MYAPP_UPLOAD_STORE_PASSWORD=*****

MYAPP_UPLOAD_KEY_PASSWORD=*****
```

```
...

android {

    ...

    defaultConfig { ... }

    signingConfigs {

        release {

            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {

                storeFile file(MYAPP_UPLOAD_STORE_FILE)

                storePassword MYAPP_UPLOAD_STORE_PASSWORD

                keyAlias MYAPP_UPLOAD_KEY_ALIAS

                keyPassword MYAPP_UPLOAD_KEY_PASSWORD

            }

        }

    }

    buildTypes {

        release {

            ...

            signingConfig signingConfigs.release

        }

    }

}

...
```

## Generating the release AAB[​](#generating-the-release-aab "Direct link to Generating the release AAB")

Run the following command in a terminal:

```
npx react-native build-android --mode=release
```

```
npm run android -- --mode="release"
```

```
yarn android --mode release
```

Note that `--mode release` is only available if you've set up signing as described above.

You can terminate any running bundler instances, since all your framework and JavaScript code is bundled in the APK's assets.

## Publishing to other stores[​](#publishing-to-other-stores "Direct link to Publishing to other stores")

By default, the generated APK has the native code for both `x86`, `x86_64`, `ARMv7a` and `ARM64-v8a` CPU architectures. This makes it easier to share APKs that run on almost all Android devices. However, this has the downside that there will be some unused native code on any device, leading to unnecessarily bigger APKs.

You can create an APK for each CPU by adding the following line in your `android/app/build.gradle` file:

Diff

```
android {



    splits {

        abi {

            reset()

            enable true

            universalApk false

            include "armeabi-v7a", "arm64-v8a", "x86", "x86_64"

        }

    }



}
```

```
/**

 * Run Proguard to shrink the Java bytecode in release builds.

 */

def enableProguardInReleaseBuilds = true
```

----
url: https://reactnative.dev/docs/linking-libraries-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
npm install <library-with-native-dependencies> --save
```

----
url: https://reactnative.dev/docs/next/global-process
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-process)** (0.87).

Version: Next

warning

🚧 This page is work in progress.

The global `process` object, as defined in Node.js.

----
url: https://reactnative.dev/docs/next/other-debugging-methods
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/other-debugging-methods)** (0.87).

Version: Next

This page covers how to use legacy JavaScript debugging methods. If you are getting started with a new React Native or Expo app, we recommend using [React Native DevTools](/docs/next/react-native-devtools).

----
url: https://reactnative.dev/docs/next/global-self
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-self)** (0.87).

Version: Next

[`self`](https://developer.mozilla.org/en-US/docs/Web/API/Window/self) is an alias for [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), as defined in Web specifications.

The use of `globalThis` is recommended over `self`.

----
url: https://reactnative.dev/docs/next/pixelratio
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/pixelratio)** (0.87).

Version: Next

`PixelRatio` gives you access to the device's pixel density and font scale.

## Fetching a correctly sized image[​](#fetching-a-correctly-sized-image "Direct link to Fetching a correctly sized image")

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.

React TSX

```
const image = getImage({

  width: PixelRatio.getPixelSizeForLayoutSize(200),

  height: PixelRatio.getPixelSizeForLayoutSize(100),

});

<Image source={image} style={{width: 200, height: 100}} />;
```

## Pixel grid snapping[​](#pixel-grid-snapping "Direct link to Pixel grid snapping")

In iOS, you can specify positions and dimensions for elements with arbitrary precision, for example 29.674825. But, ultimately the physical display only have a fixed number of pixels, for example 640×1136 for iPhone SE (1st generation) or 828×1792 for iPhone 11. iOS tries to be as faithful as possible to the user value by spreading one original pixel into multiple ones to trick the eye. The downside of this technique is that it makes the resulting element look blurry.

In practice, we found out that developers do not want this feature and they have to work around it by doing manual rounding in order to avoid having blurry elements. In React Native, we are rounding all the pixels automatically.

We have to be careful when to do this rounding. You never want to work with rounded and unrounded values at the same time as you're going to accumulate rounding errors. Having even one rounding error is deadly because a one pixel border may vanish or be twice as big.

In React Native, everything in JavaScript and within the layout engine works with arbitrary precision numbers. It's only when we set the position and dimensions of the native element on the main thread that we round. Also, rounding is done relative to the root rather than the parent, again to avoid accumulating rounding errors.

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `get()`[​](#get "Direct link to get")

React TSX

```
static get(): number;
```

***

### `getFontScale()`[​](#getfontscale "Direct link to getfontscale")

React TSX

```
static getFontScale(): number;
```

Returns the scaling factor for font sizes. This is the ratio that is used to calculate the absolute font size, so any elements that heavily depend on that should use this to do calculations.

* on Android value reflects the user preference set in **Settings > Display > Font size**
* on iOS value reflects the user preference set in **Settings > Display & Brightness > Text Size**, value can also be updated in **Settings > Accessibility > Display & Text Size > Larger Text**

If a font scale is not set, this returns the device pixel ratio.

***

### `getPixelSizeForLayoutSize()`[​](#getpixelsizeforlayoutsize "Direct link to getpixelsizeforlayoutsize")

React TSX

```
static getPixelSizeForLayoutSize(layoutSize: number): number;
```

Converts a layout size (dp) to pixel size (px).

Guaranteed to return an integer number.

***

### `roundToNearestPixel()`[​](#roundtonearestpixel "Direct link to roundtonearestpixel")

React TSX

```
static roundToNearestPixel(layoutSize: number): number;
```

----
url: https://reactnative.dev/docs/global-PerformanceLongTaskTiming
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`PerformanceLongTaskTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceLongTaskTiming) class, as defined in Web specifications.

Partial support

The value for the `attribution` property is always an empty array.

----
url: https://reactnative.dev/docs/global-console
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/console) for more information.

The global `console` object, as defined in Web specifications.

***

## Methods[​](#methods "Direct link to Methods")

### `timeStamp()`[​](#timestamp "Direct link to timestamp")

React TSX

```
console.timeStamp(

  label: string,

  start?: string | number,

  end?: string | number,

  trackName?: string,

  trackGroup?: string,

  color?: DevToolsColor

): void;
```

The `console.timeStamp` API allows you to add custom timing entries in the Performance panel timeline.

**Parameters:**

| Name       | Type               | Required | Description                                                                                                                                                                                                                                                                       |
| ---------- | ------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| label      | `string`           | Yes      | The label for the timing entry.                                                                                                                                                                                                                                                   |
| start      | `string \| number` | No       | * If string, the name of a previously recorded timestamp with `console.timeStamp`.
* If number, the [DOMHighResTimeStamp](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp). For example, from `performance.now()`.
* If undefined, the current time is used. |
| end        | `string \| number` | No       | - If string, the name of a previously recorded timestamp with `console.timeStamp`.
- If number, the [DOMHighResTimeStamp](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp). For example, from `performance.now()`.
- If undefined, the current time is used. |
| trackName  | `string`           | No       | The name of the custom track.                                                                                                                                                                                                                                                     |
| trackGroup | `string`           | No       | The name of the track group.                                                                                                                                                                                                                                                      |
| color      | `DevToolsColor`    | No       | The color of the entry.                                                                                                                                                                                                                                                           |

React TSX

```
type DevToolsColor =

  | 'primary'

  | 'primary-light'

  | 'primary-dark'

  | 'secondary'

  | 'secondary-light'

  | 'secondary-dark'

  | 'tertiary'

  | 'tertiary-light'

  | 'tertiary-dark'

  | 'warning'

  | 'error';
```

* [Methods](#methods)
  * [`timeStamp()`](#timestamp)

----
url: https://reactnative.dev/docs/fabric-native-components-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
cd android

./gradlew generateCodegenArtifactsFromSchema
```

```
package com.webview;



import android.content.Context;

import android.util.AttributeSet;

import android.webkit.WebView;

import android.webkit.WebViewClient;



import com.facebook.react.bridge.Arguments;

import com.facebook.react.bridge.WritableMap;

import com.facebook.react.bridge.ReactContext;

import com.facebook.react.uimanager.UIManagerHelper;

import com.facebook.react.uimanager.events.Event;



public class ReactWebView extends WebView {

  public ReactWebView(Context context) {

    super(context);

    configureComponent();

  }



  public ReactWebView(Context context, AttributeSet attrs) {

    super(context, attrs);

    configureComponent();

  }



  public ReactWebView(Context context, AttributeSet attrs, int defStyleAttr) {

    super(context, attrs, defStyleAttr);

    configureComponent();

  }



  private void configureComponent() {

    this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    this.setWebViewClient(new WebViewClient() {

      @Override

      public void onPageFinished(WebView view, String url) {

        emitOnScriptLoaded(OnScriptLoadedEventResult.success);

      }

    });

  }



  public void emitOnScriptLoaded(OnScriptLoadedEventResult result) {

    ReactContext reactContext = (ReactContext) context;

    int surfaceId = UIManagerHelper.getSurfaceId(reactContext);

    EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());

    WritableMap payload = Arguments.createMap();

    payload.putString("result", result.name());



    OnScriptLoadedEvent event = new OnScriptLoadedEvent(surfaceId, getId(), payload);

    if (eventDispatcher != null) {

      eventDispatcher.dispatchEvent(event);

    }

  }



  public enum OnScriptLoadedEventResult {

    success,

    error

  }



  private class OnScriptLoadedEvent extends Event<OnScriptLoadedEvent> {

    private final WritableMap payload;



    OnScriptLoadedEvent(int surfaceId, int viewId, WritableMap payload) {

      super(surfaceId, viewId);

      this.payload = payload;

    }



    @Override

    public String getEventName() {

      return "onScriptLoaded";

    }



    @Override

    public WritableMap getEventData() {

      return payload;

    }

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebView\.kt

```
package com.webview



import android.content.Context

import android.util.AttributeSet

import android.webkit.WebView

import android.webkit.WebViewClient

import com.facebook.react.bridge.Arguments

import com.facebook.react.bridge.WritableMap

import com.facebook.react.bridge.ReactContext

import com.facebook.react.uimanager.UIManagerHelper

import com.facebook.react.uimanager.events.Event



class ReactWebView: WebView {

  constructor(context: Context) : super(context) {

    configureComponent()

  }



  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {

    configureComponent()

  }



  constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {

    configureComponent()

  }



  private fun configureComponent() {

    this.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)

    this.webViewClient = object : WebViewClient() {

      override fun onPageFinished(view: WebView, url: String) {

        emitOnScriptLoaded(OnScriptLoadedEventResult.success)

      }

    }

  }



  fun emitOnScriptLoaded(result: OnScriptLoadedEventResult) {

    val reactContext = context as ReactContext

    val surfaceId = UIManagerHelper.getSurfaceId(reactContext)

    val eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id)

    val payload =

        Arguments.createMap().apply {

          putString("result", result.name)

        }

    val event = OnScriptLoadedEvent(surfaceId, id, payload)



    eventDispatcher?.dispatchEvent(event)

  }



  enum class OnScriptLoadedEventResult {

    success,

    error;

  }



  inner class OnScriptLoadedEvent(

      surfaceId: Int,

      viewId: Int,

      private val payload: WritableMap

  ) : Event<OnScriptLoadedEvent>(surfaceId, viewId) {

    override fun getEventName() = "onScriptLoaded"



    override fun getEventData() = payload

  }

}
```

```
package com.webview;



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.annotations.ReactModule;

import com.facebook.react.uimanager.SimpleViewManager;

import com.facebook.react.uimanager.ThemedReactContext;

import com.facebook.react.uimanager.ViewManagerDelegate;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;

import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;



import java.util.HashMap;

import java.util.Map;



@ReactModule(name = ReactWebViewManager.REACT_CLASS)

class ReactWebViewManager extends SimpleViewManager<ReactWebView> implements CustomWebViewManagerInterface<ReactWebView> {

  private final CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> delegate =

          new CustomWebViewManagerDelegate<>(this);



  @Override

  public ViewManagerDelegate<ReactWebView> getDelegate() {

    return delegate;

  }



  @Override

  public String getName() {

    return REACT_CLASS;

  }



  @Override

  public ReactWebView createViewInstance(ThemedReactContext context) {

    return new ReactWebView(context);

  }



  @ReactProp(name = "sourceUrl")

  @Override

  public void setSourceURL(ReactWebView view, String sourceURL) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error);

      return;

    }

    view.loadUrl(sourceURL, new HashMap<>());

  }



  public static final String REACT_CLASS = "CustomWebView";



  @Override

  public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {

    Map<String, Object> map = new HashMap<>();

    Map<String, Object> bubblingMap = new HashMap<>();

    bubblingMap.put("phasedRegistrationNames", new HashMap<String, String>() {{

      put("bubbled", "onScriptLoaded");

      put("captured", "onScriptLoadedCapture");

    }});

    map.put("onScriptLoaded", bubblingMap);

    return map;

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebViewManager.kt

```
package com.webview



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.annotations.ReactModule;

import com.facebook.react.uimanager.SimpleViewManager;

import com.facebook.react.uimanager.ThemedReactContext;

import com.facebook.react.uimanager.ViewManagerDelegate;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;

import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;



@ReactModule(name = ReactWebViewManager.REACT_CLASS)

class ReactWebViewManager(context: ReactApplicationContext) : SimpleViewManager<ReactWebView>(), CustomWebViewManagerInterface<ReactWebView> {

  private val delegate: CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> =

    CustomWebViewManagerDelegate(this)



  override fun getDelegate(): ViewManagerDelegate<ReactWebView> = delegate



  override fun getName(): String = REACT_CLASS



  override fun createViewInstance(context: ThemedReactContext): ReactWebView = ReactWebView(context)



  @ReactProp(name = "sourceUrl")

  override fun setSourceURL(view: ReactWebView, sourceURL: String?) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error)

      return;

    }

    view.loadUrl(sourceURL, emptyMap())

  }



  companion object {

    const val REACT_CLASS = "CustomWebView"

  }



  override fun getExportedCustomBubblingEventTypeConstants(): Map<String, Any> =

      mapOf(

          "onScriptLoaded" to

              mapOf(

                  "phasedRegistrationNames" to

                      mapOf(

                          "bubbled" to "onScriptLoaded",

                          "captured" to "onScriptLoadedCapture"

                      )))

}
```

```
package com.webview;



import com.facebook.react.BaseReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.model.ReactModuleInfo;

import com.facebook.react.module.model.ReactModuleInfoProvider;

import com.facebook.react.uimanager.ViewManager;



import java.util.Collections;

import java.util.HashMap;

import java.util.List;

import java.util.Map;



public class ReactWebViewPackage extends BaseReactPackage {

  @Override

  public List<ViewManager<?, ?>> createViewManagers(ReactApplicationContext reactContext) {

    return Collections.singletonList(new ReactWebViewManager(reactContext));

  }



  @Override

  public NativeModule getModule(String s, ReactApplicationContext reactApplicationContext) {

    if (ReactWebViewManager.REACT_CLASS.equals(s)) {

      return new ReactWebViewManager(reactApplicationContext);

    }

    return null;

  }



  @Override

  public ReactModuleInfoProvider getReactModuleInfoProvider() {

    return new ReactModuleInfoProvider() {

      @Override

      public Map<String, ReactModuleInfo> getReactModuleInfos() {

        Map<String, ReactModuleInfo> map = new HashMap<>();

        map.put(ReactWebViewManager.REACT_CLASS, new ReactModuleInfo(

                ReactWebViewManager.REACT_CLASS, // name

                ReactWebViewManager.REACT_CLASS, // className

                false,                           // canOverrideExistingModule

                false,                           // needsEagerInit

                false,                           // isCxxModule

                true                             // isTurboModule

        ));

        return map;

      }

    };

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebViewPackage.kt

```
package com.webview



import com.facebook.react.BaseReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.module.model.ReactModuleInfo

import com.facebook.react.module.model.ReactModuleInfoProvider

import com.facebook.react.uimanager.ViewManager



class ReactWebViewPackage : BaseReactPackage() {

  override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {

    return listOf(ReactWebViewManager(reactContext))

  }



  override fun getModule(s: String, reactApplicationContext: ReactApplicationContext): NativeModule? {

    when (s) {

      ReactWebViewManager.REACT_CLASS -> ReactWebViewManager(reactApplicationContext)

    }

    return null

  }



  override fun getReactModuleInfoProvider(): ReactModuleInfoProvider = ReactModuleInfoProvider {

    mapOf(ReactWebViewManager.REACT_CLASS to ReactModuleInfo(

      name = ReactWebViewManager.REACT_CLASS,

      className = ReactWebViewManager.REACT_CLASS,

      canOverrideExistingModule = false,

      needsEagerInit = false,

      isCxxModule = false,

      isTurboModule = true,

    )

    )

  }

}
```

```
package com.demo



import android.app.Application

import com.facebook.react.PackageList

import com.facebook.react.ReactApplication

import com.facebook.react.ReactHost

import com.facebook.react.ReactNativeHost

import com.facebook.react.ReactPackage

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

import com.facebook.react.defaults.DefaultReactNativeHost

import com.facebook.react.soloader.OpenSourceMergedSoMapping

import com.facebook.soloader.SoLoader

import com.webview.ReactWebViewPackage



class MainApplication : Application(), ReactApplication {



  override val reactNativeHost: ReactNativeHost =

      object : DefaultReactNativeHost(this) {

        override fun getPackages(): List<ReactPackage> =

            PackageList(this).packages.apply {

              add(ReactWebViewPackage())

            }



        override fun getJSMainModuleName(): String = "index"



        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG



        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

      }



  override val reactHost: ReactHost

    get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

    SoLoader.init(this, OpenSourceMergedSoMapping)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      load()

    }

  }

}
```

* [1. Run Codegen through Gradle](#1-run-codegen-through-gradle)
* [2. Write the `ReactWebView`](#2-write-the-reactwebview)
* [3. Write the `WebViewManager`](#3-write-the-webviewmanager)
* [4. Write the `ReactWebViewPackage`](#4-write-the-reactwebviewpackage)
* [5. Register the `ReactWebViewPackage` in the application](#5-register-the-reactwebviewpackage-in-the-application)

----
url: https://reactnative.dev/docs/intro-react-native-components
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React Native also lets you build your own Native Components for [Android](/docs/legacy/native-components-android) and [iOS](/docs/legacy/native-components-ios) to suit your app’s unique needs. We also have a thriving ecosystem of these **community-contributed components.** Check out [Native Directory](https://reactnative.directory) to find what the community has been creating.

## Core Components[​](#core-components "Direct link to Core Components")

React Native has many Core Components for everything from controls to activity indicators. You can find them all [documented in the API section](/docs/components-and-apis). You will mostly work with the following Core Components:

| React Native UI Component | Android View   | iOS View         | Web Analog              | Description                                                                                           |
| ------------------------- | -------------- | ---------------- | ----------------------- | ----------------------------------------------------------------------------------------------------- |
| `<View>`                  | `<ViewGroup>`  | `<UIView>`       | A non-scrolling `<div>` | A container that supports layout with flexbox, style, some touch handling, and accessibility controls |
| `<Text>`                  | `<TextView>`   | `<UITextView>`   | `<p>`                   | Displays, styles, and nests strings of text and even handles touch events                             |
| `<Image>`                 | `<ImageView>`  | `<UIImageView>`  | `<img>`                 | Displays different types of images                                                                    |
| `<ScrollView>`            | `<ScrollView>` | `<UIScrollView>` | `<div>`                 | A generic scrolling container that can contain multiple components and views                          |
| `<TextInput>`             | `<EditText>`   | `<UITextField>`  | `<input type="text">`   | Allows the user to enter text                                                                         |

In the next section, you will start combining these Core Components to learn about how React works. Have a play with them here now!

***

Because React Native uses the same API structure as React components, you’ll need to understand React component APIs to get started. The [next section](/docs/intro-react) makes for a quick introduction or refresher on the topic. However, if you’re already familiar with React, feel free to [skip ahead](/docs/handling-text-input).

* [Views and mobile development](#views-and-mobile-development)
* [Native Components](#native-components)
* [Core Components](#core-components)

----
url: https://reactnative.dev/docs/next/accessibilityinfo
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/accessibilityinfo)** (0.87).

Version: Next

Sometimes it's useful to know whether or not the device has a screen reader that is currently active. The `AccessibilityInfo` API is designed for this purpose. You can use it to query the current state of the screen reader as well as to register to be notified when the state of the screen reader changes.

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `addEventListener()`[​](#addeventlistener "Direct link to addeventlistener")

React TSX

```
static addEventListener(

  eventName: AccessibilityChangeEventName | AccessibilityAnnouncementEventName,

  handler: (

    event: AccessibilityChangeEvent | AccessibilityAnnouncementFinishedEvent,

  ) => void,

): EventSubscription;
```

Add an event handler. Supported events:

| Event name                            | Description                                                                                                                                                                                                                                                                        |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `accessibilityServiceChanged` Android | Fires when some services such as TalkBack, other Android assistive technologies, and third-party accessibility services are enabled. The argument to the event handler is a boolean. The boolean is `true` when a some accessibility services is enabled and `false` otherwise.    |
| `announcementFinished` iOS            | Fires when the screen reader has finished making an announcement. The argument to the event handler is a dictionary with these keys:- `announcement`: The string announced by the screen reader.
- `success`: A boolean indicating whether the announcement was successfully made. |
| `boldTextChanged` iOS                 | Fires when the state of the bold text toggle changes. The argument to the event handler is a boolean. The boolean is `true` when bold text is enabled and `false` otherwise.                                                                                                       |
| `grayscaleChanged` iOS                | Fires when the state of the gray scale toggle changes. The argument to the event handler is a boolean. The boolean is `true` when a gray scale is enabled and `false` otherwise.                                                                                                   |
| `invertColorsChanged` iOS             | Fires when the state of the invert colors toggle changes. The argument to the event handler is a boolean. The boolean is `true` when invert colors is enabled and `false` otherwise.                                                                                               |
| `reduceMotionChanged`                 | Fires when the state of the reduce motion toggle changes. The argument to the event handler is a boolean. The boolean is `true` when a reduce motion is enabled (or when "Transition Animation Scale" in "Developer options" is "Animation off") and `false` otherwise.            |
| `reduceTransparencyChanged` iOS       | Fires when the state of the reduce transparency toggle changes. The argument to the event handler is a boolean. The boolean is `true` when reduce transparency is enabled and `false` otherwise.                                                                                   |
| `screenReaderChanged`                 | Fires when the state of the screen reader changes. The argument to the event handler is a boolean. The boolean is `true` when a screen reader is enabled and `false` otherwise.                                                                                                    |

***

### `announceForAccessibility()`[​](#announceforaccessibility "Direct link to announceforaccessibility")

React TSX

```
static announceForAccessibility(announcement: string);
```

Post a string to be announced by the screen reader.

***

### `announceForAccessibilityWithOptions()`[​](#announceforaccessibilitywithoptions "Direct link to announceforaccessibilitywithoptions")

React TSX

```
static announceForAccessibilityWithOptions(

  announcement: string,

  options: {

    queue?: boolean;

    priority?: 'low' | 'default' | 'high';

  },

);
```

Post a string to be announced by the screen reader with modification options. By default announcements will interrupt any existing speech, but on iOS they can be queued behind existing speech by setting `queue` to `true` in the options object. An optional `priority` can also be specified on iOS.

**Parameters:**

| Name                 | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| -------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| announcementRequired | string | The string to be announced                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| optionsRequired      | object | Options object with the following keys:- `queue`: Queue the announcement behind existing speech.

  iOS
- `priority`: The priority of the announcement (`'low'`, `'default'`, or `'high'`). High priority announcements will interrupt any ongoing speech and cannot be interrupted. Default priority announcements will interrupt any ongoing speech but can be interrupted. Low priority announcements will not interrupt ongoing speech and can be interrupted.

  iOS |

***

### `getRecommendedTimeoutMillis()`Android[​](#getrecommendedtimeoutmillis-android "Direct link to getrecommendedtimeoutmillis-android")

React TSX

```
static getRecommendedTimeoutMillis(originalTimeout: number): Promise<number>;
```

Gets the timeout in millisecond that the user needs. This value is set in "Time to take action (Accessibility timeout)" of "Accessibility" settings.

**Parameters:**

| Name                    | Type   | Description                                                                           |
| ----------------------- | ------ | ------------------------------------------------------------------------------------- |
| originalTimeoutRequired | number | The timeout to return if "Accessibility timeout" is not set. Specify in milliseconds. |

***

### `isAccessibilityServiceEnabled()`Android[​](#isaccessibilityserviceenabled-android "Direct link to isaccessibilityserviceenabled-android")

React TSX

```
static isAccessibilityServiceEnabled(): Promise<boolean>;
```

Check whether any accessibility service is enabled. This includes TalkBack but also any third-party accessibility app that may be installed. To only check whether TalkBack is enabled, use [isScreenReaderEnabled](#isscreenreaderenabled). Returns a promise which resolves to a boolean. The result is `true` when some accessibility services is enabled and `false` otherwise.

note

Please use [`isScreenReaderEnabled`](#isscreenreaderenabled) if you only want to check the status of TalkBack.

***

### `isBoldTextEnabled()`iOS[​](#isboldtextenabled-ios "Direct link to isboldtextenabled-ios")

React TSX

```
static isBoldTextEnabled(): Promise<boolean>:
```

Query whether a bold text is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when bold text is enabled and `false` otherwise.

***

### `isGrayscaleEnabled()`iOS[​](#isgrayscaleenabled-ios "Direct link to isgrayscaleenabled-ios")

React TSX

```
static isGrayscaleEnabled(): Promise<boolean>;
```

Query whether grayscale is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when grayscale is enabled and `false` otherwise.

***

### `isInvertColorsEnabled()`iOS[​](#isinvertcolorsenabled-ios "Direct link to isinvertcolorsenabled-ios")

React TSX

```
static isInvertColorsEnabled(): Promise<boolean>;
```

Query whether invert colors is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when invert colors is enabled and `false` otherwise.

***

### `isReduceMotionEnabled()`[​](#isreducemotionenabled "Direct link to isreducemotionenabled")

React TSX

```
static isReduceMotionEnabled(): Promise<boolean>;
```

Query whether reduce motion is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when reduce motion is enabled and `false` otherwise.

***

### `isReduceTransparencyEnabled()`iOS[​](#isreducetransparencyenabled-ios "Direct link to isreducetransparencyenabled-ios")

React TSX

```
static isReduceTransparencyEnabled(): Promise<boolean>;
```

Query whether reduce transparency is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when a reduce transparency is enabled and `false` otherwise.

***

### `isScreenReaderEnabled()`[​](#isscreenreaderenabled "Direct link to isscreenreaderenabled")

React TSX

```
static isScreenReaderEnabled(): Promise<boolean>;
```

Query whether a screen reader is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when a screen reader is enabled and `false` otherwise.

***

### `isHighTextContrastEnabled()`Android[​](#ishightextcontrastenabled-android "Direct link to ishightextcontrastenabled-android")

React TSX

```
static isHighTextContrastEnabled(): Promise<boolean>
```

Query whether high text contrast is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when high text contrast is enabled and `false` otherwise.

***

### `isDarkerSystemColorsEnabled()`iOS[​](#isdarkersystemcolorsenabled-ios "Direct link to isdarkersystemcolorsenabled-ios")

React TSX

```
static isDarkerSystemColorsEnabled(): Promise<boolean>
```

Query whether dark system colors is currently enabled. Returns a promise which resolves to a boolean. The result is `true` when dark system colors is enabled and `false` otherwise.

***

### `prefersCrossFadeTransitions()`iOS[​](#preferscrossfadetransitions-ios "Direct link to preferscrossfadetransitions-ios")

React TSX

```
static prefersCrossFadeTransitions(): Promise<boolean>;
```

Query whether reduce motion and prefer cross-fade transitions settings are currently enabled. Returns a promise which resolves to a boolean. The result is `true` when prefer cross-fade transitions is enabled and `false` otherwise.

***

### 🗑️ `setAccessibilityFocus()`[​](#️-setaccessibilityfocus "Direct link to ️-setaccessibilityfocus")

Deprecated

Prefer using `sendAccessibilityEvent` with eventType `focus` instead.

React TSX

```
static setAccessibilityFocus(reactTag: number);
```

Set accessibility focus to a React component.

On Android, this calls `UIManager.sendAccessibilityEvent` method with passed `reactTag` and `UIManager.AccessibilityEventTypes.typeViewFocused` arguments.

note

Make sure that any `View` you want to receive the accessibility focus has `accessible={true}`.

***

### `sendAccessibilityEvent()`[​](#sendaccessibilityevent "Direct link to sendaccessibilityevent")

React TSX

```
static sendAccessibilityEvent(host: HostInstance, eventType: AccessibilityEventTypes);
```

Imperatively trigger an accessibility event on a React component, like changing the focused element for a screen reader.

note

Make sure that any `View` you want to receive the accessibility focus has `accessible={true}`.

| Name              | Type                    | Description                                                                                                            |
| ----------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| hostRequired      | HostInstance            | The component ref to send the event to.                                                                                |
| eventTypeRequired | AccessibilityEventTypes | One of `'click'` (Android only), `'focus'`, `'viewHoverEnter'` (Android only), or `'windowStateChange'` (Android only) |

* [Example](#example)

* [Methods](#methods)

  * [`addEventListener()`](#addeventlistener)
  * [`announceForAccessibility()`](#announceforaccessibility)
  * [`announceForAccessibilityWithOptions()`](#announceforaccessibilitywithoptions)
  * [`getRecommendedTimeoutMillis()`](#getrecommendedtimeoutmillis-android)

    [Android](#getrecommendedtimeoutmillis-android)
  * [`isAccessibilityServiceEnabled()`](#isaccessibilityserviceenabled-android)

    [Android](#isaccessibilityserviceenabled-android)
  * [`isBoldTextEnabled()`](#isboldtextenabled-ios)

    [iOS](#isboldtextenabled-ios)
  * [`isGrayscaleEnabled()`](#isgrayscaleenabled-ios)

    [iOS](#isgrayscaleenabled-ios)
  * [`isInvertColorsEnabled()`](#isinvertcolorsenabled-ios)

    [iOS](#isinvertcolorsenabled-ios)
  * [`isReduceMotionEnabled()`](#isreducemotionenabled)
  * [`isReduceTransparencyEnabled()`](#isreducetransparencyenabled-ios)

    [iOS](#isreducetransparencyenabled-ios)
  * [`isScreenReaderEnabled()`](#isscreenreaderenabled)
  * [`isHighTextContrastEnabled()`](#ishightextcontrastenabled-android)

    [Android](#ishightextcontrastenabled-android)
  * [`isDarkerSystemColorsEnabled()`](#isdarkersystemcolorsenabled-ios)

    [iOS](#isdarkersystemcolorsenabled-ios)
  * [`prefersCrossFadeTransitions()`](#preferscrossfadetransitions-ios)

    [iOS](#preferscrossfadetransitions-ios)
  * [🗑️ `setAccessibilityFocus()`](#️-setaccessibilityfocus)
  * [`sendAccessibilityEvent()`](#sendaccessibilityevent)

----
url: https://reactnative.dev/docs/next/datepickerios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/datepickerios)** (0.87).

Version: Next

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=datepicker) instead.

----
url: https://reactnative.dev/docs/next/panresponder
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/panresponder)** (0.87).

Version: Next

`PanResponder` reconciles several touches into a single gesture. It makes single-touch gestures resilient to extra touches, and can be used to recognize basic multi-touch gestures.

By default, `PanResponder` holds an interaction handle to block long-running JS events from interrupting active gestures.

It provides a predictable wrapper of the responder handlers provided by the [gesture responder system](/docs/next/gesture-responder-system). For each handler, it provides a new `gestureState` object alongside the native event object:

```
onPanResponderMove: (event, gestureState) => {}
```

A native event is a synthetic touch event with form of [PressEvent](/docs/next/pressevent).

```
const ExampleComponent = () => {

  const panResponder = useRef(

    PanResponder.create({

      // Ask to be the responder:

      onStartShouldSetPanResponder: (evt, gestureState) => true,

      onStartShouldSetPanResponderCapture: (evt, gestureState) =>

        true,

      onMoveShouldSetPanResponder: (evt, gestureState) => true,

      onMoveShouldSetPanResponderCapture: (evt, gestureState) =>

        true,



      onPanResponderGrant: (evt, gestureState) => {

        // The gesture has started. Show visual feedback so the user knows

        // what is happening!

        // gestureState.d{x,y} will be set to zero now

      },

      onPanResponderMove: (evt, gestureState) => {

        // The most recent move distance is gestureState.move{X,Y}

        // The accumulated gesture distance since becoming responder is

        // gestureState.d{x,y}

      },

      onPanResponderTerminationRequest: (evt, gestureState) =>

        true,

      onPanResponderRelease: (evt, gestureState) => {

        // The user has released all touches while this view is the

        // responder. This typically means a gesture has succeeded

      },

      onPanResponderTerminate: (evt, gestureState) => {

        // Another component has become the responder, so this gesture

        // should be cancelled

      },

      onShouldBlockNativeResponder: (evt, gestureState) => {

        // Returns whether this component should block native components from becoming the JS

        // responder. Returns true by default. Is currently only supported on android.

        return true;

      },

    }),

  ).current;



  return <View {...panResponder.panHandlers} />;

};
```

## Example[​](#example "Direct link to Example")

`PanResponder` works with `Animated` API to help build complex gestures in the UI. The following example contains an animated `View` component which can be dragged freely across the screen

Try the [PanResponder example in RNTester](https://github.com/react/react-native/blob/main/packages/rn-tester/js/examples/PanResponder/PanResponderExample.js).

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `create()`[​](#create "Direct link to create")

React TSX

```
static create(config: PanResponderCallbacks): PanResponderInstance;
```

**Parameters:**

| Name           | Type   | Description |
| -------------- | ------ | ----------- |
| configRequired | object | Refer below |

The `config` object provides enhanced versions of all of the responder callbacks that provide not only the [`PressEvent`](/docs/next/pressevent), but also the `PanResponder` gesture state, by replacing the word `Responder` with `PanResponder` in each of the typical `onResponder*` callbacks. For example, the `config` object would look like:

----
url: https://reactnative.dev/docs/easing
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The `Easing` module implements common easing functions. This module is used by [`Animated.timing()`](/docs/animated#timing) to convey physically believable motion in animations.

You can find a visualization of some common easing functions at <https://easings.net/>

### Predefined animations[​](#predefined-animations "Direct link to Predefined animations")

The `Easing` module provides several predefined animations through the following methods:

* [`back`](/docs/easing#back) provides a basic animation where the object goes slightly back before moving forward
* [`bounce`](/docs/easing#bounce) provides a bouncing animation
* [`ease`](/docs/easing#ease) provides a basic inertial animation
* [`elastic`](/docs/easing#elastic) provides a basic spring interaction

### Standard functions[​](#standard-functions "Direct link to Standard functions")

Three standard easing functions are provided:

* [`linear`](/docs/easing#linear)
* [`quad`](/docs/easing#quad)
* [`cubic`](/docs/easing#cubic)

The [`poly`](/docs/easing#poly) function can be used to implement quartic, quintic, and other higher power functions.

### Additional functions[​](#additional-functions "Direct link to Additional functions")

Additional mathematical functions are provided by the following methods:

* [`bezier`](/docs/easing#bezier) provides a cubic bezier curve
* [`circle`](/docs/easing#circle) provides a circular function
* [`sin`](/docs/easing#sin) provides a sinusoidal function
* [`exp`](/docs/easing#exp) provides an exponential function

The following helpers are used to modify other easing functions.

* [`in`](/docs/easing#in) runs an easing function forwards
* [`inOut`](/docs/easing#inout) makes any easing function symmetrical
* [`out`](/docs/easing#out) runs an easing function backwards

## Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `step0()`[​](#step0 "Direct link to step0")

React TSX

```
static step0(n: number);
```

A stepping function, returns 1 for any positive value of `n`.

***

### `step1()`[​](#step1 "Direct link to step1")

React TSX

```
static step1(n: number);
```

A stepping function, returns 1 if `n` is greater than or equal to 1.

***

### `linear()`[​](#linear "Direct link to linear")

React TSX

```
static linear(t: number);
```

A linear function, `f(t) = t`. Position correlates to elapsed time one to one.

<https://cubic-bezier.com/#0,0,1,1>

***

### `ease()`[​](#ease "Direct link to ease")

React TSX

```
static ease(t: number);
```

A basic inertial interaction, similar to an object slowly accelerating to speed.

<https://cubic-bezier.com/#.42,0,1,1>

***

### `quad()`[​](#quad "Direct link to quad")

React TSX

```
static quad(t: number);
```

A quadratic function, `f(t) = t * t`. Position equals the square of elapsed time.

<https://easings.net/#easeInQuad>

***

### `cubic()`[​](#cubic "Direct link to cubic")

React TSX

```
static cubic(t: number);
```

A cubic function, `f(t) = t * t * t`. Position equals the cube of elapsed time.

<https://easings.net/#easeInCubic>

***

### `poly()`[​](#poly "Direct link to poly")

React TSX

```
static poly(n: number);
```

A power function. Position is equal to the Nth power of elapsed time.

n = 4: <https://easings.net/#easeInQuart> n = 5: <https://easings.net/#easeInQuint>

***

### `sin()`[​](#sin "Direct link to sin")

React TSX

```
static sin(t: number);
```

A sinusoidal function.

<https://easings.net/#easeInSine>

***

### `circle()`[​](#circle "Direct link to circle")

React TSX

```
static circle(t: number);
```

A circular function.

<https://easings.net/#easeInCirc>

***

### `exp()`[​](#exp "Direct link to exp")

React TSX

```
static exp(t: number);
```

An exponential function.

<https://easings.net/#easeInExpo>

***

### `elastic()`[​](#elastic "Direct link to elastic")

React TSX

```
static elastic(bounciness: number);
```

A basic elastic interaction, similar to a spring oscillating back and forth.

Default bounciness is 1, which overshoots a little bit once. 0 bounciness doesn't overshoot at all, and bounciness of N > 1 will overshoot about N times.

<https://easings.net/#easeInElastic>

***

### `back()`[​](#back "Direct link to back")

React TSX

```
static back(s)
```

Use with `Animated.parallel()` to create a basic effect where the object animates back slightly as the animation starts.

***

### `bounce()`[​](#bounce "Direct link to bounce")

React TSX

```
static bounce(t: number);
```

Provides a basic bouncing effect.

<https://easings.net/#easeInBounce>

***

### `bezier()`[​](#bezier "Direct link to bezier")

React TSX

```
static bezier(x1: number, y1: number, x2: number, y2: number);
```

Provides a cubic bezier curve, equivalent to CSS Transitions' `transition-timing-function`.

A useful tool to visualize cubic bezier curves can be found at <https://cubic-bezier.com/>

***

### `in()`[​](#in "Direct link to in")

React TSX

```
static in(easing: number);
```

Runs an easing function forwards.

***

### `out()`[​](#out "Direct link to out")

React TSX

```
static out(easing: number);
```

Runs an easing function backwards.

***

### `inOut()`[​](#inout "Direct link to inout")

React TSX

```
static inOut(easing: number);
```

----
url: https://reactnative.dev/docs/communication-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

In [Integrating with Existing Apps guide](/docs/integration-with-existing-apps) and [Native UI Components guide](/docs/legacy/native-components-ios) we learn how to embed React Native in a native component and vice versa. When we mix native and React Native components, we'll eventually find a need to communicate between these two worlds. Some ways to achieve that have been already mentioned in other guides. This article summarizes available techniques.

```
NSArray *imageList = @[@"https://dummyimage.com/600x400/ffffff/000000.png",

                       @"https://dummyimage.com/600x400/000000/ffffff.png"];



NSDictionary *props = @{@"images" : imageList};



RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge

                                                 moduleName:@"ImageBrowserApp"

                                          initialProperties:props];
```

React TSX

```
import {View, Image} from 'react-native';



export default class ImageBrowserApp extends React.Component {

  renderImage(imgURI) {

    return <Image source={{uri: imgURI}} />;

  }

  render() {

    return <View>{this.props.images.map(this.renderImage)}</View>;

  }

}
```

`RCTRootView` also provides a read-write property `appProperties`. After `appProperties` is set, the React Native app is re-rendered with new properties. The update is only performed when the new updated properties differ from the previous ones.

Objective-C

```
NSArray *imageList = @[@"https://dummyimage.com/600x400/ff0000/000000.png",

                       @"https://dummyimage.com/600x400/ffffff/ff0000.png"];



rootView.appProperties = @{@"images" : imageList};
```

It is fine to update properties anytime. However, updates have to be performed on the main thread. You use the getter on any thread.

note

Currently, there is a known issue where setting appProperties during the bridge startup, the change can be lost. See <https://github.com/react/react-native/issues/20115> for more information.

There is no way to update only a few properties at a time. We suggest that you build it into your own wrapper instead.

### Passing properties from React Native to native[​](#passing-properties-from-react-native-to-native "Direct link to Passing properties from React Native to native")

The problem exposing properties of native components is covered in detail in [this article](/docs/legacy/native-components-ios#properties). In short, export properties with `RCT_CUSTOM_VIEW_PROPERTY` macro in your custom native component, then use them in React Native as if the component was an ordinary React Native component.

### Limits of properties[​](#limits-of-properties "Direct link to Limits of properties")

The main drawback of cross-language properties is that they do not support callbacks, which would allow us to handle bottom-up data bindings. Imagine you have a small RN view that you want to be removed from the native parent view as a result of a JS action. There is no way to do that with props, as the information would need to go bottom-up.

Although we have a flavor of cross-language callbacks ([described here](/docs/legacy/native-modules-ios#callbacks)), these callbacks are not always the thing we need. The main problem is that they are not intended to be passed as properties. Rather, this mechanism allows us to trigger a native action from JS, and handle the result of that action in JS.

## Other ways of cross-language interaction (events and native modules)[​](#other-ways-of-cross-language-interaction-events-and-native-modules "Direct link to Other ways of cross-language interaction (events and native modules)")

As stated in the previous chapter, using properties comes with some limitations. Sometimes properties are not enough to drive the logic of our app and we need a solution that gives more flexibility. This chapter covers other communication techniques available in React Native. They can be used for internal communication (between JS and native layers in RN) as well as for external communication (between RN and the 'pure native' part of your app).

React Native enables you to perform cross-language function calls. You can execute custom native code from JS and vice versa. Unfortunately, depending on the side we are working on, we achieve the same goal in different ways. For native - we use events mechanism to schedule an execution of a handler function in JS, while for React Native we directly call methods exported by native modules.

### Calling React Native functions from native (events)[​](#calling-react-native-functions-from-native-events "Direct link to Calling React Native functions from native (events)")

Events are described in detail in [this article](/docs/legacy/native-components-ios#events). Note that using events gives us no guarantees about execution time, as the event is handled on a separate thread.

Events are powerful, because they allow us to change React Native components without needing a reference to them. However, there are some pitfalls that you can fall into while using them:

* As events can be sent from anywhere, they can introduce spaghetti-style dependencies into your project.
* Events share namespace, which means that you may encounter some name collisions. Collisions will not be detected statically, which makes them hard to debug.
* If you use several instances of the same React Native component and you want to distinguish them from the perspective of your event, you'll likely need to introduce identifiers and pass them along with events (you can use the native view's `reactTag` as an identifier).

The common pattern we use when embedding native in React Native is to make the native component's RCTViewManager a delegate for the views, sending events back to JavaScript via the bridge. This keeps related event calls in one place.

### Calling native functions from React Native (native modules)[​](#calling-native-functions-from-react-native-native-modules "Direct link to Calling native functions from React Native (native modules)")

Native modules are Objective-C classes that are available in JS. Typically one instance of each module is created per JS bridge. They can export arbitrary functions and constants to React Native. They have been covered in detail in [this article](/docs/legacy/native-modules-ios).

This case is covered in [this article](/docs/legacy/native-components-ios#styles). To summarize, since all our native react views are subclasses of `UIView`, most style and size attributes will work like you would expect out of the box.

### Layout of a React Native component embedded in native[​](#layout-of-a-react-native-component-embedded-in-native "Direct link to Layout of a React Native component embedded in native")

#### React Native content with fixed size[​](#react-native-content-with-fixed-size "Direct link to React Native content with fixed size")

The general scenario is when we have a React Native app with a fixed size, which is known to the native side. In particular, a full-screen React Native view falls into this case. If we want a smaller root view, we can explicitly set RCTRootView's frame.

For instance, to make an RN app 200 (logical) pixels high, and the hosting view's width wide, we could do:

SomeViewController.m

```
- (void)viewDidLoad

{

  [...]

  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge

                                                   moduleName:appName

                                            initialProperties:props];

  rootView.frame = CGRectMake(0, 0, self.view.width, 200);

  [self.view addSubview:rootView];

}
```

```
typedef NS_ENUM(NSInteger, RCTRootViewSizeFlexibility) {

  RCTRootViewSizeFlexibilityNone = 0,

  RCTRootViewSizeFlexibilityWidth,

  RCTRootViewSizeFlexibilityHeight,

  RCTRootViewSizeFlexibilityWidthAndHeight,

};
```

`RCTRootViewSizeFlexibilityNone` is the default value, which makes a root view's size fixed (but it still can be updated with `setFrame:`). The other three modes allow us to track React Native content's size updates. For instance, setting mode to `RCTRootViewSizeFlexibilityHeight` will cause React Native to measure the content's height and pass that information back to `RCTRootView`'s delegate. An arbitrary action can be performed within the delegate, including setting the root view's frame, so the content fits. The delegate is called only when the size of the content has changed.

caution

Making a dimension flexible in both JS and native leads to undefined behavior. For example - don't make a top-level React component's width flexible (with `flexbox`) while you're using `RCTRootViewSizeFlexibilityWidth` on the hosting `RCTRootView`.

Let's look at an example.

FlexibleSizeExampleView\.m

```
- (instancetype)initWithFrame:(CGRect)frame

{

  [...]



  _rootView = [[RCTRootView alloc] initWithBridge:bridge

  moduleName:@"FlexibilityExampleApp"

  initialProperties:@{}];



  _rootView.delegate = self;

  _rootView.sizeFlexibility = RCTRootViewSizeFlexibilityHeight;

  _rootView.frame = CGRectMake(0, 0, self.frame.size.width, 0);

}



#pragma mark - RCTRootViewDelegate

- (void)rootViewDidChangeIntrinsicSize:(RCTRootView *)rootView

{

  CGRect newFrame = rootView.frame;

  newFrame.size = rootView.intrinsicContentSize;



  rootView.frame = newFrame;

}
```

----
url: https://reactnative.dev/docs/next/layoutevent
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/layoutevent)** (0.87).

Version: Next

`LayoutEvent` object is returned in the callback as a result of component layout change, for example `onLayout` in [View](/docs/next/view) component.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

    layout: {

        width: 520,

        height: 70.5,

        x: 0,

        y: 42.5

    },

    target: 1127

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `height`[​](#height "Direct link to height")

Height of the component after the layout changes.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `width`[​](#width "Direct link to width")

Width of the component after the layout changes.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `x`[​](#x "Direct link to x")

Component X coordinate inside the parent component.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `y`[​](#y "Direct link to y")

Component Y coordinate inside the parent component.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `target`[​](#target "Direct link to target")

The node id of the element receiving the LayoutEvent.

| Type                        | Optional |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

## Used by[​](#used-by "Direct link to Used by")

* [`Image`](/docs/next/image)
* [`Pressable`](/docs/next/pressable)
* [`ScrollView`](/docs/next/scrollview)
* [`Text`](/docs/next/text)
* [`TextInput`](/docs/next/textinput)
* [`TouchableWithoutFeedback`](/docs/next/touchablewithoutfeedback)
* [`View`](/docs/next/view)

----
url: https://reactnative.dev/docs/next/troubleshooting
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/troubleshooting)** (0.87).

Version: Next

These are some common issues you may run into while setting up React Native. If you encounter something that is not listed here, try [searching for the issue in GitHub](https://github.com/react/react-native/issues/).

### Port already in use[​](#port-already-in-use "Direct link to Port already in use")

The [Metro bundler](https://metrobundler.dev/) runs on port 8081. If another process is already using that port, you can either terminate that process, or change the port that the bundler uses.

#### Terminating a process on port 8081[​](#terminating-a-process-on-port-8081 "Direct link to Terminating a process on port 8081")

Run the following command to find the id for the process that is listening on port 8081:

```
sudo lsof -i :8081
```

Then run the following to terminate the process:

```
kill -9 <PID>
```

On Windows you can find the process using port 8081 using [Resource Monitor](https://stackoverflow.com/questions/48198/how-can-you-find-out-which-process-is-listening-on-a-port-on-windows) and stop it using Task Manager.

#### Using a port other than 8081[​](#using-a-port-other-than-8081 "Direct link to Using a port other than 8081")

You can configure the bundler to use a port other than 8081 by using the `port` parameter, from the root of your project run:

* npm
* Yarn

```
npm start -- --port=8088
```

```
yarn start --port 8088
```

You will also need to update your applications to load the JavaScript bundle from the new port. If running on device from Xcode, you can do this by updating occurrences of `8081` to your chosen port in the `ios/__App_Name__.xcodeproj/project.pbxproj` file.

### NPM locking error[​](#npm-locking-error "Direct link to NPM locking error")

If you encounter an error such as `npm WARN locking Error: EACCES` while using the React Native CLI, try running the following:

```
sudo chown -R $USER ~/.npm

sudo chown -R $USER /usr/local/lib/node_modules
```

### Missing libraries for React[​](#missing-libraries-for-react "Direct link to Missing libraries for React")

If you added React Native manually to your project, make sure you have included all the relevant dependencies that you are using, like `RCTText.xcodeproj`, `RCTImage.xcodeproj`. Next, the binaries built by these dependencies have to be linked to your app binary. Use the `Linked Frameworks and Binaries` section in the Xcode project settings. More detailed steps are here: [Linking Libraries](/docs/next/linking-libraries-ios).

If you are using CocoaPods, verify that you have added React along with the subspecs to the `Podfile`. For example, if you were using the `<Text />`, `<Image />` and `fetch()` APIs, you would need to add these in your `Podfile`:

```
pod 'React', :path => '../node_modules/react-native', :subspecs => [

  'RCTText',

  'RCTImage',

  'RCTNetwork',

  'RCTWebSocket',

]
```

```
import Firebase from 'firebase';
```

## Shell Command Unresponsive Exception[​](#shell-command-unresponsive-exception "Direct link to Shell Command Unresponsive Exception")

If you encounter a ShellCommandUnresponsiveException exception such as:

```
Execution failed for task ':app:installDebug'.

  com.android.builder.testing.api.DeviceException: com.android.ddmlib.ShellCommandUnresponsiveException
```

Restart the ADB server by running the following commands in your terminal:

```
adb kill-server

adb start-server
```

## Unable to start react-native package manager (on Linux)[​](#unable-to-start-react-native-package-manager-on-linux "Direct link to Unable to start react-native package manager (on Linux)")

### Case 1: Error "code":"ENOSPC","errno":"ENOSPC"[​](#case-1-error-codeenospcerrnoenospc "Direct link to Case 1: Error \"code\":\"ENOSPC\",\"errno\":\"ENOSPC\"")

Issue caused by the number of directories [inotify](https://github.com/guard/listen/blob/master/README.md#increasing-the-amount-of-inotify-watchers) (used by watchman on Linux) can monitor. To solve it, run this command in your terminal window

```
echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
```

----
url: https://reactnative.dev/docs/next/typescript
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/typescript)** (0.87).

Version: Next

[TypeScript](https://www.typescriptlang.org/) is a language which extends JavaScript by adding type definitions. New React Native projects target TypeScript by default, but also support JavaScript and Flow.

## Getting Started with TypeScript[​](#getting-started-with-typescript "Direct link to Getting Started with TypeScript")

New projects created by the [React Native CLI](/docs/next/getting-started-without-a-framework#step-1-creating-a-new-application) or popular templates like [Ignite](https://github.com/infinitered/ignite) will use TypeScript by default.

TypeScript may also be used with [Expo](https://expo.io), which maintains TypeScript templates, or will prompt you to automatically install and configure TypeScript when a `.ts` or `.tsx` file is added to your project.

```
npx create-expo-app --template
```

## Adding TypeScript to an Existing Project[​](#adding-typescript-to-an-existing-project "Direct link to Adding TypeScript to an Existing Project")

1. Add TypeScript, types, and ESLint plugins to your project.

* npm
* Yarn

```
npm install -D typescript @react-native/typescript-config @types/jest @types/react @types/react-test-renderer
```

```
yarn add --dev typescript @react-native/typescript-config @types/jest @types/react @types/react-test-renderer
```

note

This command adds the latest version of every dependency. The versions may need to be changed to match the existing packages used by your project. You can use a tool like [React Native Upgrade Helper](https://react-native-community.github.io/upgrade-helper/) to see the versions shipped by React Native.

2. Add a TypeScript config file. Create a `tsconfig.json` in the root of your project:

tsconfig.json

```
{

  "extends": "@react-native/typescript-config"

}
```

3. Rename a JavaScript file to be `*.tsx`

warning

You should leave the `./index.js` entrypoint file as it is otherwise you may run into an issue when it comes to bundling a production build.

4. Run `tsc` to type-check your new TypeScript files.

* npm
* Yarn

```
npx tsc
```

```
yarn tsc
```

## Using JavaScript Instead of TypeScript[​](#using-javascript-instead-of-typescript "Direct link to Using JavaScript Instead of TypeScript")

React Native defaults new applications to TypeScript, but JavaScript may still be used. Files with a `.jsx` extension are treated as JavaScript instead of TypeScript, and will not be typechecked. JavaScript modules may still be imported by TypeScript modules, along with the reverse.

## How TypeScript and React Native works[​](#how-typescript-and-react-native-works "Direct link to How TypeScript and React Native works")

Out of the box, TypeScript sources are transformed by [Babel](/docs/javascript-environment#javascript-syntax-transformers) during bundling. We recommend that you use the TypeScript compiler only for type checking. This is the default behavior of `tsc` for newly created applications. If you have existing TypeScript code being ported to React Native, there are [one or two caveats](https://babeljs.io/docs/en/next/babel-plugin-transform-typescript) to using Babel instead of TypeScript.

## What does React Native + TypeScript look like[​](#what-does-react-native--typescript-look-like "Direct link to What does React Native + TypeScript look like")

You can provide an interface for a React Component's [Props](/docs/next/props) and [State](/docs/next/state) via `React.Component<Props, State>` which will provide type-checking and editor auto-completing when working with that component in JSX.

components/Hello.tsx

```
import {useState} from 'react';

import {Button, StyleSheet, Text, View} from 'react-native';



export type Props = {

  name: string;

  baseEnthusiasmLevel?: number;

};



function Hello({name, baseEnthusiasmLevel = 0}: Props) {

  const [enthusiasmLevel, setEnthusiasmLevel] = useState(

    baseEnthusiasmLevel,

  );



  const onIncrement = () =>

    setEnthusiasmLevel(enthusiasmLevel + 1);

  const onDecrement = () =>

    setEnthusiasmLevel(

      enthusiasmLevel > 0 ? enthusiasmLevel - 1 : 0,

    );



  const getExclamationMarks = (numChars: number) =>

    numChars > 0 ? Array(numChars + 1).join('!') : '';



  return (

    <View style={styles.container}>

      <Text style={styles.greeting}>

        Hello {name}

        {getExclamationMarks(enthusiasmLevel)}

      </Text>

      <View>

        <Button

          title="Increase enthusiasm"

          accessibilityLabel="increment"

          onPress={onIncrement}

          color="blue"

        />

        <Button

          title="Decrease enthusiasm"

          accessibilityLabel="decrement"

          onPress={onDecrement}

          color="red"

        />

      </View>

    </View>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    alignItems: 'center',

    justifyContent: 'center',

  },

  greeting: {

    fontSize: 20,

    fontWeight: 'bold',

    margin: 16,

  },

});



export default Hello;
```

```
{

-  "extends": "@react-native/typescript-config"

+  "extends": "@react-native/typescript-config",

+  "compilerOptions": {

+    "baseUrl": ".",

+    "paths": {

+      "*": ["src/*"],

+      "tests": ["tests/*"],

+      "@components/*": ["src/components/*"],

+    },

+  }

}
```

2. Add [`babel-plugin-module-resolver`](https://github.com/tleunen/babel-plugin-module-resolver) as a development package to your project:

* npm
* Yarn

```
npm install --save-dev babel-plugin-module-resolver
```

```
yarn add --dev babel-plugin-module-resolver
```

3. Finally, configure your `babel.config.js` (note that the syntax for your `babel.config.js` is different from your `tsconfig.json`):

Diff

```
{

   presets: ['module:metro-react-native-babel-preset'],

+  plugins: [

+    [

+       'module-resolver',

+       {

+         root: ['./src'],

+         extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],

+         alias: {

+           tests: ['./tests/'],

+           "@components": "./src/components",

+         }

+       }

+    ]

+  ]

}
```

----
url: https://reactnative.dev/docs/next/upgrading
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/upgrading)** (0.87).

Version: Next

```
# {{VERSION}} and {{REACT_VERSION}} are the release versions showing in the diff

npm install react-native@{{VERSION}}

npm install react@{{REACT_VERSION}}
```

```
# {{VERSION}} and {{REACT_VERSION}} are the release versions showing in the diff

yarn add react-native@{{VERSION}}

yarn add react@{{REACT_VERSION}}
```

----
url: https://reactnative.dev/docs/virtualizedlist
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Base implementation for the more convenient [`<FlatList>`](/docs/flatlist) and [`<SectionList>`](/docs/sectionlist) components, which are also better documented. In general, this should only really be used if you need more flexibility than [`FlatList`](/docs/flatlist) provides, e.g. for use with immutable data instead of plain arrays.

Virtualization massively improves memory consumption and performance of large lists by maintaining a finite render window of active items and replacing all items outside of the render window with appropriately sized blank space. The window adapts to scrolling behavior, and items are rendered incrementally with low-pri (after any running interactions) if they are far from the visible area, or with hi-pri otherwise to minimize the potential of seeing blank space.

## Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

***

Some caveats:

* Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
* This is a `PureComponent` which means that it will not re-render if `props` are shallow-equal. Make sure that everything your `renderItem` function depends on is passed as a prop (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on changes. This includes the `data` prop and parent component state.
* In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
* By default, the list looks for a `key` prop on each item and uses that for the React key. Alternatively, you can provide a custom `keyExtractor` prop.

***

# Reference

## Props[​](#props "Direct link to Props")

### [ScrollView Props](/docs/scrollview#props)[​](#scrollview-props "Direct link to scrollview-props")

Inherits [ScrollView Props](/docs/scrollview#props).

***

### `data`[​](#data "Direct link to data")

Opaque data type passed to `getItem` and `getItemCount` to retrieve items.

| Type |
| ---- |
| any  |

***

### Require&#x64;**`getItem`**[​](#required-getitem "Direct link to required-getitem")

React TSX

```
(data: any, index: number) => any;
```

A generic accessor for extracting an item from any sort of data blob.

| Type     |
| -------- |
| function |

***

### Require&#x64;**`getItemCount`**[​](#required-getitemcount "Direct link to required-getitemcount")

React TSX

```
(data: any) => number;
```

Determines how many items are in the data blob.

| Type     |
| -------- |
| function |

***

### Require&#x64;**`renderItem`**[​](#required-renderitem "Direct link to required-renderitem")

React TSX

```
(info: any) => ?React.Element<any>
```

Takes an item from `data` and renders it into the list

| Type     |
| -------- |
| function |

***

### `CellRendererComponent`[​](#cellrenderercomponent "Direct link to cellrenderercomponent")

CellRendererComponent allows customizing how cells rendered by `renderItem`/`ListItemComponent` are wrapped when placed into the underlying ScrollView. This component must accept event handlers which notify VirtualizedList of changes within the cell.

| Type                                     |
| ---------------------------------------- |
| `React.ComponentType<CellRendererProps>` |

***

### `ItemSeparatorComponent`[​](#itemseparatorcomponent "Direct link to itemseparatorcomponent")

Rendered in between each item, but not at the top or bottom. By default, `highlighted` and `leadingItem` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` which will update the `highlighted` prop, but you can also add custom props with `separators.updateProps`. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type                         |
| ---------------------------- |
| component, function, element |

***

### `ListEmptyComponent`[​](#listemptycomponent "Direct link to listemptycomponent")

Rendered when the list is empty. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListItemComponent`[​](#listitemcomponent "Direct link to listitemcomponent")

Each data item is rendered using this element. Can be a React Component Class, or a render function.

| Type                |
| ------------------- |
| component, function |

***

### `ListFooterComponent`[​](#listfootercomponent "Direct link to listfootercomponent")

Rendered at the bottom of all the items. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListFooterComponentStyle`[​](#listfootercomponentstyle "Direct link to listfootercomponentstyle")

Styling for internal View for `ListFooterComponent`.

| Type          | Required |
| ------------- | -------- |
| ViewStyleProp | No       |

***

### `ListHeaderComponent`[​](#listheadercomponent "Direct link to listheadercomponent")

Rendered at the top of all the items. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListHeaderComponentStyle`[​](#listheadercomponentstyle "Direct link to listheadercomponentstyle")

Styling for internal View for `ListHeaderComponent`.

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

***

### `debug`[​](#debug "Direct link to debug")

`debug` will turn on extra logging and visual overlays to aid with debugging both usage and implementation, but with a significant perf hit.

| Type    |
| ------- |
| boolean |

***

### 🗑️ `disableVirtualization`[​](#️-disablevirtualization "Direct link to ️-disablevirtualization")

Deprecated

Virtualization provides significant performance and memory optimizations, but fully unmounts react instances that are outside of the render window. You should only need to disable this for debugging purposes.

| Type    |
| ------- |
| boolean |

***

### `extraData`[​](#extradata "Direct link to extradata")

A marker property for telling the list to re-render (since it implements `PureComponent`). If any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the `data` prop, stick it here and treat it immutably.

| Type |
| ---- |
| any  |

***

### `getItemLayout`[​](#getitemlayout "Direct link to getitemlayout")

React TSX

```
(

  data: any,

  index: number,

) => {length: number, offset: number, index: number}
```

| Type     |
| -------- |
| function |

***

### `horizontal`[​](#horizontal "Direct link to horizontal")

If `true`, renders items next to each other horizontally instead of stacked vertically.

| Type    |
| ------- |
| boolean |

***

### `initialNumToRender`[​](#initialnumtorender "Direct link to initialnumtorender")

How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.

| Type   | Default |
| ------ | ------- |
| number | `10`    |

***

### `initialScrollIndex`[​](#initialscrollindex "Direct link to initialscrollindex")

Instead of starting at the top with the first item, start at `initialScrollIndex`. This disables the "scroll to top" optimization that keeps the first `initialNumToRender` items always rendered and immediately renders the items starting at this initial index. Requires `getItemLayout` to be implemented.

| Type   |
| ------ |
| number |

***

### `inverted`[​](#inverted "Direct link to inverted")

Reverses the direction of scroll. Uses scale transforms of `-1`.

| Type    |
| ------- |
| boolean |

***

### `keyExtractor`[​](#keyextractor "Direct link to keyextractor")

React TSX

```
(item: any, index: number) => string;
```

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks `item.key`, then `item.id`, and then falls back to using the index, like React does.

| Type     |
| -------- |
| function |

***

### `maxToRenderPerBatch`[​](#maxtorenderperbatch "Direct link to maxtorenderperbatch")

The maximum number of items to render in each incremental render batch. The more rendered at once, the better the fill rate, but responsiveness may suffer because rendering content may interfere with responding to button taps or other interactions.

| Type   |
| ------ |
| number |

***

### `onEndReached`[​](#onendreached "Direct link to onendreached")

Called once when the scroll position gets within `onEndReachedThreshold` from the logical end of the list.

| Type                                        |
| ------------------------------------------- |
| `(info: {distanceFromEnd: number}) => void` |

***

### `onEndReachedThreshold`[​](#onendreachedthreshold "Direct link to onendreachedthreshold")

How far from the end (in units of visible length of the list) the trailing edge of the list must be from the end of the content to trigger the `onEndReached` callback. Thus, a value of 0.5 will trigger `onEndReached` when the end of the content is within half the visible length of the list.

| Type   | Default |
| ------ | ------- |
| number | `2`     |

***

### `onRefresh`[​](#onrefresh "Direct link to onrefresh")

React TSX

```
() => void;
```

If provided, a standard `RefreshControl` will be added for "Pull to Refresh" functionality. Make sure to also set the `refreshing` prop correctly.

| Type     |
| -------- |
| function |

***

### `onScrollToIndexFailed`[​](#onscrolltoindexfailed "Direct link to onscrolltoindexfailed")

React TSX

```
(info: {

  index: number,

  highestMeasuredFrameIndex: number,

  averageItemLength: number,

}) => void;
```

Used to handle failures when scrolling to an index that has not been measured yet. Recommended action is to either compute your own offset and `scrollTo` it, or scroll as far as possible and then try again after more items have been rendered.

| Type     |
| -------- |
| function |

***

### `onStartReached`[​](#onstartreached "Direct link to onstartreached")

Called once when the scroll position gets within `onStartReachedThreshold` from the logical start of the list.

| Type                                          |
| --------------------------------------------- |
| `(info: {distanceFromStart: number}) => void` |

***

### `onStartReachedThreshold`[​](#onstartreachedthreshold "Direct link to onstartreachedthreshold")

How far from the start (in units of visible length of the list) the leading edge of the list must be from the start of the content to trigger the `onStartReached` callback. Thus, a value of 0.5 will trigger `onStartReached` when the start of the content is within half the visible length of the list.

| Type   | Default |
| ------ | ------- |
| number | `2`     |

***

### `onViewableItemsChanged`[​](#onviewableitemschanged "Direct link to onviewableitemschanged")

Called when the viewability of rows changes, as defined by the `viewabilityConfig` prop.

| Type                                                                     |
| ------------------------------------------------------------------------ |
| `(callback: {changed: ViewToken[], viewableItems: ViewToken[]}) => void` |

***

### `persistentScrollbar`[​](#persistentscrollbar "Direct link to persistentscrollbar")

| Type |
| ---- |
| bool |

***

### `progressViewOffset`[​](#progressviewoffset "Direct link to progressviewoffset")

Set this when offset is needed for the loading indicator to show correctly.

| Type   |
| ------ |
| number |

***

### `refreshControl`[​](#refreshcontrol "Direct link to refreshcontrol")

A custom refresh control element. When set, it overrides the default `<RefreshControl>` component built internally. The onRefresh and refreshing props are also ignored. Only works for vertical VirtualizedList.

| Type    |
| ------- |
| element |

***

### `refreshing`[​](#refreshing "Direct link to refreshing")

Set this true while waiting for new data from a refresh.

| Type    |
| ------- |
| boolean |

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

warning

Using this property may lead to bugs (missing content) in some circumstances - use at your own risk.

When `true`, offscreen child views are removed from their native backing superview when offscreen. This may improve scroll performance for large lists. On Android the default value is `true`.

| Type    |
| ------- |
| boolean |

***

### `renderScrollComponent`[​](#renderscrollcomponent "Direct link to renderscrollcomponent")

React TSX

```
(props: object) => element;
```

Render a custom scroll component, e.g. with a differently styled `RefreshControl`.

| Type     |
| -------- |
| function |

***

### `viewabilityConfig`[​](#viewabilityconfig "Direct link to viewabilityconfig")

See `ViewabilityHelper.js` for flow type and further documentation.

| Type              |
| ----------------- |
| ViewabilityConfig |

***

### `viewabilityConfigCallbackPairs`[​](#viewabilityconfigcallbackpairs "Direct link to viewabilityconfigcallbackpairs")

List of `ViewabilityConfig`/`onViewableItemsChanged` pairs. A specific `onViewableItemsChanged` will be called when its corresponding `ViewabilityConfig`'s conditions are met. See `ViewabilityHelper.js` for flow type and further documentation.

| Type                                   |
| -------------------------------------- |
| array of ViewabilityConfigCallbackPair |

***

### `updateCellsBatchingPeriod`[​](#updatecellsbatchingperiod "Direct link to updatecellsbatchingperiod")

Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off screen. Similar fill rate/responsiveness tradeoff as `maxToRenderPerBatch`.

| Type   |
| ------ |
| number |

***

### `windowSize`[​](#windowsize "Direct link to windowsize")

Determines the maximum number of items rendered outside of the visible area, in units of visible lengths. So if your list fills the screen, then `windowSize={21}` (the default) will render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing this number will reduce memory consumption and may improve performance, but will increase the chance that fast scrolling may reveal momentary blank areas of unrendered content.

| Type   |
| ------ |
| number |

## Methods[​](#methods "Direct link to Methods")

### `flashScrollIndicators()`[​](#flashscrollindicators "Direct link to flashscrollindicators")

React TSX

```
flashScrollIndicators();
```

***

### `getScrollableNode()`[​](#getscrollablenode "Direct link to getscrollablenode")

React TSX

```
getScrollableNode(): any;
```

***

### `getScrollRef()`[​](#getscrollref "Direct link to getscrollref")

React TSX

```
getScrollRef():

  | React.ElementRef<typeof ScrollView>

  | React.ElementRef<typeof View>

  | null;
```

***

### `getScrollResponder()`[​](#getscrollresponder "Direct link to getscrollresponder")

React TSX

```
getScrollResponder () => ScrollResponderMixin | null;
```

Provides a handle to the underlying scroll responder. Note that `this._scrollRef` might not be a `ScrollView`, so we need to check that it responds to `getScrollResponder` before calling it.

***

### `scrollToEnd()`[​](#scrolltoend "Direct link to scrolltoend")

React TSX

```
scrollToEnd(params?: {animated?: boolean});
```

Scrolls to the end of the content. May be janky without `getItemLayout` prop.

**Parameters:**

| Name   | Type   |
| ------ | ------ |
| params | object |

Valid `params` keys are:

* `'animated'` (boolean) - Whether the list should do an animation while scrolling. Defaults to `true`.

***

### `scrollToIndex()`[​](#scrolltoindex "Direct link to scrolltoindex")

React TSX

```
scrollToIndex(params: {

  index: number;

  animated?: boolean;

  viewOffset?: number;

  viewPosition?: number;

});
```

Valid `params` consist of:

* 'index' (number). Required.
* 'animated' (boolean). Optional.
* 'viewOffset' (number). Optional.
* 'viewPosition' (number). Optional.

***

### `scrollToItem()`[​](#scrolltoitem "Direct link to scrolltoitem")

React TSX

```
scrollToItem(params: {

  item: ItemT;

  animated?: boolean;

  viewOffset?: number;

  viewPosition?: number;

);
```

Valid `params` consist of:

* 'item' (Item). Required.
* 'animated' (boolean). Optional.
* 'viewOffset' (number). Optional.
* 'viewPosition' (number). Optional.

***

### `scrollToOffset()`[​](#scrolltooffset "Direct link to scrolltooffset")

React TSX

```
scrollToOffset(params: {

  offset: number;

  animated?: boolean;

});
```

    [**`getItem`**](#required-getitem)
  * [Required](#required-getitemcount)

    [**`getItemCount`**](#required-getitemcount)
  * [Required](#required-renderitem)

    [**`renderItem`**](#required-renderitem)

----
url: https://reactnative.dev/docs/legacy/native-modules-intro
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

Sometimes a React Native app needs to access a native platform API that is not available by default in JavaScript, for example the native APIs to access Apple or Google Pay. Maybe you want to reuse some existing Objective-C, Swift, Java or C++ libraries without having to reimplement it in JavaScript, or write some high performance, multi-threaded code for things like image processing.

The NativeModule system exposes instances of Java/Objective-C/C++ (native) classes to JavaScript (JS) as JS objects, thereby allowing you to execute arbitrary native code from within JS. While we don't expect this feature to be part of the usual development process, it is essential that it exists. If React Native doesn't export a native API that your JS app needs you should be able to export it yourself!

## Native Module Setup[​](#native-module-setup "Direct link to Native Module Setup")

There are different ways to write a native module for your React Native application:

1. Creating a local library that can be imported in your React Native application. Read [Creating local libraries](/docs/legacy/local-library-setup) guide to learn more.
2. Directly within your React Native application's iOS/Android projects
3. As an NPM package that can be installed as a dependency by your/other React Native applications.

This guide will first walk you through implementing a native module directly within a React Native application. However the native module you build in the following guide can be distributed as an NPM package. Check out the [Setting Up a Native Module as an NPM Package](/docs/legacy/native-modules-setup) guide if you are interested in doing so.

## Getting Started[​](#getting-started "Direct link to Getting Started")

In the following sections we will walk you through guides on how to build a native module directly within a React Native application. As a prerequisite, you will need a React Native application to work within. You can follow the steps [here](/docs/getting-started) to setup a React Native application if you do not already have one.

Imagine that you want to access the iOS/Android native calendar APIs from JavaScript within a React Native application in order to create calendar events. React Native does not expose a JavaScript API to communicate with the native calendar libraries. However, through native modules, you can write native code that communicates with native calendar APIs. Then you can invoke that native code through JavaScript in your React Native application.

In the following sections you will create such a Calendar native module for both [Android](/docs/legacy/native-modules-android) and [iOS](/docs/legacy/native-modules-ios).

* [Native Module Setup](#native-module-setup)
* [Getting Started](#getting-started)

----
url: https://reactnative.dev/docs/next/document-nodes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/document-nodes)** (0.87).

Version: Next

Document nodes represent a complete native view tree. Apps using native navigation would provide a separate document node for each screen. Apps not using native navigation would generally provide a single document for the whole app (similar to single-page apps on Web).

***

----
url: https://reactnative.dev/docs/next/improvingux
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/improvingux)** (0.87).

Version: Next

Check out [`TextInput` docs](/docs/next/textinput) for more configuration options.

* TypeScript
* JavaScript

## Manage layout when keyboard is visible[​](#manage-layout-when-keyboard-is-visible "Direct link to Manage layout when keyboard is visible")

Software keyboard takes almost half of the screen. If you have interactive elements that can get covered by the keyboard, make sure they are still accessible by using the [`KeyboardAvoidingView` component](/docs/next/keyboardavoidingview).

* TypeScript
* JavaScript

## Make tappable areas larger[​](#make-tappable-areas-larger "Direct link to Make tappable areas larger")

On mobile phones it's hard to be very precise when pressing buttons. Make sure all interactive elements are 44x44 or larger. One way to do this is to leave enough space for the element, `padding`, `minWidth` and `minHeight` style values can be useful for that. Alternatively, you can use [`hitSlop` prop](/docs/next/touchablewithoutfeedback#hitslop) to increase interactive area without affecting the layout. Here's a demo:

## Use Android Ripple[​](#use-android-ripple "Direct link to Use Android Ripple")

Android API 21+ uses the material design ripple to provide user with feedback when they touch an interactable area on the screen. React Native exposes this through the [`TouchableNativeFeedback` component](/docs/next/touchablenativefeedback). Using this touchable effect instead of opacity or highlight will often make your app feel much more fitting on the platform. That said, you need to be careful when using it because it doesn't work on iOS or on Android API < 21, so you will need to fallback to using one of the other Touchable components on iOS. You can use a library like [react-native-platform-touchable](https://github.com/react-community/react-native-platform-touchable) to handle the platform differences for you.

----
url: https://reactnative.dev/docs/next/handling-touches
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/handling-touches)** (0.87).

Version: Next

Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map. React Native provides components to handle all sorts of common gestures, as well as a comprehensive [gesture responder system](/docs/next/gesture-responder-system) to allow for more advanced gesture recognition, but the one component you will most likely be interested in is the basic Button.

## Displaying a basic button[​](#displaying-a-basic-button "Direct link to Displaying a basic button")

[Button](/docs/next/button) provides a basic button component that is rendered nicely on all platforms. The minimal example to display a button looks like this:

React TSX

```
<Button

  onPress={() => {

    console.log('You tapped the button!');

  }}

  title="Press Me"

/>
```

This will render a blue label on iOS, and a blue rounded rectangle with light text on Android. Pressing the button will call the "onPress" function, which in this case displays an alert popup. If you like, you can specify a "color" prop to change the color of your button.

Go ahead and play around with the `Button` component using the example below. You can select which platform your app is previewed in by clicking on the toggle in the bottom right and then clicking on "Tap to Play" to preview the app.

## Touchables[​](#touchables "Direct link to Touchables")

If the basic button doesn't look right for your app, you can build your own button using any of the "Touchable" components provided by React Native. These components provide the capability to capture tapping gestures and can display feedback when a gesture is recognized. However, these components do not provide any default styling, so you will need to do a bit of work to get them looking nice in your app.

Which "Touchable" component you use will depend on what kind of feedback you want to provide:

* Generally, you can use [**TouchableHighlight**](/docs/next/touchablehighlight) anywhere you would use a button or link on web. The view's background will be darkened when the user presses down on the button.

* You may consider using [**TouchableNativeFeedback**](/docs/next/touchablenativefeedback) on Android to display ink surface reaction ripples that respond to the user's touch.

* [**TouchableOpacity**](/docs/next/touchableopacity) can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down.

* If you need to handle a tap gesture but you don't want any feedback to be displayed, use [**TouchableWithoutFeedback**](/docs/next/touchablewithoutfeedback).

In some cases, you may want to detect when a user presses and holds a view for a set amount of time. These long presses can be handled by passing a function to the `onLongPress` props of any of the "Touchable" components.

Let's see all of these in action:

## Scrolling and swiping[​](#scrolling-and-swiping "Direct link to Scrolling and swiping")

Gestures commonly used on devices with touchable screens include swipes and pans. These allow the user to scroll through a list of items, or swipe through pages of content. For these, check out the [ScrollView](/docs/next/scrollview) Core Component.

## Known issues[​](#known-issues "Direct link to Known issues")

* [react-native#29308](https://github.com/react/react-native/issues/29308#issuecomment-792864162): The touch area never extends past the parent view bounds and on Android negative margin is not supported.

- [Displaying a basic button](#displaying-a-basic-button)
- [Touchables](#touchables)
- [Scrolling and swiping](#scrolling-and-swiping)
- [Known issues](#known-issues)

----
url: https://reactnative.dev/docs/button
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

A basic button component that should render nicely on any platform. Supports a minimal level of customization.

If this button doesn't look right for your app, you can build your own button using [Pressable](/docs/pressable). For inspiration, look at the [source code for the Button component](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Components/Button.js).

React TSX

```
<Button

  onPress={onPressLearnMore}

  title="Learn More"

  color="#841584"

  accessibilityLabel="Learn more about this purple button"

/>
```

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### Require&#x64;**`onPress`**[​](#requiredonpress "Direct link to requiredonpress")

Handler to be called when the user taps the button.

| Type                          |
| ----------------------------- |
| `({nativeEvent: PressEvent})` |

***

### Require&#x64;**`title`**[​](#requiredtitle "Direct link to requiredtitle")

Text to display inside the button. On Android the given title will be converted to the uppercased form.

| Type   |
| ------ |
| string |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

Text to display for blindness accessibility features.

| Type   |
| ------ |
| string |

***

### `accessibilityLanguage`iOS[​](#accessibilitylanguage-ios "Direct link to accessibilitylanguage-ios")

A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the [BCP 47 specification](https://www.rfc-editor.org/info/bcp47).

See the [iOS `accessibilityLanguage` doc](https://developer.apple.com/documentation/objectivec/nsobject/1615192-accessibilitylanguage) for more information.

| Type   |
| ------ |
| string |

***

### `accessibilityActions`[​](#accessibilityactions "Direct link to accessibilityactions")

Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The `accessibilityActions` property should contain a list of action objects. Each action object should contain the field name and label.

See the [Accessibility guide](/docs/accessibility#accessibility-actions) for more information.

| Type  | Required |
| ----- | -------- |
| array | No       |

***

### `onAccessibilityAction`[​](#onaccessibilityaction "Direct link to onaccessibilityaction")

Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

See the [Accessibility guide](/docs/accessibility#accessibility-actions) for more information.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `color`[​](#color "Direct link to color")

Color of the text (iOS), or background color of the button (Android).

| Type                  | Default                             |
| --------------------- | ----------------------------------- |
| [color](/docs/colors) | `'#2196F3'`Android***`'#007AFF'`iOS |

***

### `disabled`[​](#disabled "Direct link to disabled")

If `true`, disable all interactions for this component.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `hasTVPreferredFocus`TV[​](#hastvpreferredfocus-tv "Direct link to hastvpreferredfocus-tv")

TV preferred focus.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `nextFocusDown`AndroidTV[​](#nextfocusdown-androidtv "Direct link to nextfocusdown-androidtv")

Designates the next view to receive focus when the user navigates down. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusDown).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`AndroidTV[​](#nextfocusforward-androidtv "Direct link to nextfocusforward-androidtv")

Designates the next view to receive focus when the user navigates forward. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusForward).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`AndroidTV[​](#nextfocusleft-androidtv "Direct link to nextfocusleft-androidtv")

Designates the next view to receive focus when the user navigates left. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusLeft).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`AndroidTV[​](#nextfocusright-androidtv "Direct link to nextfocusright-androidtv")

Designates the next view to receive focus when the user navigates right. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusRight).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`AndroidTV[​](#nextfocusup-androidtv "Direct link to nextfocusup-androidtv")

Designates the next view to receive focus when the user navigates up. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusUp).

| Type   |
| ------ |
| number |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

| Type   |
| ------ |
| string |

***

### `touchSoundDisabled`Android[​](#touchsounddisabled-android "Direct link to touchsounddisabled-android")

If `true`, doesn't play system sound on touch.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

* [Example](#example)

* [Props](#props)

  * [Required](#requiredonpress)

    [**`onPress`**](#requiredonpress)
  * [Required](#requiredtitle)

    [**`title`**](#requiredtitle)
  * [`accessibilityLabel`](#accessibilitylabel)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)
  * [`accessibilityActions`](#accessibilityactions)
  * [`onAccessibilityAction`](#onaccessibilityaction)
  * [`color`](#color)
  * [`disabled`](#disabled)
  * [`hasTVPreferredFocus`](#hastvpreferredfocus-tv)

    [TV](#hastvpreferredfocus-tv)
  * [`nextFocusDown`](#nextfocusdown-androidtv)

    [Android](#nextfocusdown-androidtv)

    [TV](#nextfocusdown-androidtv)
  * [`nextFocusForward`](#nextfocusforward-androidtv)

    [Android](#nextfocusforward-androidtv)

    [TV](#nextfocusforward-androidtv)
  * [`nextFocusLeft`](#nextfocusleft-androidtv)

    [Android](#nextfocusleft-androidtv)

    [TV](#nextfocusleft-androidtv)
  * [`nextFocusRight`](#nextfocusright-androidtv)

    [Android](#nextfocusright-androidtv)

    [TV](#nextfocusright-androidtv)
  * [`nextFocusUp`](#nextfocusup-androidtv)

    [Android](#nextfocusup-androidtv)

    [TV](#nextfocusup-androidtv)
  * [`testID`](#testid)
  * [`touchSoundDisabled`](#touchsounddisabled-android)

    [Android](#touchsounddisabled-android)

----
url: https://reactnative.dev/docs/the-new-architecture/custom-cxx-types
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

note

This guide assumes that you are familiar with the [**Pure C++ Turbo Native Modules**](/docs/the-new-architecture/pure-cxx-modules) guide. This will build on top of that guide.

```
#pragma once



#include <react/bridging/Bridging.h>



namespace facebook::react {



template <>

struct Bridging<int64_t> {

  // Converts from the JS representation to the C++ representation

  static int64_t fromJs(jsi::Runtime &rt, const jsi::String &value) {

    try {

      size_t pos;

      auto str = value.utf8(rt);

      auto num = std::stoll(str, &pos);

      if (pos != str.size()) {

        throw std::invalid_argument("Invalid number"); // don't support alphanumeric strings

      }

      return num;

    } catch (const std::logic_error &e) {

      throw jsi::JSError(rt, e.what());

    }

  }



  // Converts from the C++ representation to the JS representation

  static jsi::String toJs(jsi::Runtime &rt, int64_t value) {

    return bridging::toJs(rt, std::to_string(value));

  }

};



}
```

```
import {TurboModule, TurboModuleRegistry} from 'react-native';



export interface Spec extends TurboModule {

  readonly reverseString: (input: string) => string;

+  readonly cubicRoot: (input: string) => number;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeSampleModule',

);
```

NativeSampleModule.js

```
// @flow

import type {TurboModule} from 'react-native';

import { TurboModuleRegistry } from "react-native";



export interface Spec extends TurboModule {

  +reverseString: (input: string) => string;

+  +cubicRoot: (input: string) => number;

}



export default (TurboModuleRegistry.getEnforcing<Spec>(

  "NativeSampleModule"

): Spec);
```

In this files, we are defining the function that needs to be implemented in C++.

### 3. Implement the Native Code[​](#3-implement-the-native-code "Direct link to 3. Implement the Native Code")

Now, we need to implement the function that we declared in the JS specification.

1. Open the `specs/NativeSampleModule.h` file and apply the following changes:

NativeSampleModule.h

```
#pragma once



#include <AppSpecsJSI.h>

#include <memory>

#include <string>



+ #include "Int64.h"



namespace facebook::react {



class NativeSampleModule : public NativeSampleModuleCxxSpec<NativeSampleModule> {

public:

  NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker);



  std::string reverseString(jsi::Runtime& rt, std::string input);

+ int32_t cubicRoot(jsi::Runtime& rt, int64_t input);

};



} // namespace facebook::react
```

2. Open the `specs/NativeSampleModule.cpp` file and apply the implement the new function:

NativeSampleModule.cpp

```
#include "NativeSampleModule.h"

+ #include <cmath>



namespace facebook::react {



NativeSampleModule::NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker)

    : NativeSampleModuleCxxSpec(std::move(jsInvoker)) {}



std::string NativeSampleModule::reverseString(jsi::Runtime& rt, std::string input) {

  return std::string(input.rbegin(), input.rend());

}



+int32_t NativeSampleModule::cubicRoot(jsi::Runtime& rt, int64_t input) {

+    return std::cbrt(input);

+}



} // namespace facebook::react
```

The implementation imports the `<cmath>` C++ library to perform mathematical operations, then it implements the `cubicRoot` function using the `cbrt` primitive from the `<cmath>` module.

### 4. Test your code in Your App[​](#4-test-your-code-in-your-app "Direct link to 4. Test your code in Your App")

Now, we can test the code in our app.

First, we need to update the `App.tsx` file to use the new method from the TurboModule. Then, we can build our apps in Android and iOS.

1. Open the `App.tsx` code apply the following changes:

App.tsx

```
// ...

+ const [cubicSource, setCubicSource] = useState('')

+ const [cubicRoot, setCubicRoot] = useState(0)

  return (

    <SafeAreaView style={styles.container}>

      <View>

        <Text style={styles.title}>

          Welcome to C++ Turbo Native Module Example

        </Text>

        <Text>Write down here the text you want to revert</Text>

        <TextInput

          style={styles.textInput}

          placeholder="Write your text here"

          onChangeText={setValue}

          value={value}

        />

        <Button title="Reverse" onPress={onPress} />

        <Text>Reversed text: {reversedValue}</Text>

+        <Text>For which number do you want to compute the Cubic Root?</Text>

+        <TextInput

+          style={styles.textInput}

+          placeholder="Write your text here"

+          onChangeText={setCubicSource}

+          value={cubicSource}

+        />

+        <Button title="Get Cubic Root" onPress={() => setCubicRoot(SampleTurboModule.cubicRoot(cubicSource))} />

+        <Text>The cubic root is: {cubicRoot}</Text>

      </View>

    </SafeAreaView>

  );

}

//...
```

2. To test the app on Android, run `yarn android` from the root folder of your project.
3. To test the app on iOS, run `yarn ios` from the root folder of your project.

## Adding a New Structured Custom Type: Address[​](#adding-a-new-structured-custom-type-address "Direct link to Adding a New Structured Custom Type: Address")

The approach above can be generalized to any kind of type. For structured types, React Native provides some helper functions that make it easier to bridge them from JS to C++ and vice versa.

Let's assume that we want to bridge a custom `Address` type with the following properties:

TypeScript

```
interface Address {

  street: string;

  num: number;

  isInUS: boolean;

}
```

### 1. Define the type in the specs[​](#1-define-the-type-in-the-specs "Direct link to 1. Define the type in the specs")

For the first step, let's define the new custom type in the JS specs, so that Codegen can output all the supporting code. In this way, we don't have to manually write the code.

1. Open the `specs/NativeSampleModule` file and add the following changes.

* TypeScript
* Flow

NativeSampleModule (Add Address type and validateAddress function)

```
import {TurboModule, TurboModuleRegistry} from 'react-native';



+export type Address = {

+  street: string,

+  num: number,

+  isInUS: boolean,

+};



export interface Spec extends TurboModule {

  readonly reverseString: (input: string) => string;

+ readonly validateAddress: (input: Address) => boolean;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeSampleModule',

);
```

NativeSampleModule (Add Address type and validateAddress function)

```


// @flow

import type {TurboModule} from 'react-native';

import { TurboModuleRegistry } from "react-native";



+export type Address = {

+  street: string,

+  num: number,

+  isInUS: boolean,

+};





export interface Spec extends TurboModule {

  +reverseString: (input: string) => string;

+ +validateAddress: (input: Address) => boolean;

}



export default (TurboModuleRegistry.getEnforcing<Spec>(

  "NativeSampleModule"

): Spec);
```

```
#include "Int64.h"

#include <memory>

#include <string>



namespace facebook::react {

+  using Address = NativeSampleModuleAddress<std::string, int32_t, bool>;



+  template <>

+  struct Bridging<Address>

+      : NativeSampleModuleAddressBridging<Address> {};

  // ...

}
```

```
  std::string reverseString(jsi::Runtime& rt, std::string input);



+  bool validateAddress(jsi::Runtime &rt, jsi::Object input);

};



} // namespace facebook::react
```

2. Open the `shared/NativeSampleModule.cpp` file and add the function implementation

NativeSampleModule.cpp (validateAddress implementation)

```
bool NativeSampleModule::validateAddress(jsi::Runtime &rt, jsi::Object input) {

  std::string street = input.getProperty(rt, "street").asString(rt).utf8(rt);

  int32_t number = input.getProperty(rt, "num").asNumber();



  return !street.empty() && number > 0;

}
```

```
const [street, setStreet] = useState('');

const [num, setNum] = useState('');

const [isValidAddress, setIsValidAddress] = useState<

  boolean | null

>(null);



const onPress = () => {

  let houseNum = parseInt(num, 10);

  if (isNaN(houseNum)) {

    houseNum = -1;

  }

  const address = {

    street,

    num: houseNum,

    isInUS: false,

  };

  const result = SampleTurboModule.validateAddress(address);

  setIsValidAddress(result);

};



return (

  <SafeAreaView style={styles.container}>

    <View>

      <Text style={styles.title}>

        Welcome to C Turbo Native Module Example

      </Text>

      <Text>Address:</Text>

      <TextInput

        style={styles.textInput}

        placeholder="Write your address here"

        onChangeText={setStreet}

        value={street}

      />

      <Text>Number:</Text>

      <TextInput

        style={styles.textInput}

        placeholder="Write your address here"

        onChangeText={setNum}

        value={num}

      />

      <Button title="Validate" onPress={onPress} />

      {isValidAddress != null && (

        <Text>

          Your address is {isValidAddress ? 'valid' : 'not valid'}

        </Text>

      )}

    </View>

  </SafeAreaView>

);
```

----
url: https://reactnative.dev/docs/next/legacy/native-components-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/legacy/native-components-ios)** (0.87).

Version: Next

```
#import <MapKit/MapKit.h>



#import <React/RCTViewManager.h>



@interface RNTMapManager : RCTViewManager

@end



@implementation RNTMapManager



RCT_EXPORT_MODULE(RNTMap)



- (UIView *)view

{

  return [[MKMapView alloc] init];

}



@end
```

note

Do not attempt to set the `frame` or `backgroundColor` properties on the `UIView` instance that you expose through the `-view` method. React Native will overwrite the values set by your custom class in order to match your JavaScript component's layout props. If you need this granularity of control it might be better to wrap the `UIView` instance you want to style in another `UIView` and return the wrapper `UIView` instead. See [Issue 2948](https://github.com/react/react-native/issues/2948) for more context.

info

In the example above, we prefixed our class name with `RNT`. Prefixes are used to avoid name collisions with other frameworks. Apple frameworks use two-letter prefixes, and React Native uses `RCT` as a prefix. In order to avoid name collisions, we recommend using a three-letter prefix other than `RCT` in your own classes.

Then you need a little bit of JavaScript to make this a usable React component:

MapView\.tsx

```
import {requireNativeComponent} from 'react-native';



export default requireNativeComponent('RNTMap');
```

The `requireNativeComponent` function automatically resolves `RNTMap` to `RNTMapManager` and exports our native view for use in JavaScript.

MyApp.tsx

```
import MapView from './MapView.tsx';



export default function MyApp() {

  return <MapView style={{flex: 1}} />;

}
```

note

When rendering, don't forget to stretch the view, otherwise you'll be staring at a blank screen.

This is now a fully-functioning native map view component in JavaScript, complete with pinch-zoom and other native gesture support. We can't really control it from JavaScript yet, though.

## Properties[​](#properties "Direct link to Properties")

The first thing we can do to make this component more usable is to bridge over some native properties. Let's say we want to be able to disable zooming and specify the visible region. Disabling zoom is a boolean, so we add this one line:

RNTMapManager.m

```
RCT_EXPORT_VIEW_PROPERTY(zoomEnabled, BOOL)
```

Note that we explicitly specify the type as `BOOL` - React Native uses `RCTConvert` under the hood to convert all sorts of different data types when talking over the bridge, and bad values will show convenient "RedBox" errors to let you know there is an issue ASAP. When things are straightforward like this, the whole implementation is taken care of for you by this macro.

Now to actually disable zooming, we set the property in JavaScript:

MyApp.tsx

```
import MapView from './MapView.tsx';



export default function MyApp() {

  return <MapView zoomEnabled={false} style={{flex: 1}} />;

}
```

To document the properties (and which values they accept) of our MapView component we'll add a wrapper component and document the interface with TypeScript:

MapView\.tsx

```
import {requireNativeComponent} from 'react-native';



const RNTMap = requireNativeComponent('RNTMap');



export default function MapView(props: {

  /**

   * Whether the user may use pinch gestures to zoom in and out.

   */

  zoomEnabled?: boolean;

}) {

  return <RNTMap {...props} />;

}
```

Now we have a nicely documented wrapper component to work with.

Next, let's add the more complex `region` prop. We start by adding the native code:

RNTMapManager.m

```
RCT_CUSTOM_VIEW_PROPERTY(region, MKCoordinateRegion, MKMapView)

{

  [view setRegion:json ? [RCTConvert MKCoordinateRegion:json] : defaultView.region animated:YES];

}
```

Ok, this is more complicated than the `BOOL` case we had before. Now we have a `MKCoordinateRegion` type that needs a conversion function, and we have custom code so that the view will animate when we set the region from JS. Within the function body that we provide, `json` refers to the raw value that has been passed from JS. There is also a `view` variable which gives us access to the manager's view instance, and a `defaultView` that we use to reset the property back to the default value if JS sends us a null sentinel.

You could write any conversion function you want for your view - here is the implementation for `MKCoordinateRegion` via a category on `RCTConvert`. It uses an already existing category of ReactNative `RCTConvert+CoreLocation`:

RNTMapManager.m

```
#import "RCTConvert+Mapkit.h"
```

RCTConvert+Mapkit.h

```
#import <MapKit/MapKit.h>

#import <React/RCTConvert.h>

#import <CoreLocation/CoreLocation.h>

#import <React/RCTConvert+CoreLocation.h>



@interface RCTConvert (Mapkit)



+ (MKCoordinateSpan)MKCoordinateSpan:(id)json;

+ (MKCoordinateRegion)MKCoordinateRegion:(id)json;



@end



@implementation RCTConvert(MapKit)



+ (MKCoordinateSpan)MKCoordinateSpan:(id)json

{

  json = [self NSDictionary:json];

  return (MKCoordinateSpan){

    [self CLLocationDegrees:json[@"latitudeDelta"]],

    [self CLLocationDegrees:json[@"longitudeDelta"]]

  };

}



+ (MKCoordinateRegion)MKCoordinateRegion:(id)json

{

  return (MKCoordinateRegion){

    [self CLLocationCoordinate2D:json],

    [self MKCoordinateSpan:json]

  };

}



@end
```

These conversion functions are designed to safely process any JSON that the JS might throw at them by displaying "RedBox" errors and returning standard initialization values when missing keys or other developer errors are encountered.

To finish up support for the `region` prop, we can document it with TypeScript:

MapView\.tsx

```
import {requireNativeComponent} from 'react-native';



const RNTMap = requireNativeComponent('RNTMap');



export default function MapView(props: {

  /**

   * The region to be displayed by the map.

   *

   * The region is defined by the center coordinates and the span of

   * coordinates to display.

   */

  region?: {

    /**

     * Coordinates for the center of the map.

     */

    latitude: number;

    longitude: number;



    /**

     * Distance between the minimum and the maximum latitude/longitude

     * to be displayed.

     */

    latitudeDelta: number;

    longitudeDelta: number;

  };

  /**

   * Whether the user may use pinch gestures to zoom in and out.

   */

  zoomEnabled?: boolean;

}) {

  return <RNTMap {...props} />;

}
```

We can now supply the `region` prop to `MapView`:

MyApp.tsx

```
import MapView from './MapView.tsx';



export default function MyApp() {

  const region = {

    latitude: 37.48,

    longitude: -122.16,

    latitudeDelta: 0.1,

    longitudeDelta: 0.1,

  };

  return (

    <MapView

      region={region}

      zoomEnabled={false}

      style={{flex: 1}}

    />

  );

}
```

## Events[​](#events "Direct link to Events")

So now we have a native map component that we can control freely from JS, but how do we deal with events from the user, like pinch-zooms or panning to change the visible region?

Until now we've only returned a `MKMapView` instance from our manager's `-(UIView *)view` method. We can't add new properties to `MKMapView` so we have to create a new subclass from `MKMapView` which we use for our View. We can then add a `onRegionChange` callback on this subclass:

RNTMapView\.h

```
#import <MapKit/MapKit.h>



#import <React/RCTComponent.h>



@interface RNTMapView: MKMapView



@property (nonatomic, copy) RCTBubblingEventBlock onRegionChange;



@end
```

RNTMapView\.m

```
#import "RNTMapView.h"



@implementation RNTMapView



@end
```

Note that all `RCTBubblingEventBlock` must be prefixed with `on`. Next, declare an event handler property on `RNTMapManager`, make it a delegate for all the views it exposes, and forward events to JS by calling the event handler block from the native view.

RNTMapManager.m

```
#import <MapKit/MapKit.h>

#import <React/RCTViewManager.h>



#import "RNTMapView.h"

#import "RCTConvert+Mapkit.h"



@interface RNTMapManager : RCTViewManager <MKMapViewDelegate>

@end



@implementation RNTMapManager



RCT_EXPORT_MODULE()



RCT_EXPORT_VIEW_PROPERTY(zoomEnabled, BOOL)

RCT_EXPORT_VIEW_PROPERTY(onRegionChange, RCTBubblingEventBlock)



RCT_CUSTOM_VIEW_PROPERTY(region, MKCoordinateRegion, MKMapView)

{

  [view setRegion:json ? [RCTConvert MKCoordinateRegion:json] : defaultView.region animated:YES];

}



- (UIView *)view

{

  RNTMapView *map = [RNTMapView new];

  map.delegate = self;

  return map;

}



#pragma mark MKMapViewDelegate



- (void)mapView:(RNTMapView *)mapView regionDidChangeAnimated:(BOOL)animated

{

  if (!mapView.onRegionChange) {

    return;

  }



  MKCoordinateRegion region = mapView.region;

  mapView.onRegionChange(@{

    @"region": @{

      @"latitude": @(region.center.latitude),

      @"longitude": @(region.center.longitude),

      @"latitudeDelta": @(region.span.latitudeDelta),

      @"longitudeDelta": @(region.span.longitudeDelta),

    }

  });

}

@end
```

In the delegate method `-mapView:regionDidChangeAnimated:` the event handler block is called on the corresponding view with the region data. Calling the `onRegionChange` event handler block results in calling the same callback prop in JavaScript. This callback is invoked with the raw event, which we typically process in the wrapper component to simplify the API:

MapView\.tsx

```
// ...



type RegionChangeEvent = {

  nativeEvent: {

    latitude: number;

    longitude: number;

    latitudeDelta: number;

    longitudeDelta: number;

  };

};



export default function MapView(props: {

  // ...

  /**

   * Callback that is called continuously when the user is dragging the map.

   */

  onRegionChange: (event: RegionChangeEvent) => unknown;

}) {

  return <RNTMap {...props} onRegionChange={onRegionChange} />;

}
```

MyApp.tsx

```
import MapView from './MapView.tsx';



export default function MyApp() {

  // ...



  const onRegionChange = useCallback(event => {

    const {region} = event.nativeEvent;

    // Do something with `region.latitude`, etc.

  });



  return (

    <MapView

      // ...

      onRegionChange={onRegionChange}

    />

  );

}
```

## Handling multiple native views[​](#handling-multiple-native-views "Direct link to Handling multiple native views")

A React Native view can have more than one child view in the view tree eg.

React TSX

```
<View>

  <MyNativeView />

  <MyNativeView />

  <Button />

</View>
```

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:

React TSX

```
<View>

  <MyNativeView ref={this.myNativeReference} />

  <MyNativeView ref={this.myNativeReference2} />

  <Button

    onPress={() => {

      this.myNativeReference.callNativeMethod();

    }}

  />

</View>
```

Now the above component has a reference to a particular `MyNativeView` which allows us to use a specific instance of `MyNativeView`. Now the button can control which `MyNativeView` should change its `backgroundColor`. In this example let's assume that `callNativeMethod` changes `backgroundColor`.

MyNativeView\.ios.tsx

```
class MyNativeView extends React.Component {

  callNativeMethod = () => {

    UIManager.dispatchViewManagerCommand(

      ReactNative.findNodeHandle(this),

      UIManager.getViewManagerConfig('RNCMyNativeView').Commands

        .callNativeMethod,

      [],

    );

  };



  render() {

    return <NativeComponent ref={NATIVE_COMPONENT_REF} />;

  }

}
```

`callNativeMethod` is our custom iOS method which for example changes the `backgroundColor` which is exposed through `MyNativeView`. This method uses `UIManager.dispatchViewManagerCommand` which needs 3 parameters:

* `(nonnull NSNumber \*)reactTag`  -  id of react view.
* `commandID:(NSInteger)commandID`  -  Id of the native method that should be called
* `commandArgs:(NSArray<id> \*)commandArgs`  -  Args of the native method that we can pass from JS to native.

RNCMyNativeViewManager.m

```
#import <React/RCTViewManager.h>

#import <React/RCTUIManager.h>

#import <React/RCTLog.h>



RCT_EXPORT_METHOD(callNativeMethod:(nonnull NSNumber*) reactTag) {

    [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *,UIView *> *viewRegistry) {

        NativeView *view = viewRegistry[reactTag];

        if (!view || ![view isKindOfClass:[NativeView class]]) {

            RCTLogError(@"Cannot find NativeView with tag #%@", reactTag);

            return;

        }

        [view callNativeMethod];

    }];



}
```

Here the `callNativeMethod` is defined in the `RNCMyNativeViewManager.m` file and contains only one parameter which is `(nonnull NSNumber*) reactTag`. This exported function will find a particular view using `addUIBlock` which contains the `viewRegistry` parameter and returns the component based on `reactTag` allowing it to call the method on the correct component.

## Styles[​](#styles "Direct link to Styles")

Since all our native react views are subclasses of `UIView`, most style attributes will work like you would expect out of the box. Some components will want a default style, however, for example `UIDatePicker` which is a fixed size. This default style is important for the layout algorithm to work as expected, but we also want to be able to override the default style when using the component. `DatePickerIOS` does this by wrapping the native component in an extra view, which has flexible styling, and using a fixed style (which is generated with constants passed in from native) on the inner native component:

DatePickerIOS.ios.tsx

```
import {UIManager} from 'react-native';

const RCTDatePickerIOSConsts = UIManager.RCTDatePicker.Constants;

...

  render: function() {

    return (

      <View style={this.props.style}>

        <RCTDatePickerIOS

          ref={DATEPICKER}

          style={styles.rkDatePickerIOS}

          ...

        />

      </View>

    );

  }

});



const styles = StyleSheet.create({

  rkDatePickerIOS: {

    height: RCTDatePickerIOSConsts.ComponentHeight,

    width: RCTDatePickerIOSConsts.ComponentWidth,

  },

});
```

The `RCTDatePickerIOSConsts` constants are exported from native by grabbing the actual frame of the native component like so:

RCTDatePickerManager.m

```
- (NSDictionary *)constantsToExport

{

  UIDatePicker *dp = [[UIDatePicker alloc] init];

  [dp layoutIfNeeded];



  return @{

    @"ComponentHeight": @(CGRectGetHeight(dp.frame)),

    @"ComponentWidth": @(CGRectGetWidth(dp.frame)),

    @"DatePickerModes": @{

      @"time": @(UIDatePickerModeTime),

      @"date": @(UIDatePickerModeDate),

      @"datetime": @(UIDatePickerModeDateAndTime),

    }

  };

}
```

This guide covered many of the aspects of bridging over custom native components, but there is even more you might need to consider, such as custom hooks for inserting and laying out subviews. If you want to go even deeper, check out the [source code](https://github.com/react/react-native/tree/main/packages/react-native/React/Views) of some of the implemented components.

* [iOS MapView example](#ios-mapview-example)
* [Properties](#properties)
* [Events](#events)
* [Handling multiple native views](#handling-multiple-native-views)
* [Styles](#styles)

----
url: https://reactnative.dev/docs/next/keyboard
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/keyboard)** (0.87).

Version: Next

`Keyboard` module to control keyboard events.

### Usage[​](#usage "Direct link to Usage")

The Keyboard module allows you to listen for native events and react to them, as well as make changes to the keyboard, like dismissing it.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `addListener()`[​](#addlistener "Direct link to addlistener")

React TSX

```
static addListener: (

  eventType: KeyboardEventName,

  listener: KeyboardEventListener,

) => EventSubscription;
```

The `addListener` function connects a JavaScript function to an identified native keyboard notification event.

This function then returns the reference to the listener.

**Parameters:**

| Name              | Type     | Description                                                                    |
| ----------------- | -------- | ------------------------------------------------------------------------------ |
| eventNameRequired | string   | The string that identifies the event you're listening for. See the list below. |
| callbackRequired  | function | The function to be called when the event fires                                 |

***

### `dismiss()`[​](#dismiss "Direct link to dismiss")

React TSX

```
static dismiss();
```

Dismisses the active keyboard and removes focus.

***

### `scheduleLayoutAnimation`[​](#schedulelayoutanimation "Direct link to schedulelayoutanimation")

React TSX

```
static scheduleLayoutAnimation(event: KeyboardEvent);
```

Useful for syncing TextInput (or other keyboard accessory view) size of position changes with keyboard movements.

***

### `isVisible()`[​](#isvisible "Direct link to isvisible")

React TSX

```
static isVisible(): boolean;
```

Whether the keyboard is last known to be visible.

***

### `metrics()`[​](#metrics "Direct link to metrics")

React TSX

```
static metrics(): KeyboardMetrics | undefined;
```

----
url: https://reactnative.dev/docs/next/style
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/style)** (0.87).

Version: Next

With React Native, you style your application using JavaScript. All of the core components accept a prop named `style`. The style names and [values](/docs/next/colors) usually match how CSS works on the web, except names are written using camel casing, e.g. `backgroundColor` rather than `background-color`.

The `style` prop can be a plain old JavaScript object. That's what we usually use for example code. You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles.

As a component grows in complexity, it is often cleaner to use `StyleSheet.create` to define several styles in one place. Here's an example:

One common pattern is to make your component accept a `style` prop which in turn is used to style subcomponents. You can use this to make styles "cascade" the way they do in CSS.

There are a lot more ways to customize the text style. Check out the [Text component reference](/docs/next/text) for a complete list.

Now you can make your text beautiful. The next step in becoming a style expert is to [learn how to control component size](/docs/next/height-and-width).

## Known issues[​](#known-issues "Direct link to Known issues")

* [react-native#29308](https://github.com/react/react-native/issues/29308#issuecomment-792864162): In some cases React Native does not match how CSS works on the web, for example the touch area never extends past the parent view bounds and on Android negative margin is not supported.

- [Known issues](#known-issues)

----
url: https://reactnative.dev/docs/global-setTimeout
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout) for more information.

The global `setTimeout` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/touchablenativefeedback
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

tip

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the [Pressable](/docs/pressable) API.

A wrapper for making views respond properly to touches (Android only). On Android this component uses native state drawable to display touch feedback.

At the moment it only supports having a single View instance as a child node, as it's implemented by replacing that View with another instance of RCTView node with some additional properties set.

Background drawable of native feedback touchable can be customized with `background` property.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [TouchableWithoutFeedback Props](/docs/touchablewithoutfeedback#props)[​](#touchablewithoutfeedback-props "Direct link to touchablewithoutfeedback-props")

Inherits [TouchableWithoutFeedback Props](/docs/touchablewithoutfeedback#props).

***

### `background`[​](#background "Direct link to background")

Determines the type of background drawable that's going to be used to display feedback. It takes an object with `type` property and extra data depending on the `type`. It's recommended to use one of the static methods to generate that dictionary.

| Type               |
| ------------------ |
| backgroundPropType |

***

### `useForeground`[​](#useforeground "Direct link to useforeground")

Set to true to add the ripple effect to the foreground of the view, instead of the background. This is useful if one of your child views has a background of its own, or you're e.g. displaying images, and you don't want the ripple to be covered by them.

Check TouchableNativeFeedback.canUseNativeForeground() first, as this is only available on Android 6.0 and above. If you try to use this on older versions you will get a warning and fallback to background.

| Type |
| ---- |
| bool |

***

### `hasTVPreferredFocus`Android[​](#hastvpreferredfocus-android "Direct link to hastvpreferredfocus-android")

TV preferred focus (see documentation for the View component).

| Type |
| ---- |
| bool |

***

### `nextFocusDown`Android[​](#nextfocusdown-android "Direct link to nextfocusdown-android")

TV next focus down (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`Android[​](#nextfocusforward-android "Direct link to nextfocusforward-android")

TV next focus forward (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`Android[​](#nextfocusleft-android "Direct link to nextfocusleft-android")

TV next focus left (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`Android[​](#nextfocusright-android "Direct link to nextfocusright-android")

TV next focus right (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`Android[​](#nextfocusup-android "Direct link to nextfocusup-android")

TV next focus up (see documentation for the View component).

| Type   |
| ------ |
| number |

## Methods[​](#methods "Direct link to Methods")

### `SelectableBackground()`[​](#selectablebackground "Direct link to selectablebackground")

React TSX

```
static SelectableBackground(

  rippleRadius: number | null,

): ThemeAttributeBackgroundPropType;
```

Creates an object that represents android theme's default background for selectable elements (`?android:attr/selectableItemBackground`). `rippleRadius` parameter controls the radius of the ripple effect.

***

### `SelectableBackgroundBorderless()`[​](#selectablebackgroundborderless "Direct link to selectablebackgroundborderless")

React TSX

```
static SelectableBackgroundBorderless(

  rippleRadius: number | null,

): ThemeAttributeBackgroundPropType;
```

Creates an object that represent android theme's default background for borderless selectable elements (`?android:attr/selectableItemBackgroundBorderless`). Available on android API level 21+. `rippleRadius` parameter controls the radius of the ripple effect.

***

### `Ripple()`[​](#ripple "Direct link to ripple")

React TSX

```
static Ripple(

  color: ColorValue,

  borderless: boolean,

  rippleRadius?: number | null,

): RippleBackgroundPropType;
```

Creates an object that represents ripple drawable with specified color (as a string). If property `borderless` evaluates to true the ripple will render outside of the view bounds (see native actionbar buttons as an example of that behavior). This background type is available on Android API level 21+.

**Parameters:**

| Name         | Type    | Required | Description                                 |
| ------------ | ------- | -------- | ------------------------------------------- |
| color        | string  | Yes      | The ripple color                            |
| borderless   | boolean | Yes      | If the ripple can render outside its bounds |
| rippleRadius | ?number | No       | controls the radius of the ripple effect    |

***

### `canUseNativeForeground()`[​](#canusenativeforeground "Direct link to canusenativeforeground")

React TSX

```
static canUseNativeForeground(): boolean;
```

* [Example](#example)

* [Props](#props)

  * [TouchableWithoutFeedback Props](#touchablewithoutfeedback-props)
  * [`background`](#background)
  * [`useForeground`](#useforeground)
  * [`hasTVPreferredFocus`](#hastvpreferredfocus-android)

    [Android](#hastvpreferredfocus-android)
  * [`nextFocusDown`](#nextfocusdown-android)

    [Android](#nextfocusdown-android)
  * [`nextFocusForward`](#nextfocusforward-android)

    [Android](#nextfocusforward-android)
  * [`nextFocusLeft`](#nextfocusleft-android)

    [Android](#nextfocusleft-android)
  * [`nextFocusRight`](#nextfocusright-android)

    [Android](#nextfocusright-android)
  * [`nextFocusUp`](#nextfocusup-android)

    [Android](#nextfocusup-android)

* [Methods](#methods)

  * [`SelectableBackground()`](#selectablebackground)
  * [`SelectableBackgroundBorderless()`](#selectablebackgroundborderless)
  * [`Ripple()`](#ripple)
  * [`canUseNativeForeground()`](#canusenativeforeground)

----
url: https://reactnative.dev/docs/next/out-of-tree-platforms
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/out-of-tree-platforms)** (0.87).

Version: Next

```
{

  "rnpm": {

    "haste": {

      "providesModuleNodeModules": ["react-native-example"],

      "platforms": ["example"]

    }

  }

}
```

`"providesModuleNodeModules"` is an array of modules that will get added to the Haste module search path, and `"platforms"` is an array of platform suffixes that will be added as valid platforms.

* [Creating your own React Native platform](#creating-your-own-react-native-platform)
  * [Bundling](#bundling)

----
url: https://reactnative.dev/docs/next/global-requestAnimationFrame
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-requestAnimationFrame)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame) for more information.

The global `requestAnimationFrame` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-clearTimeout
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearTimeout) for more information.

The global `clearTimeout` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/text
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/text)** (0.87).

Version: Next

A React component for displaying text.

`Text` supports nesting, styling, and touch handling.

In the following example, the nested title and body text will inherit the `fontFamily` from `styles.baseText`, but the title provides its own additional styles. The title and body will stack on top of each other on account of the literal newlines:

## Nested text[​](#nested-text "Direct link to Nested text")

Both Android and iOS allow you to display formatted text by annotating ranges of a string with specific formatting like bold or colored text (`NSAttributedString` on iOS, `SpannableString` on Android). In practice, this is very tedious. For React Native, we decided to use the web paradigm for this, where you can nest text to achieve the same effect.

Behind the scenes, React Native converts this to a flat `NSAttributedString` or `SpannableString` that contains the following information:

```
"I am bold and red"

0-9: bold

9-17: bold, red
```

## Containers[​](#containers "Direct link to Containers")

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.

React TSX

```
<Text>

  <Text>First part and </Text>

  <Text>second part</Text>

</Text>

// Text container: the text will be inline, if the space allows it

// |First part and second part|



// otherwise, the text will flow as if it was one

// |First part |

// |and second |

// |part       |



<View>

  <Text>First part and </Text>

  <Text>second part</Text>

</View>

// View container: each text is its own block

// |First part and|

// |second part   |



// otherwise, the text will flow in its own block

// |First part |

// |and        |

// |second part|
```

## Limited Style Inheritance[​](#limited-style-inheritance "Direct link to Limited Style Inheritance")

On the web, the usual way to set a font family and size for the entire document is to take advantage of inherited CSS properties like so:

CSS

```
html {

  font-family:

    'lucida grande', tahoma, verdana, arial, sans-serif;

  font-size: 11px;

  color: #141823;

}
```

All elements in the document will inherit this font unless they or one of their parents specifies a new rule.

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>`.

React TSX

```
// BAD: will raise exception, can't have a text node as child of a <View>

<View>

  Some text

</View>



// GOOD

<View>

  <Text>

    Some text

  </Text>

</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.

React TSX

```
<View>

  <MyAppText>

    Text styled with the default font for the entire application

  </MyAppText>

  <MyAppHeaderText>Text styled as a header</MyAppHeaderText>

</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:

React TSX

```
const MyAppHeaderText = ({children}) => {

  return (

    <MyAppText>

      <Text style={{fontSize: 20}}>{children}</Text>

    </MyAppText>

  );

};
```

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.

React TSX

```
<Text style={{fontWeight: 'bold'}}>

  I am bold

  <Text style={{color: 'red'}}>and red</Text>

</Text>
```

We believe that this more constrained way to style text will yield better apps:

* (Developer) React components are designed with strong isolation in mind: You should be able to drop a component anywhere in your application, trusting that as long as the props are the same, it will look and behave the same way. Text properties that could inherit from outside of the props would break this isolation.

* (Implementor) The implementation of React Native is also simplified. We do not need to have a `fontFamily` field on every single element, and we do not need to potentially traverse the tree up to the root every time we display a text node. The style inheritance is only encoded inside of the native Text component and doesn't leak to other components or the system itself.

***

# Reference

## Props[​](#props "Direct link to Props")

### `accessibilityHint`[​](#accessibilityhint "Direct link to accessibilityhint")

An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label.

| Type   |
| ------ |
| string |

***

### `accessibilityLanguage`iOS[​](#accessibilitylanguage-ios "Direct link to accessibilitylanguage-ios")

A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the [BCP 47 specification](https://www.rfc-editor.org/info/bcp47).

See the [iOS `accessibilityLanguage` doc](https://developer.apple.com/documentation/objectivec/nsobject/1615192-accessibilitylanguage) for more information.

| Type   |
| ------ |
| string |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the `Text` nodes separated by space.

| Type   |
| ------ |
| string |

***

### `accessibilityRole`[​](#accessibilityrole "Direct link to accessibilityrole")

Tells the screen reader to treat the currently focused on element as having a specific role.

On iOS, these roles map to corresponding Accessibility Traits. Image button has the same functionality as if the trait was set to both 'image' and 'button'. See the [Accessibility guide](/docs/next/accessibility#accessibilityrole) for more information.

On Android, these roles have similar functionality on TalkBack as adding Accessibility Traits does on Voiceover in iOS

| Type                                                            |
| --------------------------------------------------------------- |
| [AccessibilityRole](/docs/next/accessibility#accessibilityrole) |

***

### `accessibilityState`[​](#accessibilitystate "Direct link to accessibilitystate")

Tells the screen reader to treat the currently focused on element as being in a specific state.

You can provide one state, no state, or multiple states. The states must be passed in through an object, e.g. `{selected: true, disabled: true}`.

| Type                                                              |
| ----------------------------------------------------------------- |
| [AccessibilityState](/docs/next/accessibility#accessibilitystate) |

***

### `accessibilityActions`[​](#accessibilityactions "Direct link to accessibilityactions")

Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The `accessibilityActions` property should contain a list of action objects. Each action object should contain the field name and label.

See the [Accessibility guide](/docs/next/accessibility#accessibility-actions) for more information.

| Type  | Required |
| ----- | -------- |
| array | No       |

***

### `onAccessibilityAction`[​](#onaccessibilityaction "Direct link to onaccessibilityaction")

Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

See the [Accessibility guide](/docs/next/accessibility#accessibility-actions) for more information.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `accessible`[​](#accessible "Direct link to accessible")

When set to `true`, indicates that the view is an accessibility element.

See the [Accessibility guide](/docs/next/accessibility#accessible) for more information.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

***

### `adjustsFontSizeToFit`[​](#adjustsfontsizetofit "Direct link to adjustsfontsizetofit")

Specifies whether fonts should be scaled down automatically to fit given style constraints.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `allowFontScaling`[​](#allowfontscaling "Direct link to allowfontscaling")

Specifies whether fonts should scale to respect Text Size accessibility settings.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

***

### `android_hyphenationFrequency`Android[​](#android_hyphenationfrequency-android "Direct link to android_hyphenationfrequency-android")

Sets the frequency of automatic hyphenation to use when determining word breaks on Android API Level 23+.

| Type                                | Default  |
| ----------------------------------- | -------- |
| enum(`'none'`, `'normal'`,`'full'`) | `'none'` |

***

### `aria-busy`[​](#aria-busy "Direct link to aria-busy")

Indicates an element is being modified and that assistive technologies may want to wait until the changes are complete before informing the user about the update.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-checked`[​](#aria-checked "Direct link to aria-checked")

Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

| Type             | Default |
| ---------------- | ------- |
| boolean, 'mixed' | false   |

***

### `aria-disabled`[​](#aria-disabled "Direct link to aria-disabled")

Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-expanded`[​](#aria-expanded "Direct link to aria-expanded")

Indicates whether an expandable element is currently expanded or collapsed.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-label`[​](#aria-label "Direct link to aria-label")

Defines a string value that labels an interactive element.

| Type   |
| ------ |
| string |

***

### `aria-selected`[​](#aria-selected "Direct link to aria-selected")

Indicates whether a selectable element is currently selected or not.

| Type    |
| ------- |
| boolean |

### `dataDetectorType`Android[​](#datadetectortype-android "Direct link to datadetectortype-android")

Determines the types of data converted to clickable URLs in the text element. By default, no data types are detected.

You can provide only one type.

| Type                                                          | Default  |
| ------------------------------------------------------------- | -------- |
| enum(`'phoneNumber'`, `'link'`, `'email'`, `'none'`, `'all'`) | `'none'` |

***

### `disabled`Android[​](#disabled-android "Direct link to disabled-android")

Specifies the disabled state of the text view for testing purposes.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `dynamicTypeRamp`iOS[​](#dynamictyperamp-ios "Direct link to dynamictyperamp-ios")

The [Dynamic Type](https://developer.apple.com/documentation/uikit/uifont/scaling_fonts_automatically) ramp to apply to this element on iOS.

| Type                                                                                                                                                     | Default  |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| enum(`'caption2'`, `'caption1'`, `'footnote'`, `'subheadline'`, `'callout'`, `'body'`, `'headline'`, `'title3'`, `'title2'`, `'title1'`, `'largeTitle'`) | `'body'` |

***

| Type                                           | Default |
| ---------------------------------------------- | ------- |
| enum(`'head'`, `'middle'`, `'tail'`, `'clip'`) | `tail`  |

***

### `id`[​](#id "Direct link to id")

Used to locate this view from native code. Has precedence over `nativeID` prop.

| Type   |
| ------ |
| string |

***

### `maxFontSizeMultiplier`[​](#maxfontsizemultiplier "Direct link to maxfontsizemultiplier")

Specifies the largest possible scale a font can reach when `allowFontScaling` is enabled. Possible values:

* `null/undefined`: inherit from the parent node or the global default (0)
* `0`: no max, ignore parent/global default
* `>= 1`: sets the `maxFontSizeMultiplier` of this node to this value

| Type   | Default     |
| ------ | ----------- |
| number | `undefined` |

***

### `minimumFontScale`[​](#minimumfontscale "Direct link to minimumfontscale")

Specifies the smallest possible scale a font can reach when `adjustsFontSizeToFit` is enabled. (values 0.01-1.0).

| Type   |
| ------ |
| number |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

Used to locate this view from native code.

| Type   |
| ------ |
| string |

***

### `numberOfLines`[​](#numberoflines "Direct link to numberoflines")

Used to truncate the text with an ellipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number. Setting this property to `0` will result in unsetting this value, which means that no lines restriction will be applied.

This prop is commonly used with `ellipsizeMode`.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: LayoutEvent}) => void` |

***

### `onLongPress`[​](#onlongpress "Direct link to onlongpress")

This function is called on long press.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onMoveShouldSetResponder`[​](#onmoveshouldsetresponder "Direct link to onmoveshouldsetresponder")

Does this view want to "claim" touch responsiveness? This is called for every touch move on the `View` when it is not the responder.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onPress`[​](#onpress "Direct link to onpress")

Function called on user press, triggered after `onPressOut`.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onPressIn`[​](#onpressin "Direct link to onpressin")

Called immediately when a touch is engaged, before `onPressOut` and `onPress`.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onPressOut`[​](#onpressout "Direct link to onpressout")

Called when a touch is released.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderGrant`[​](#onrespondergrant "Direct link to onrespondergrant")

The View is now responding to touch events. This is the time to highlight and show the user what is happening.

On Android, return true from this callback to prevent any other native components from becoming responder until this responder terminates.

| Type                                            |
| ----------------------------------------------- |
| `({nativeEvent: PressEvent}) => void ｜ boolean` |

***

### `onResponderMove`[​](#onrespondermove "Direct link to onrespondermove")

The user is moving their finger.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderRelease`[​](#onresponderrelease "Direct link to onresponderrelease")

Fired at the end of the touch.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderTerminate`[​](#onresponderterminate "Direct link to onresponderterminate")

The responder has been taken from the `View`. Might be taken by other views after a call to `onResponderTerminationRequest`, or might be taken by the OS without asking (e.g., happens with control center/ notification center on iOS)

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderTerminationRequest`[​](#onresponderterminationrequest "Direct link to onresponderterminationrequest")

Some other `View` wants to become a responder and is asking this `View` to release its responder. Returning `true` allows its release.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onStartShouldSetResponderCapture`[​](#onstartshouldsetrespondercapture "Direct link to onstartshouldsetrespondercapture")

If a parent `View` wants to prevent a child `View` from becoming a responder on a touch start, it should have this handler which returns `true`.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onTextLayout`[​](#ontextlayout "Direct link to ontextlayout")

Invoked on Text layout change.

| Type                                                            |
| --------------------------------------------------------------- |
| ([`TextLayoutEvent`](/docs/next/text#textlayoutevent)) => mixed |

***

### `pressRetentionOffset`[​](#pressretentionoffset "Direct link to pressretentionoffset")

When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view is disabled. Ensure you pass in a constant to reduce memory allocations.

| Type                            |
| ------------------------------- |
| [Rect](/docs/next/rect), number |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/next/element-nodes) when mounted.

Note that `Text` components don't provide text nodes, the same way that paragraph elements (`<p>`) on Web are element nodes instead of text nodes. Text nodes can be found as their child nodes instead.

***

### `role`[​](#role "Direct link to role")

`role` communicates the purpose of a component to the user of an assistive technology. Has precedence over the [`accessibilityRole`](/docs/next/text#accessibilityrole) prop.

| Type                                  |
| ------------------------------------- |
| [Role](/docs/next/accessibility#role) |

***

### `selectable`[​](#selectable "Direct link to selectable")

Lets the user select text, to use the native copy and paste functionality.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `selectionColor`Android[​](#selectioncolor-android "Direct link to selectioncolor-android")

The highlight color of the text.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `style`[​](#style "Direct link to style")

| Type                                                                                       |
| ------------------------------------------------------------------------------------------ |
| [Text Style](/docs/next/text-style-props), [View Style Props](/docs/next/view-style-props) |

***

### `suppressHighlighting`iOS[​](#suppresshighlighting-ios "Direct link to suppresshighlighting-ios")

When `true`, no visual change is made when text is pressed down. By default, a gray oval highlights the text on press down.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

| Type   |
| ------ |
| string |

***

### `textBreakStrategy`Android[​](#textbreakstrategy-android "Direct link to textbreakstrategy-android")

Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced`.

| Type                                            | Default       |
| ----------------------------------------------- | ------------- |
| enum(`'simple'`, `'highQuality'`, `'balanced'`) | `highQuality` |

***

### `lineBreakStrategyIOS`iOS[​](#linebreakstrategyios-ios "Direct link to linebreakstrategyios-ios")

Set line break strategy on iOS 14+. Possible values are `none`, `standard`, `hangul-word` and `push-out`.

| Type                                                        | Default  |
| ----------------------------------------------------------- | -------- |
| enum(`'none'`, `'standard'`, `'hangul-word'`, `'push-out'`) | `'none'` |

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### TextLayout[​](#textlayout "Direct link to TextLayout")

`TextLayout` object is a part of [`TextLayoutEvent`](/docs/next/text#textlayoutevent) callback and contains the measurement data for `Text` line.

#### Example[​](#example "Direct link to Example")

JavaScript

```
{

    capHeight: 10.496,

    ascender: 14.624,

    descender: 4,

    width: 28.224,

    height: 18.624,

    xHeight: 6.048,

    x: 0,

    y: 0

}
```

#### Properties[​](#properties "Direct link to Properties")

| Name      | Type   | Optional | Description                                                         |
| --------- | ------ | -------- | ------------------------------------------------------------------- |
| ascender  | number | No       | The line ascender height after the text layout changes.             |
| capHeight | number | No       | Height of capital letter above the baseline.                        |
| descender | number | No       | The line descender height after the text layout changes.            |
| height    | number | No       | Height of the line after the text layout changes.                   |
| width     | number | No       | Width of the line after the text layout changes.                    |
| x         | number | No       | Line X coordinate inside the Text component.                        |
| xHeight   | number | No       | Distance between the baseline and median of the line (corpus size). |
| y         | number | No       | Line Y coordinate inside the Text component.                        |

### TextLayoutEvent[​](#textlayoutevent "Direct link to TextLayoutEvent")

`TextLayoutEvent` object is returned in the callback as a result of a component layout change. It contains a key called `lines` with a value which is an array containing [`TextLayout`](/docs/next/text#textlayout) object corresponded to every rendered text line.

#### Example[​](#example-1 "Direct link to Example")

JavaScript

```
{

  lines: [

    TextLayout,

    TextLayout,

    // ...

  ];

  target: 1127;

}
```

#### Properties[​](#properties-1 "Direct link to Properties")

| Name   | Type                                               | Optional | Description                                           |
| ------ | -------------------------------------------------- | -------- | ----------------------------------------------------- |
| lines  | array of [TextLayout](/docs/next/text#textlayout)s | No       | Provides the TextLayout data for every rendered line. |
| target | number                                             | No       | The node id of the element.                           |

* [Nested text](#nested-text)

* [Containers](#containers)

* [Limited Style Inheritance](#limited-style-inheritance)

* [Props](#props)

  * [`accessibilityHint`](#accessibilityhint)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)

    [Android](#android_hyphenationfrequency-android)

    [Android](#datadetectortype-android)
  * [`disabled`](#disabled-android)

    [Android](#disabled-android)
  * [`dynamicTypeRamp`](#dynamictyperamp-ios)

    [iOS](#dynamictyperamp-ios)

    [Android](#selectioncolor-android)
  * [`style`](#style)
  * [`suppressHighlighting`](#suppresshighlighting-ios)

    [iOS](#suppresshighlighting-ios)
  * [`testID`](#testid)
  * [`textBreakStrategy`](#textbreakstrategy-android)

    [Android](#textbreakstrategy-android)
  * [`lineBreakStrategyIOS`](#linebreakstrategyios-ios)

    [iOS](#linebreakstrategyios-ios)

* [Type Definitions](#type-definitions)

  * [TextLayout](#textlayout)
  * [TextLayoutEvent](#textlayoutevent)

----
url: https://reactnative.dev/docs/next/the-new-architecture/native-modules-custom-events
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/the-new-architecture/native-modules-custom-events)** (0.87).

Version: Next

```
+import type {TurboModule, CodegenTypes} from 'react-native';

import {TurboModuleRegistry} from 'react-native';



+export type KeyValuePair = {

+  key: string,

+  value: string,

+}



export interface Spec extends TurboModule {

  setItem(value: string, key: string): void;

  getItem(key: string): string | null;

  removeItem(key: string): void;

  clear(): void;



+ readonly onKeyAdded: CodegenTypes.EventEmitter<KeyValuePair>;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeLocalStorage',

);
```

Open the `NativeLocalStorage.js` file and update it as it follows:

NativeLocalStorage.js

```


// @flow

+import type {TurboModule, CodegenTypes} from 'react-native';

import {TurboModule, TurboModuleRegistry} from 'react-native';



+export type KeyValuePair = {

+  key: string,

+  value: string,

+}



export interface Spec extends TurboModule {

  setItem(value: string, key: string): void;

  getItem(key: string): ?string;

  removeItem(key: string): void;

  clear(): void;

+ onKeyAdded: CodegenTypes.EventEmitter<KeyValuePair>

}

export default (TurboModuleRegistry.get<Spec>(

  'NativeLocalStorage'

): ?Spec);
```

```
cd android

./gradlew generateCodegenArtifactsFromSchema



BUILD SUCCESSFUL in 837ms

14 actionable tasks: 3 executed, 11 up-to-date
```

This is automatically run when you build your Android application.

Codegen is run as part of the script phases that's automatically added to the project generated by CocoaPods.

```
cd ios

bundle install

bundle exec pod install
```

The output will look like this:

```
...

Framework build type is static library

[Codegen] Adding script_phases to ReactCodegen.

[Codegen] Generating ./build/generated/ios/ReactCodegen.podspec.json

[Codegen] Analyzing /Users/me/src/TurboModuleExample/package.json

[Codegen] Searching for Codegen-enabled libraries in the app.

[Codegen] Found TurboModuleExample

[Codegen] Searching for Codegen-enabled libraries in the project dependencies.

[Codegen] Found react-native

...
```

## Step 3: Update the App code[​](#step-3-update-the-app-code "Direct link to Step 3: Update the App code")

Now, it's time to update the code of the App to handle the new event.

Open the `App.tsx` file and modify it as it follows:

App.tsx

```
import {

+ Alert,

+ EventSubscription,

  SafeAreaView,

  StyleSheet,

  Text,

  TextInput,

  Button,

} from 'react-native';



import NativeLocalStorage from './specs/NativeLocalStorage';



const EMPTY = '<empty>';



function App(): React.JSX.Element {

  const [value, setValue] = React.useState<string | null>(null);

+ const [key, setKey] = React.useState<string | null>(null);

+ const listenerSubscription = React.useRef<null | EventSubscription>(null);



+ React.useEffect(() => {

+   listenerSubscription.current = NativeLocalStorage?.onKeyAdded((pair) => Alert.alert(`New key added: ${pair.key} with value: ${pair.value}`));



+   return  () => {

+     listenerSubscription.current?.remove();

+     listenerSubscription.current = null;

+   }

+ }, [])



  const [editingValue, setEditingValue] = React.useState<

    string | null

  >(null);



- React.useEffect(() => {

-   const storedValue = NativeLocalStorage?.getItem('myKey');

-   setValue(storedValue ?? '');

- }, []);



  function saveValue() {

+   if (key == null) {

+     Alert.alert('Please enter a key');

+     return;

+   }

    NativeLocalStorage?.setItem(editingValue ?? EMPTY, key);

    setValue(editingValue);

  }



  function clearAll() {

    NativeLocalStorage?.clear();

    setValue('');

  }



  function deleteValue() {

+   if (key == null) {

+     Alert.alert('Please enter a key');

+     return;

+   }

    NativeLocalStorage?.removeItem(key);

    setValue('');

  }



+ function retrieveValue() {

+   if (key == null) {

+     Alert.alert('Please enter a key');

+     return;

+   }

+   const val = NativeLocalStorage?.getItem(key);

+   setValue(val);

+ }



  return (

    <SafeAreaView style={{flex: 1}}>

      <Text style={styles.text}>

        Current stored value is: {value ?? 'No Value'}

      </Text>

+     <Text>Key:</Text>

+      <TextInput

+       placeholder="Enter the key you want to store"

+       style={styles.textInput}

+       onChangeText={setKey}

+     />

+     <Text>Value:</Text>

      <TextInput

        placeholder="Enter the text you want to store"

        style={styles.textInput}

        onChangeText={setEditingValue}

      />

      <Button title="Save" onPress={saveValue} />

+     <Button title="Retrieve" onPress={retrieveValue} />

      <Button title="Delete" onPress={deleteValue} />

      <Button title="Clear" onPress={clearAll} />

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  text: {

    margin: 10,

    fontSize: 20,

  },

  textInput: {

    margin: 10,

    height: 40,

    borderColor: 'black',

    borderWidth: 1,

    paddingLeft: 5,

    paddingRight: 5,

    borderRadius: 5,

  },

});



export default App;
```

```
package com.nativelocalstorage



import android.content.Context

import android.content.SharedPreferences

import com.nativelocalstorage.NativeLocalStorageSpec

+import com.facebook.react.bridge.Arguments

import com.facebook.react.bridge.ReactApplicationContext

+import com.facebook.react.bridge.WritableMap



class NativeLocalStorageModule(reactContext: ReactApplicationContext) : NativeLocalStorageSpec(reactContext) {



  override fun getName() = NAME



  override fun setItem(value: String, key: String) {

+   var shouldEmit = false

+   if (getItem(key) != null) {

+       shouldEmit = true

+   }

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.putString(key, value)

    editor.apply()



+   if (shouldEmit == true) {

+       val eventData = Arguments.createMap().apply {

+           putString("key", key)

+           putString("value", value)

+       }

+       emitOnKeyAdded(eventData)

+   }

  }



  override fun getItem(key: String): String? {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val username = sharedPref.getString(key, null)

    return username.toString()

  }
```

```
#import <Foundation/Foundation.h>

#import <NativeLocalStorageSpec/NativeLocalStorageSpec.h>



NS_ASSUME_NONNULL_BEGIN



-@interface RCTNativeLocalStorage : NSObject <NativeLocalStorageSpec>

+@interface RCTNativeLocalStorage : NativeLocalStorageSpecBase <NativeLocalStorageSpec>



@end



NS_ASSUME_NONNULL_END
```

3. Open the `RCTNativeLocalStorage.mm` file.
4. Modify it to emit the events when needed, for example:

RCTNativeLocalStorage.mm

```
 - (void)setItem:(NSString *)value key:(NSString *)key {

+  BOOL shouldEmitEvent = NO;

+  if (![self getItem:key]) {

+    shouldEmitEvent = YES;

+  }

   [self.localStorage setObject:value forKey:key];



+  if (shouldEmitEvent) {

+    [self emitOnKeyAdded:@{@"key": key, @"value": value}];

+  }

}
```

The `NativeLocalStorageSpecBase` is a base class that provides the `emitOnKeyAdded` method and its basic implementation and boilerplate. Thanks to this class, you don't have to handle all the conversion between Objective-C and JSI that is required to send the event to JS.

In case of complex types, like the `KeyValuePair` defined in the specs, Codegen will generate a generic dictionary that you can populate on the native side. It's your responsibility to make sure that the the keys you are using in the dictionary are the same properties that are defined in the spec type in JS.

## Step 5: Run Your App[​](#step-5-run-your-app "Direct link to Step 5: Run Your App")

If you now try to run your app, you should see this behavior.

| Android | iOS |
| ------- | --- |
|         |     |

* [Emitting an Event when a new key added to the storage](#emitting-an-event-when-a-new-key-added-to-the-storage)
* [Step 1: Update the Specs of NativeLocalStorage](#step-1-update-the-specs-of-nativelocalstorage)
* [Step 2: Generate Codegen](#step-2-generate-codegen)
* [Step 3: Update the App code](#step-3-update-the-app-code)
* [Step 4: Write your Native Code](#step-4-write-your-native-code)
* [Step 5: Run Your App](#step-5-run-your-app)

----
url: https://reactnative.dev/docs/switch
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Renders a boolean input.

This is a controlled component that requires an `onValueChange` callback that updates the `value` prop in order for the component to reflect user actions. If the `value` prop is not updated, the component will continue to render the supplied `value` prop instead of the expected result of any user actions.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### `disabled`[​](#disabled "Direct link to disabled")

If true the user won't be able to toggle the switch.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `ios_backgroundColor`iOS[​](#ios_backgroundcolor-ios "Direct link to ios_backgroundcolor-ios")

On iOS, custom color for the background. This background color can be seen either when the switch value is `false` or when the switch is disabled (and the switch is translucent).

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `onChange`[​](#onchange "Direct link to onchange")

Invoked when the user tries to change the value of the switch. Receives the change event as an argument. If you want to only receive the new value, use `onValueChange` instead.

| Type     |
| -------- |
| function |

***

### `onValueChange`[​](#onvaluechange "Direct link to onvaluechange")

Invoked when the user tries to change the value of the switch. Receives the new value as an argument. If you want to instead receive an event, use `onChange`.

| Type     |
| -------- |
| function |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/element-nodes) when mounted.

***

### `thumbColor`[​](#thumbcolor "Direct link to thumbcolor")

Color of the foreground switch grip. If this is set on iOS, the switch grip will lose its drop shadow.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `trackColor`[​](#trackcolor "Direct link to trackcolor")

Custom colors for the switch track.

*iOS*: When the switch value is `false`, the track shrinks into the border. If you want to change the color of the background exposed by the shrunken track, use [`ios_backgroundColor`](/docs/switch#ios_backgroundcolor-ios).

| Type                                  |
| ------------------------------------- |
| `object: {false: color, true: color}` |

***

### `value`[​](#value "Direct link to value")

The value of the switch. If true the switch will be turned on. Default value is false.

| Type |
| ---- |
| bool |

* [Example](#example)

* [Props](#props)

  * [View Props](#view-props)
  * [`disabled`](#disabled)
  * [`ios_backgroundColor`](#ios_backgroundcolor-ios)

    [iOS](#ios_backgroundcolor-ios)
  * [`onChange`](#onchange)
  * [`onValueChange`](#onvaluechange)
  * [`ref`](#ref)
  * [`thumbColor`](#thumbcolor)
  * [`trackColor`](#trackcolor)
  * [`value`](#value)

----
url: https://reactnative.dev/docs/next/virtualizedlist
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/virtualizedlist)** (0.87).

Version: Next

Base implementation for the more convenient [`<FlatList>`](/docs/next/flatlist) and [`<SectionList>`](/docs/next/sectionlist) components, which are also better documented. In general, this should only really be used if you need more flexibility than [`FlatList`](/docs/next/flatlist) provides, e.g. for use with immutable data instead of plain arrays.

Virtualization massively improves memory consumption and performance of large lists by maintaining a finite render window of active items and replacing all items outside of the render window with appropriately sized blank space. The window adapts to scrolling behavior, and items are rendered incrementally with low-pri (after any running interactions) if they are far from the visible area, or with hi-pri otherwise to minimize the potential of seeing blank space.

## Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

***

Some caveats:

* Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
* This is a `PureComponent` which means that it will not re-render if `props` are shallow-equal. Make sure that everything your `renderItem` function depends on is passed as a prop (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on changes. This includes the `data` prop and parent component state.
* In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
* By default, the list looks for a `key` prop on each item and uses that for the React key. Alternatively, you can provide a custom `keyExtractor` prop.

***

# Reference

## Props[​](#props "Direct link to Props")

### [ScrollView Props](/docs/next/scrollview#props)[​](#scrollview-props "Direct link to scrollview-props")

Inherits [ScrollView Props](/docs/next/scrollview#props).

***

### `data`[​](#data "Direct link to data")

Opaque data type passed to `getItem` and `getItemCount` to retrieve items.

| Type |
| ---- |
| any  |

***

### Require&#x64;**`getItem`**[​](#required-getitem "Direct link to required-getitem")

React TSX

```
(data: any, index: number) => any;
```

A generic accessor for extracting an item from any sort of data blob.

| Type     |
| -------- |
| function |

***

### Require&#x64;**`getItemCount`**[​](#required-getitemcount "Direct link to required-getitemcount")

React TSX

```
(data: any) => number;
```

Determines how many items are in the data blob.

| Type     |
| -------- |
| function |

***

### Require&#x64;**`renderItem`**[​](#required-renderitem "Direct link to required-renderitem")

React TSX

```
(info: any) => ?React.Element<any>
```

Takes an item from `data` and renders it into the list

| Type     |
| -------- |
| function |

***

### `CellRendererComponent`[​](#cellrenderercomponent "Direct link to cellrenderercomponent")

CellRendererComponent allows customizing how cells rendered by `renderItem`/`ListItemComponent` are wrapped when placed into the underlying ScrollView. This component must accept event handlers which notify VirtualizedList of changes within the cell.

| Type                                     |
| ---------------------------------------- |
| `React.ComponentType<CellRendererProps>` |

***

### `ItemSeparatorComponent`[​](#itemseparatorcomponent "Direct link to itemseparatorcomponent")

Rendered in between each item, but not at the top or bottom. By default, `highlighted` and `leadingItem` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` which will update the `highlighted` prop, but you can also add custom props with `separators.updateProps`. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type                         |
| ---------------------------- |
| component, function, element |

***

### `ListEmptyComponent`[​](#listemptycomponent "Direct link to listemptycomponent")

Rendered when the list is empty. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListItemComponent`[​](#listitemcomponent "Direct link to listitemcomponent")

Each data item is rendered using this element. Can be a React Component Class, or a render function.

| Type                |
| ------------------- |
| component, function |

***

### `ListFooterComponent`[​](#listfootercomponent "Direct link to listfootercomponent")

Rendered at the bottom of all the items. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListFooterComponentStyle`[​](#listfootercomponentstyle "Direct link to listfootercomponentstyle")

Styling for internal View for `ListFooterComponent`.

| Type          | Required |
| ------------- | -------- |
| ViewStyleProp | No       |

***

### `ListHeaderComponent`[​](#listheadercomponent "Direct link to listheadercomponent")

Rendered at the top of all the items. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListHeaderComponentStyle`[​](#listheadercomponentstyle "Direct link to listheadercomponentstyle")

Styling for internal View for `ListHeaderComponent`.

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

***

### `debug`[​](#debug "Direct link to debug")

`debug` will turn on extra logging and visual overlays to aid with debugging both usage and implementation, but with a significant perf hit.

| Type    |
| ------- |
| boolean |

***

### 🗑️ `disableVirtualization`[​](#️-disablevirtualization "Direct link to ️-disablevirtualization")

Deprecated

Virtualization provides significant performance and memory optimizations, but fully unmounts react instances that are outside of the render window. You should only need to disable this for debugging purposes.

| Type    |
| ------- |
| boolean |

***

### `extraData`[​](#extradata "Direct link to extradata")

A marker property for telling the list to re-render (since it implements `PureComponent`). If any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the `data` prop, stick it here and treat it immutably.

| Type |
| ---- |
| any  |

***

### `getItemLayout`[​](#getitemlayout "Direct link to getitemlayout")

React TSX

```
(

  data: any,

  index: number,

) => {length: number, offset: number, index: number}
```

| Type     |
| -------- |
| function |

***

### `horizontal`[​](#horizontal "Direct link to horizontal")

If `true`, renders items next to each other horizontally instead of stacked vertically.

| Type    |
| ------- |
| boolean |

***

### `initialNumToRender`[​](#initialnumtorender "Direct link to initialnumtorender")

How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.

| Type   | Default |
| ------ | ------- |
| number | `10`    |

***

### `initialScrollIndex`[​](#initialscrollindex "Direct link to initialscrollindex")

Instead of starting at the top with the first item, start at `initialScrollIndex`. This disables the "scroll to top" optimization that keeps the first `initialNumToRender` items always rendered and immediately renders the items starting at this initial index. Requires `getItemLayout` to be implemented.

| Type   |
| ------ |
| number |

***

### `inverted`[​](#inverted "Direct link to inverted")

Reverses the direction of scroll. Uses scale transforms of `-1`.

| Type    |
| ------- |
| boolean |

***

### `keyExtractor`[​](#keyextractor "Direct link to keyextractor")

React TSX

```
(item: any, index: number) => string;
```

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks `item.key`, then `item.id`, and then falls back to using the index, like React does.

| Type     |
| -------- |
| function |

***

### `maxToRenderPerBatch`[​](#maxtorenderperbatch "Direct link to maxtorenderperbatch")

The maximum number of items to render in each incremental render batch. The more rendered at once, the better the fill rate, but responsiveness may suffer because rendering content may interfere with responding to button taps or other interactions.

| Type   |
| ------ |
| number |

***

### `onEndReached`[​](#onendreached "Direct link to onendreached")

Called once when the scroll position gets within `onEndReachedThreshold` from the logical end of the list.

| Type                                        |
| ------------------------------------------- |
| `(info: {distanceFromEnd: number}) => void` |

***

### `onEndReachedThreshold`[​](#onendreachedthreshold "Direct link to onendreachedthreshold")

How far from the end (in units of visible length of the list) the trailing edge of the list must be from the end of the content to trigger the `onEndReached` callback. Thus, a value of 0.5 will trigger `onEndReached` when the end of the content is within half the visible length of the list.

| Type   | Default |
| ------ | ------- |
| number | `2`     |

***

### `onRefresh`[​](#onrefresh "Direct link to onrefresh")

React TSX

```
() => void;
```

If provided, a standard `RefreshControl` will be added for "Pull to Refresh" functionality. Make sure to also set the `refreshing` prop correctly.

| Type     |
| -------- |
| function |

***

### `onScrollToIndexFailed`[​](#onscrolltoindexfailed "Direct link to onscrolltoindexfailed")

React TSX

```
(info: {

  index: number,

  highestMeasuredFrameIndex: number,

  averageItemLength: number,

}) => void;
```

Used to handle failures when scrolling to an index that has not been measured yet. Recommended action is to either compute your own offset and `scrollTo` it, or scroll as far as possible and then try again after more items have been rendered.

| Type     |
| -------- |
| function |

***

### `onStartReached`[​](#onstartreached "Direct link to onstartreached")

Called once when the scroll position gets within `onStartReachedThreshold` from the logical start of the list.

| Type                                          |
| --------------------------------------------- |
| `(info: {distanceFromStart: number}) => void` |

***

### `onStartReachedThreshold`[​](#onstartreachedthreshold "Direct link to onstartreachedthreshold")

How far from the start (in units of visible length of the list) the leading edge of the list must be from the start of the content to trigger the `onStartReached` callback. Thus, a value of 0.5 will trigger `onStartReached` when the start of the content is within half the visible length of the list.

| Type   | Default |
| ------ | ------- |
| number | `2`     |

***

### `onViewableItemsChanged`[​](#onviewableitemschanged "Direct link to onviewableitemschanged")

Called when the viewability of rows changes, as defined by the `viewabilityConfig` prop.

| Type                                                                     |
| ------------------------------------------------------------------------ |
| `(callback: {changed: ViewToken[], viewableItems: ViewToken[]}) => void` |

***

### `persistentScrollbar`[​](#persistentscrollbar "Direct link to persistentscrollbar")

| Type |
| ---- |
| bool |

***

### `progressViewOffset`[​](#progressviewoffset "Direct link to progressviewoffset")

Set this when offset is needed for the loading indicator to show correctly.

| Type   |
| ------ |
| number |

***

### `refreshControl`[​](#refreshcontrol "Direct link to refreshcontrol")

A custom refresh control element. When set, it overrides the default `<RefreshControl>` component built internally. The onRefresh and refreshing props are also ignored. Only works for vertical VirtualizedList.

| Type    |
| ------- |
| element |

***

### `refreshing`[​](#refreshing "Direct link to refreshing")

Set this true while waiting for new data from a refresh.

| Type    |
| ------- |
| boolean |

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

warning

Using this property may lead to bugs (missing content) in some circumstances - use at your own risk.

When `true`, offscreen child views are removed from their native backing superview when offscreen. This may improve scroll performance for large lists. On Android the default value is `true`.

| Type    |
| ------- |
| boolean |

***

### `renderScrollComponent`[​](#renderscrollcomponent "Direct link to renderscrollcomponent")

React TSX

```
(props: object) => element;
```

Render a custom scroll component, e.g. with a differently styled `RefreshControl`.

| Type     |
| -------- |
| function |

***

### `viewabilityConfig`[​](#viewabilityconfig "Direct link to viewabilityconfig")

See `ViewabilityHelper.js` for flow type and further documentation.

| Type              |
| ----------------- |
| ViewabilityConfig |

***

### `viewabilityConfigCallbackPairs`[​](#viewabilityconfigcallbackpairs "Direct link to viewabilityconfigcallbackpairs")

List of `ViewabilityConfig`/`onViewableItemsChanged` pairs. A specific `onViewableItemsChanged` will be called when its corresponding `ViewabilityConfig`'s conditions are met. See `ViewabilityHelper.js` for flow type and further documentation.

| Type                                   |
| -------------------------------------- |
| array of ViewabilityConfigCallbackPair |

***

### `updateCellsBatchingPeriod`[​](#updatecellsbatchingperiod "Direct link to updatecellsbatchingperiod")

Amount of time between low-pri item render batches, e.g. for rendering items quite a ways off screen. Similar fill rate/responsiveness tradeoff as `maxToRenderPerBatch`.

| Type   |
| ------ |
| number |

***

### `windowSize`[​](#windowsize "Direct link to windowsize")

Determines the maximum number of items rendered outside of the visible area, in units of visible lengths. So if your list fills the screen, then `windowSize={21}` (the default) will render the visible screen area plus up to 10 screens above and 10 below the viewport. Reducing this number will reduce memory consumption and may improve performance, but will increase the chance that fast scrolling may reveal momentary blank areas of unrendered content.

| Type   |
| ------ |
| number |

## Methods[​](#methods "Direct link to Methods")

### `flashScrollIndicators()`[​](#flashscrollindicators "Direct link to flashscrollindicators")

React TSX

```
flashScrollIndicators();
```

***

### `getScrollableNode()`[​](#getscrollablenode "Direct link to getscrollablenode")

React TSX

```
getScrollableNode(): any;
```

***

### `getScrollRef()`[​](#getscrollref "Direct link to getscrollref")

React TSX

```
getScrollRef():

  | React.ElementRef<typeof ScrollView>

  | React.ElementRef<typeof View>

  | null;
```

***

### `getScrollResponder()`[​](#getscrollresponder "Direct link to getscrollresponder")

React TSX

```
getScrollResponder () => ScrollResponderMixin | null;
```

Provides a handle to the underlying scroll responder. Note that `this._scrollRef` might not be a `ScrollView`, so we need to check that it responds to `getScrollResponder` before calling it.

***

### `scrollToEnd()`[​](#scrolltoend "Direct link to scrolltoend")

React TSX

```
scrollToEnd(params?: {animated?: boolean});
```

Scrolls to the end of the content. May be janky without `getItemLayout` prop.

**Parameters:**

| Name   | Type   |
| ------ | ------ |
| params | object |

Valid `params` keys are:

* `'animated'` (boolean) - Whether the list should do an animation while scrolling. Defaults to `true`.

***

### `scrollToIndex()`[​](#scrolltoindex "Direct link to scrolltoindex")

React TSX

```
scrollToIndex(params: {

  index: number;

  animated?: boolean;

  viewOffset?: number;

  viewPosition?: number;

});
```

Valid `params` consist of:

* 'index' (number). Required.
* 'animated' (boolean). Optional.
* 'viewOffset' (number). Optional.
* 'viewPosition' (number). Optional.

***

### `scrollToItem()`[​](#scrolltoitem "Direct link to scrolltoitem")

React TSX

```
scrollToItem(params: {

  item: ItemT;

  animated?: boolean;

  viewOffset?: number;

  viewPosition?: number;

);
```

Valid `params` consist of:

* 'item' (Item). Required.
* 'animated' (boolean). Optional.
* 'viewOffset' (number). Optional.
* 'viewPosition' (number). Optional.

***

### `scrollToOffset()`[​](#scrolltooffset "Direct link to scrolltooffset")

React TSX

```
scrollToOffset(params: {

  offset: number;

  animated?: boolean;

});
```

    [**`getItem`**](#required-getitem)
  * [Required](#required-getitemcount)

    [**`getItemCount`**](#required-getitemcount)
  * [Required](#required-renderitem)

    [**`renderItem`**](#required-renderitem)

----
url: https://reactnative.dev/docs/next/security
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/security)** (0.87).

Version: Next

| **Do** use async storage when...              | **Don't** use async storage for... |
| --------------------------------------------- | ---------------------------------- |
| Persisting non-sensitive data across app runs | Token storage                      |
| Persisting Redux state                        | Secrets                            |
| Persisting GraphQL state                      |                                    |
| Storing global app-wide variables             |                                    |

----
url: https://reactnative.dev/docs/next/refreshcontrol
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/refreshcontrol)** (0.87).

Version: Next

This component is used inside a ScrollView or ListView to add pull to refresh functionality. When the ScrollView is at `scrollY: 0`, swiping down triggers an `onRefresh` event.

## Example[​](#example "Direct link to Example")

note

`refreshing` is a controlled prop, this is why it needs to be set to `true` in the `onRefresh` function otherwise the refresh indicator will stop immediately.

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### Require&#x64;**`refreshing`**[​](#requiredrefreshing "Direct link to requiredrefreshing")

Whether the view should be indicating an active refresh.

| Type    |
| ------- |
| boolean |

***

### `colors`Android[​](#colors-android "Direct link to colors-android")

The colors (at least one) that will be used to draw the refresh indicator.

| Type                                 |
| ------------------------------------ |
| array of [colors](/docs/next/colors) |

***

### `enabled`Android[​](#enabled-android "Direct link to enabled-android")

Whether the pull to refresh functionality is enabled.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

***

### `onRefresh`[​](#onrefresh "Direct link to onrefresh")

Called when the view starts refreshing.

| Type     |
| -------- |
| function |

***

### `progressBackgroundColor`Android[​](#progressbackgroundcolor-android "Direct link to progressbackgroundcolor-android")

The background color of the refresh indicator.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `progressViewOffset`[​](#progressviewoffset "Direct link to progressviewoffset")

Progress view top offset.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

***

### `size`Android[​](#size-android "Direct link to size-android")

Size of the refresh indicator.

| Type                         | Default     |
| ---------------------------- | ----------- |
| enum(`'default'`, `'large'`) | `'default'` |

***

### `tintColor`iOS[​](#tintcolor-ios "Direct link to tintcolor-ios")

The color of the refresh indicator.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `title`iOS[​](#title-ios "Direct link to title-ios")

The title displayed under the refresh indicator.

| Type   |
| ------ |
| string |

***

### `titleColor`iOS[​](#titlecolor-ios "Direct link to titlecolor-ios")

The color of the refresh indicator title.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

* [Example](#example)

* [Props](#props)

  * [View Props](#view-props)
  * [Required](#requiredrefreshing)

    [**`refreshing`**](#requiredrefreshing)
  * [`colors`](#colors-android)

    [Android](#colors-android)
  * [`enabled`](#enabled-android)

    [Android](#enabled-android)
  * [`onRefresh`](#onrefresh)
  * [`progressBackgroundColor`](#progressbackgroundcolor-android)

    [Android](#progressbackgroundcolor-android)
  * [`progressViewOffset`](#progressviewoffset)
  * [`size`](#size-android)

    [Android](#size-android)
  * [`tintColor`](#tintcolor-ios)

    [iOS](#tintcolor-ios)
  * [`title`](#title-ios)

    [iOS](#title-ios)
  * [`titleColor`](#titlecolor-ios)

    [iOS](#titlecolor-ios)

----
url: https://reactnative.dev/docs/debugging
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

[React Native DevTools](/docs/react-native-devtools) is our built-in debugger for React Native. It allows you to inspect and understand how your JavaScript code is running, similar to a web browser.

To open DevTools, either:

* Select "Open DevTools" in the Dev Menu.
* Press `j` from the CLI.

On first launch, DevTools will open to a welcome panel, along with an open console drawer where you can view logs and interact with the JavaScript runtime. From the top of the window, you can navigate to other panels, including the integrated React Components Inspector and Profiler.

Learn more in our [React Native DevTools guide](/docs/react-native-devtools).

```
import {LogBox} from 'react-native';
```

#### Ignore all logs[​](#ignore-all-logs "Direct link to Ignore all logs")

LogBox notifications can be disabled using `LogBox.ignoreAllLogs()`. This can be useful in situations such as giving product demos.

JavaScript

```
LogBox.ignoreAllLogs();
```

#### Ignore specific logs[​](#ignore-specific-logs "Direct link to Ignore specific logs")

Notifications can be disabled on a per-log basis via `LogBox.ignoreLogs()`. This can be useful for noisy warnings or those that cannot be fixed, e.g. in a third-party dependency.

JavaScript

```
LogBox.ignoreLogs([

  // Exact message

  'Warning: componentWillReceiveProps has been renamed',



  // Substring or regex match

  /GraphQL error: .*/,

]);
```

----
url: https://reactnative.dev/docs/next/global-AbortController
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-AbortController)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) for more information.

The global `AbortController` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/props)** (0.87).

Version: Next

Most components can be customized when they are created, with different parameters. These created parameters are called `props`, short for properties.

For example, one basic React Native component is the `Image`. When you create an image, you can use a prop named `source` to control what image it shows.

Notice the braces surrounding `{pic}` - these embed the variable `pic` into JSX. You can put any JavaScript expression inside braces in JSX.

Your own components can also use `props`. This lets you make a single component that is used in many different places in your app, with slightly different properties in each place by referring to `props` in your `render` function. Here's an example:

* TypeScript
* JavaScript

Using `name` as a prop lets us customize the `Greeting` component, so we can reuse that component for each of our greetings. This example also uses the `Greeting` component in JSX, similar to the [Core Components](/docs/next/intro-react-native-components). The power to do this is what makes React so cool - if you find yourself wishing that you had a different set of UI primitives to work with, you can invent new ones.

The other new thing going on here is the [`View`](/docs/next/view) component. A [`View`](/docs/next/view) is useful as a container for other components, to help control style and layout.

With `props` and the basic [`Text`](/docs/next/text), [`Image`](/docs/next/image), and [`View`](/docs/next/view) components, you can build a wide variety of static screens. To learn how to make your app change over time, you need to [learn about State](/docs/next/state).

----
url: https://reactnative.dev/docs/next/inputaccessoryview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/inputaccessoryview)** (0.87).

Version: Next

Deprecated

`InputAccessoryView` is deprecated and will be removed in a future release.

A component which enables customization of the keyboard input accessory view on iOS. The input accessory view is displayed above the keyboard whenever a `TextInput` has focus. This component can be used to create custom toolbars.

To use this component wrap your custom toolbar with the InputAccessoryView component, and set a `nativeID`. Then, pass that `nativeID` as the `inputAccessoryViewID` of whatever `TextInput` you desire. A basic example:

This component can also be used to create sticky text inputs (text inputs which are anchored to the top of the keyboard). To do this, wrap a `TextInput` with the `InputAccessoryView` component, and don't set a `nativeID`. For an example, look at [InputAccessoryViewExample.js](https://github.com/react/react-native/blob/main/packages/rn-tester/js/examples/InputAccessoryView/InputAccessoryViewExample.js).

***

# Reference

## Props[​](#props "Direct link to Props")

### `backgroundColor`[​](#backgroundcolor "Direct link to backgroundcolor")

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

An ID which is used to associate this `InputAccessoryView` to specified TextInput(s).

| Type   |
| ------ |
| string |

***

### `style`[​](#style "Direct link to style")

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

----
url: https://reactnative.dev/docs/next/keyboardavoidingview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/keyboardavoidingview)** (0.87).

Version: Next

This component will automatically adjust its height, position, or bottom padding based on the keyboard height to remain visible while the virtual keyboard is displayed.

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/next/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/next/view#props).

***

### `behavior`[​](#behavior "Direct link to behavior")

Specify how to react to the presence of the keyboard.

note

Android and iOS both interact with this prop differently. On both iOS and Android, setting `behavior` is recommended.

| Type                                        |
| ------------------------------------------- |
| enum(`'height'`, `'position'`, `'padding'`) |

***

### `contentContainerStyle`[​](#contentcontainerstyle "Direct link to contentcontainerstyle")

The style of the content container (View) when behavior is `'position'`.

| Type                                      |
| ----------------------------------------- |
| [View Style](/docs/next/view-style-props) |

***

### `enabled`[​](#enabled "Direct link to enabled")

Enabled or disabled KeyboardAvoidingView.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

***

### `keyboardVerticalOffset`[​](#keyboardverticaloffset "Direct link to keyboardverticaloffset")

This is the distance between the top of the user screen and the react native view, may be non-zero in some use cases.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

----
url: https://reactnative.dev/docs/next/global-Response
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-Response)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Response) for more information.

The global `Response` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/global-cancelIdleCallback
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-cancelIdleCallback)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelIdleCallback) for more information.

The global `cancelIdleCallback` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/global-Blob
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-Blob)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Blob) for more information.

The global `Blob` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/systrace
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/systrace)** (0.87).

Version: Next

`Systrace` is a standard Android marker-based profiling tool (and is installed when you install the Android platform-tools package). Profiled code blocks are surrounded by start/end markers which are then visualized in a colorful chart format. Both the Android SDK and React Native framework provide standard markers that you can visualize.

## Example[​](#example "Direct link to Example")

`Systrace` allows you to mark JavaScript (JS) events with a tag and an integer value. Start profiling with an Android profiling tool such as Perfetto or EasyProfiler, then use these markers to identify the events in the captured trace.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `isEnabled()`[​](#isenabled "Direct link to isenabled")

React TSX

```
static isEnabled(): boolean;
```

***

### `beginEvent()`[​](#beginevent "Direct link to beginevent")

React TSX

```
static beginEvent(eventName: string | (() => string), args?: EventArgs);
```

beginEvent/endEvent for starting and then ending a profile within the same call stack frame.

***

### `endEvent()`[​](#endevent "Direct link to endevent")

React TSX

```
static endEvent(args?: EventArgs);
```

***

### `beginAsyncEvent()`[​](#beginasyncevent "Direct link to beginasyncevent")

React TSX

```
static beginAsyncEvent(

  eventName: string | (() => string),

  args?: EventArgs,

): number;
```

beginAsyncEvent/endAsyncEvent for starting and then ending a profile where the end can either occur on another thread or out of the current stack frame, eg await the returned cookie variable should be used as input into the endAsyncEvent call to end the profile.

***

### `endAsyncEvent()`[​](#endasyncevent "Direct link to endasyncevent")

React TSX

```
static endAsyncEvent(

  eventName: EventName,

  cookie: number,

  args?: EventArgs,

);
```

***

### `counterEvent()`[​](#counterevent "Direct link to counterevent")

React TSX

```
static counterEvent(eventName: string | (() => string), value: number);
```

----
url: https://reactnative.dev/docs/element-nodes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Element nodes represent native components in the native view tree (similar to [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) nodes on Web).

They are provided by all native components, and by many built-in components, via refs:

info

Note that some built-in components are only a container for other components (including native components). For example, `ScrollView` internally renders a native scroll view and a native view, which are accessible through the ref it provides using methods like `getNativeScrollRef()` and `getInnerViewRef()`.

***

    * ⚠️ The `options` parameter is not supported.

    * ℹ️ Returns the value of the `id` or `nativeID` props.
    * ⚠️ For built-in components, only `ScrollView` instances can return a value other than zero.
  * [`scrollTop`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop)
    * ⚠️ For built-in components, only `ScrollView` instances can return a value other than zero.
  * [`scrollWidth`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth)
  * [`tagName`](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName)
    * ℹ️ Returns a normalized native component name prefixed with `RN:`, like `RN:View`.

    * ℹ️ Will return the [document node](/docs/next/document-nodes) where this component was rendered.

    * ℹ️ Will return a reference to itself if the component is not mounted.

----
url: https://reactnative.dev/docs/optimizing-javascript-loading
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Parsing and running JavaScript code requires memory and time. Because of this, as your app grows, it's often useful to delay loading code until it's needed for the first time. React Native comes with some standard optimizations that are on by default, and there are techniques you can adopt in your own code to help React load your app more efficiently. There are also some advanced automatic optimizations (with their own tradeoffs) that are suitable for very large apps.

## Recommended: Use Hermes[​](#recommended-use-hermes "Direct link to Recommended: Use Hermes")

Hermes is the default engine for new React Native apps, and is highly optimized for efficient code loading. In release builds, JavaScript code is fully compiled to bytecode ahead of time. Bytecode is loaded to memory on-demand and does not need to be parsed like plain JavaScript does.

info

Read more about using Hermes in React Native [here](/docs/hermes).

```
import Logger from './utils/Logger';



//  🚩 🚩 🚩 Side effect! This must be executed before React can even begin to

// render the SplashScreen component, and can unexpectedly break code elsewhere

// in your app if you later decide to lazy-load SplashScreen.

global.logger = new Logger();



export function SplashScreen() {

  // ...

}
```

## Advanced: Call `require` inline[​](#advanced-call-require-inline "Direct link to advanced-call-require-inline")

Sometimes you may want to defer loading some code until you use it for the first time, without using `lazy` or an asynchronous `import()`. You can do this by using the [`require()`](https://metrobundler.dev/docs/module-api/#require) function where you would otherwise use a static `import` at the top of the file.

VeryExpensive.tsx

```
import {Component} from 'react';

import {Text} from 'react-native';

// ... import some very expensive modules



export default function VeryExpensive() {

  // ... lots and lots of rendering logic

  return <Text>Very Expensive Component</Text>;

}
```

Optimized.tsx

```
import {useCallback, useState} from 'react';

import {TouchableOpacity, View, Text} from 'react-native';

// Usually we would write a static import:

// import VeryExpensive from './VeryExpensive';



let VeryExpensive = null;



export default function Optimize() {

  const [needsExpensive, setNeedsExpensive] = useState(false);

  const didPress = useCallback(() => {

    if (VeryExpensive == null) {

      VeryExpensive = require('./VeryExpensive').default;

    }



    setNeedsExpensive(true);

  }, []);



  return (

    <View style={{marginTop: 20}}>

      <TouchableOpacity onPress={didPress}>

        <Text>Load</Text>

      </TouchableOpacity>

      {needsExpensive ? <VeryExpensive /> : null}

    </View>

  );

}
```

## Advanced: Automatically inline `require` calls[​](#advanced-automatically-inline-require-calls "Direct link to 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.

React TSX

```
import {useCallback, useState} from 'react';

import {TouchableOpacity, View, Text} from 'react-native';



// This top-level require call will be evaluated lazily as part of the component below.

const VeryExpensive = require('./VeryExpensive').default;



export default function Optimize() {

  const [needsExpensive, setNeedsExpensive] = useState(false);

  const didPress = useCallback(() => {

    setNeedsExpensive(true);

  }, []);



  return (

    <View style={{marginTop: 20}}>

      <TouchableOpacity onPress={didPress}>

        <Text>Load</Text>

      </TouchableOpacity>

      {needsExpensive ? <VeryExpensive /> : null}

    </View>

  );

}
```

```
module.exports = {

  transformer: {

    async getTransformOptions() {

      return {

        transform: {

          inlineRequires: false,

        },

      };

    },

  },

};
```

To only **exclude certain modules from `require` inlining:**

There are two relevant transformer options: `inlineRequires.blockList` and `nonInlinedRequires`. See the code snippet for examples of how to use each one.

metro.config.js

```
module.exports = {

  transformer: {

    async getTransformOptions() {

      return {

        transform: {

          inlineRequires: {

            blockList: {

              // require() calls in `DoNotInlineHere.js` will not be inlined.

              [require.resolve('./src/DoNotInlineHere.js')]: true,



              // require() calls anywhere else will be inlined, unless they

              // match any entry nonInlinedRequires (see below).

            },

          },

          nonInlinedRequires: [

            // require('react') calls will not be inlined anywhere

            'react',

          ],

        },

      };

    },

  },

};
```

```
project.ext.react = [

  bundleCommand: "ram-bundle",

]
```

Use the following lines on Android if you want to use a single indexed file:

```
project.ext.react = [

  bundleCommand: "ram-bundle",

  extraPackagerArgs: ["--indexed-ram-bundle"]

]
```

On iOS, RAM bundles are always indexed ( = single file).

Enable the RAM format in Xcode by editing the build phase "Bundle React Native code and images". Before `../node_modules/react-native/scripts/react-native-xcode.sh` add `export BUNDLE_COMMAND="ram-bundle"`:

```
export BUNDLE_COMMAND="ram-bundle"

export NODE_BINARY=node

../node_modules/react-native/scripts/react-native-xcode.sh
```

----
url: https://reactnative.dev/docs/style
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

With React Native, you style your application using JavaScript. All of the core components accept a prop named `style`. The style names and [values](/docs/colors) usually match how CSS works on the web, except names are written using camel casing, e.g. `backgroundColor` rather than `background-color`.

The `style` prop can be a plain old JavaScript object. That's what we usually use for example code. You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles.

As a component grows in complexity, it is often cleaner to use `StyleSheet.create` to define several styles in one place. Here's an example:

One common pattern is to make your component accept a `style` prop which in turn is used to style subcomponents. You can use this to make styles "cascade" the way they do in CSS.

There are a lot more ways to customize the text style. Check out the [Text component reference](/docs/text) for a complete list.

Now you can make your text beautiful. The next step in becoming a style expert is to [learn how to control component size](/docs/height-and-width).

## Known issues[​](#known-issues "Direct link to Known issues")

* [react-native#29308](https://github.com/react/react-native/issues/29308#issuecomment-792864162): In some cases React Native does not match how CSS works on the web, for example the touch area never extends past the parent view bounds and on Android negative margin is not supported.

- [Known issues](#known-issues)

----
url: https://reactnative.dev/docs/next/appendix
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/appendix)** (0.87).

Version: Next

| Flow                                     | TypeScript                      | Flow Nullable Support      | TypeScript Nullable Support     | Android (Java)                       | iOS (ObjC)                                                     |
| ---------------------------------------- | ------------------------------- | -------------------------- | ------------------------------- | ------------------------------------ | -------------------------------------------------------------- |
| `string`                                 | `string`                        | `?string`                  | `string \| null`                | `string`                             | `NSString`                                                     |
| `boolean`                                | `boolean`                       | `?boolean`                 | `boolean \| null`               | `Boolean`                            | `NSNumber`                                                     |
| Object Literal `{\| foo: string, ...\|}` | `{ foo: string, ...} as const`  | `?{\| foo: string, ...\|}` | `?{ foo: string, ...} as const` | -                                    | -                                                              |
| Object \[[1](#notes)]                    | Object \[[1](#notes)]           | `?Object`                  | `Object \| null`                | `ReadableMap`                        | `@` (untyped dictionary)                                       |
| `Array<T>`                               | `Array<T>`                      | `?Array<T>`                | `Array<T> \| null`              | `ReadableArray`                      | `NSArray` (or `RCTConvertVecToArray` when used inside objects) |
| `Function`                               | `Function`                      | `?Function`                | `Function \| null`              | -                                    | -                                                              |
| `Promise<T>`                             | `Promise<T>`                    | `?Promise<T>`              | `Promise<T> \| null`            | `com.facebook.react.bridge.Promise`  | `RCTPromiseResolve` and `RCTPromiseRejectBlock`                |
| Type Unions `'SUCCESS'\|'FAIL'`          | Type Unions `'SUCCESS'\|'FAIL'` | Only as callbacks          |                                 | -                                    | -                                                              |
| Callbacks `() =>`                        | Callbacks `() =>`               | Yes                        |                                 | `com.facebook.react.bridge.Callback` | `RCTResponseSenderBlock`                                       |
| `number`                                 | `number`                        | No                         |                                 | `double`                             | `NSNumber`                                                     |

----
url: https://reactnative.dev/docs/next/element-nodes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/element-nodes)** (0.87).

Version: Next

Element nodes represent native components in the native view tree (similar to [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) nodes on Web).

They are provided by all native components, and by many built-in components, via refs:

info

Note that some built-in components are only a container for other components (including native components). For example, `ScrollView` internally renders a native scroll view and a native view, which are accessible through the ref it provides using methods like `getNativeScrollRef()` and `getInnerViewRef()`.

***

    * ⚠️ The `options` parameter is not supported.

    * ℹ️ Returns the value of the `id` or `nativeID` props.
    * ⚠️ For built-in components, only `ScrollView` instances can return a value other than zero.
  * [`scrollTop`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop)
    * ⚠️ For built-in components, only `ScrollView` instances can return a value other than zero.
  * [`scrollWidth`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth)
  * [`tagName`](https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName)
    * ℹ️ Returns a normalized native component name prefixed with `RN:`, like `RN:View`.

    * ℹ️ Will return the [document node](/docs/next/document-nodes) where this component was rendered.

    * ℹ️ Will return a reference to itself if the component is not mounted.

----
url: https://reactnative.dev/docs/next/set-up-your-environment
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/set-up-your-environment)** (0.87).

Version: Next

In this guide, you'll learn how to set up your environment, so that you can run your project with Android Studio and Xcode. This will allow you to develop with Android emulators and iOS simulators, build your app locally, and more.

info

This guide requires Android Studio or Xcode. If you already have one of these programs installed, you should be able to get up and running within a few minutes. If they are not installed, you should expect to spend about an hour installing and configuring them.

Is setting up my environment required?

Setting up your environment is not required if you're using a [Framework](/architecture/glossary#react-native-framework). With a React Native Framework, you don't need to set up Android Studio or Xcode as it will take care of building the native app for you

If you have constraints that prevent you from using a Framework, or you'd like to write your own Framework, then setting up your local environment is a requirement. After your environment is set up, learn how to [get started without a framework](/docs/next/getting-started-without-a-framework).

```
brew install node

brew install watchman
```

If you have already installed Node on your system, make sure it is Node 22.11.0 or newer.

[Watchman](https://facebook.github.io/watchman) is a tool by Facebook for watching changes in the filesystem. It is highly recommended you install it for better performance.

### Java Development Kit

We recommend installing the OpenJDK distribution called Azul **Zulu** using [Homebrew](https://brew.sh/). Run the following commands in a Terminal after installing Homebrew:

```
brew install --cask zulu@17



# Get path to where cask was installed to find the JDK installer

brew info --cask zulu@17



# ==> zulu@17: <version number>

# https://www.azul.com/downloads/

# Installed

# /opt/homebrew/Caskroom/zulu@17/<version number> (185.8MB) (note that the path is /usr/local/Caskroom on non-Apple Silicon Macs)

# Installed using the formulae.brew.sh API on 2024-06-06 at 10:00:00



# Navigate to the folder

open /opt/homebrew/Caskroom/zulu@17/<version number> # or /usr/local/Caskroom/zulu@17/<version number>
```

After opening Finder, double click the `Double-Click to Install Azul Zulu JDK 17.pkg` package to install the JDK.

After the JDK installation, add or update your `JAVA_HOME` environment variable in `~/.zshrc` (or in `~/.bash_profile`).

If you used above steps, JDK will likely be located at `/Library/Java/JavaVirtualMachines/zulu-17.jdk/Contents/Home`:

```
export JAVA_HOME=/Library/Java/JavaVirtualMachines/zulu-17.jdk/Contents/Home
```

```
export ANDROID_HOME=$HOME/Library/Android/sdk

export PATH=$PATH:$ANDROID_HOME/emulator

export PATH=$PATH:$ANDROID_HOME/platform-tools
```

If you have a physical Android device, you can use it for development in place of an AVD by plugging it in to your computer using a USB cable and following the instructions [here](/docs/next/running-on-device).

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/next/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/next/getting-started).

## Installing dependencies[​](#installing-dependencies "Direct link to Installing dependencies")

You will need Node, Watchman, the React Native command line interface, Xcode and CocoaPods.

While you can use any editor of your choice to develop your app, you will need to install Xcode in order to set up the necessary tooling to build your React Native app for iOS.

### Node & Watchman[​](#node--watchman "Direct link to Node & Watchman")

We recommend installing Node and Watchman using [Homebrew](https://brew.sh/). Run the following commands in a Terminal after installing Homebrew:

```
brew install node

brew install watchman
```

```
export NVM_DIR="$HOME/.nvm"

[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
```

You might also want to ensure that all "shell script build phase" of your Xcode project, is using `/bin/zsh` as its shell.

### That's it!

Congratulations! You successfully set up your development environment.

## Now what?

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/next/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/next/getting-started).

```
choco install -y nodejs-lts microsoft-openjdk17
```

```
%LOCALAPPDATA%\Android\Sdk
```

```
%LOCALAPPDATA%\Android\Sdk\platform-tools
```

## Preparing the Android device

You will need an Android device to run your React Native Android app. This can be either a physical Android device, or more commonly, you can use an Android Virtual Device which allows you to emulate an Android device on your computer.

Either way, you will need to prepare the device to run Android apps for development.

### Using a physical device

If you have a physical Android device, you can use it for development in place of an AVD by plugging it in to your computer using a USB cable and following the instructions [here](/docs/next/running-on-device).

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/next/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/next/getting-started).

## Unsupported[​](#unsupported "Direct link to Unsupported")

info

A Mac is required to build projects with native code for iOS. You can use [Expo Go](https://expo.dev/go) from [Expo](/docs/next/environment-setup#start-a-new-react-native-project-with-expo) to develop your app on your iOS device.

```
export ANDROID_HOME=$HOME/Android/Sdk

export PATH=$PATH:$ANDROID_HOME/emulator

export PATH=$PATH:$ANDROID_HOME/platform-tools
```

If you have a physical Android device, you can use it for development in place of an AVD by plugging it in to your computer using a USB cable and following the instructions [here](/docs/next/running-on-device).

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/next/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/next/getting-started).

## Unsupported[​](#unsupported-1 "Direct link to Unsupported")

info

A Mac is required to build projects with native code for iOS. You can use [Expo Go](https://expo.dev/go) from [Expo](/docs/next/environment-setup#start-a-new-react-native-project-with-expo) to develop your app on your iOS device.

----
url: https://reactnative.dev/docs/next/signed-apk-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/signed-apk-android)** (0.87).

Version: Next

```
keytool -genkeypair -v -storetype PKCS12 -keystore my-upload-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
```

This command prompts you for passwords for the keystore and key and for the Distinguished Name fields for your key. It then generates the keystore as a file called `my-upload-key.keystore`.

The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later when signing your app, so remember to take note of the alias.

### macOS[​](#macos "Direct link to macOS")

On macOS, if you're not sure where your JDK bin folder is, then perform the following command to find it:

```
/usr/libexec/java_home
```

It will output the directory of the JDK, which will look something like this:

```
/Library/Java/JavaVirtualMachines/jdkX.X.X_XXX.jdk/Contents/Home
```

Navigate to that directory by using the command `cd /your/jdk/path` and use the keytool command with sudo permission as shown below.

```
sudo keytool -genkey -v -keystore my-upload-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
```

caution

Remember to keep the keystore file private. In case you've lost upload key or it's been compromised you should [follow these instructions](https://support.google.com/googleplay/android-developer/answer/7384423#reset).

## Setting up Gradle variables[​](#setting-up-gradle-variables "Direct link to Setting up Gradle variables")

1. Place the `my-upload-key.keystore` file under the `android/app` directory in your project folder.
2. Edit the file `~/.gradle/gradle.properties` or `android/gradle.properties`, and add the following (replace `*****` with the correct keystore password, alias and key password),

```
MYAPP_UPLOAD_STORE_FILE=my-upload-key.keystore

MYAPP_UPLOAD_KEY_ALIAS=my-key-alias

MYAPP_UPLOAD_STORE_PASSWORD=*****

MYAPP_UPLOAD_KEY_PASSWORD=*****
```

```
...

android {

    ...

    defaultConfig { ... }

    signingConfigs {

        release {

            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {

                storeFile file(MYAPP_UPLOAD_STORE_FILE)

                storePassword MYAPP_UPLOAD_STORE_PASSWORD

                keyAlias MYAPP_UPLOAD_KEY_ALIAS

                keyPassword MYAPP_UPLOAD_KEY_PASSWORD

            }

        }

    }

    buildTypes {

        release {

            ...

            signingConfig signingConfigs.release

        }

    }

}

...
```

## Generating the release AAB[​](#generating-the-release-aab "Direct link to Generating the release AAB")

Run the following command in a terminal:

```
npx react-native build-android --mode=release
```

```
npm run android -- --mode="release"
```

```
yarn android --mode release
```

Note that `--mode release` is only available if you've set up signing as described above.

You can terminate any running bundler instances, since all your framework and JavaScript code is bundled in the APK's assets.

## Publishing to other stores[​](#publishing-to-other-stores "Direct link to Publishing to other stores")

By default, the generated APK has the native code for both `x86`, `x86_64`, `ARMv7a` and `ARM64-v8a` CPU architectures. This makes it easier to share APKs that run on almost all Android devices. However, this has the downside that there will be some unused native code on any device, leading to unnecessarily bigger APKs.

You can create an APK for each CPU by adding the following line in your `android/app/build.gradle` file:

Diff

```
android {



    splits {

        abi {

            reset()

            enable true

            universalApk false

            include "armeabi-v7a", "arm64-v8a", "x86", "x86_64"

        }

    }



}
```

```
/**

 * Run Proguard to shrink the Java bytecode in release builds.

 */

def enableProguardInReleaseBuilds = true
```

----
url: https://reactnative.dev/docs/global-URLSearchParams
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) for more information.\\

The global `URLSearchParams` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-AbortSignal
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) for more information.

The global `AbortSignal` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/share
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
static share(content: ShareContent, options?: ShareOptions);
```

Open a dialog to share text content.

In iOS, returns a Promise which will be invoked with an object containing `action` and `activityType`. If the user dismissed the dialog, the Promise will still be resolved with action being `Share.dismissedAction` and all the other keys being undefined. Note that some share options will not appear or work on the iOS simulator.

In Android, returns a Promise which will always be resolved with action being `Share.sharedAction`.

**Properties:**

| Name            | Type   | Description                                                                                                                                                                                    |
| --------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| contentRequired | object | `message` - a message to share `url` - a URL to shareiOS `title` - title of the messageAndroid***At least one of `url` and `message` is required.                                              |
| options         | object | `dialogTitle`Android `excludedActivityTypes`iOS `subject` - a subject to share via emailiOS `tintColor`iOS `anchor` - the node to which the action sheet should be anchored (used for iPad)iOS |

***

## Properties[​](#properties "Direct link to Properties")

### `sharedAction`[​](#sharedaction "Direct link to sharedaction")

React TSX

```
static sharedAction: 'sharedAction';
```

The content was successfully shared.

***

### `dismissedAction`iOS[​](#dismissedaction-ios "Direct link to dismissedaction-ios")

React TSX

```
static dismissedAction: 'dismissedAction';
```

    [iOS](#dismissedaction-ios)

----
url: https://reactnative.dev/docs/next/imagepickerios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/imagepickerios)** (0.87).

Version: Next

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=image+picker) instead.

----
url: https://reactnative.dev/docs/react-native-devtools
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

* Use the [`PerformanceObserver` API](/docs/global-PerformanceObserver) in your app to observe performance events at runtime — useful if you want to capture performance telemetry.

    [Since 0.83](#network-since-083)
  * [Performance](#performance-since-083)

    [Since 0.83](#performance-since-083)
  * [Memory](#memory)

- [React DevTools features](#react-devtools-features)

  * [React Components](#react-components)
  * [React Profiler](#react-profiler)

- [Reconnecting DevTools](#reconnecting-devtools)

----
url: https://reactnative.dev/docs/devsettings
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The `DevSettings` module exposes methods for customizing settings for developers in development.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `addMenuItem()`[​](#addmenuitem "Direct link to addmenuitem")

React TSX

```
static addMenuItem(title: string, handler: () => any);
```

Add a custom menu item to the Dev Menu.

**Parameters:**

| Name            | Type     |
| --------------- | -------- |
| titleRequired   | string   |
| handlerRequired | function |

**Example:**

React TSX

```
DevSettings.addMenuItem('Show Secret Dev Screen', () => {

  Alert.alert('Showing secret dev screen!');

});
```

***

### `reload()`[​](#reload "Direct link to reload")

React TSX

```
static reload(reason?: string): void;
```

Reload the application. Can be invoked directly or on user interaction.

**Example:**

React TSX

```
<Button title="Reload" onPress={() => DevSettings.reload()} />
```

* [Methods](#methods)

  * [`addMenuItem()`](#addmenuitem)
  * [`reload()`](#reload)

----
url: https://reactnative.dev/docs/pressable
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Pressable is a Core Component wrapper that can detect various stages of press interactions on any of its defined children.

React TSX

```
<Pressable onPress={onPressFunction}>

  <Text>I'm pressable!</Text>

</Pressable>
```

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

### `android_ripple`Android[​](#android_ripple-android "Direct link to android_ripple-android")

Enables the Android ripple effect and configures its properties. The `color` field accepts both plain colors and [`PlatformColor`](/docs/platformcolor) values, so you can reference theme attributes like `?attr/colorAccent`. When a `PlatformColor` is used, the ripple is automatically updated when the system configuration changes (for example, when switching between light and dark mode).

| Type                                         |
| -------------------------------------------- |
| [RippleConfig](/docs/pressable#rippleconfig) |

### `children`[​](#children "Direct link to children")

Either children or a function that receives a boolean reflecting whether the component is currently pressed.

| Type                           |
| ------------------------------ |
| [React Node](/docs/react-node) |

### `unstable_pressDelay`[​](#unstable_pressdelay "Direct link to unstable_pressdelay")

Duration (in milliseconds) to wait after press down before calling `onPressIn`.

| Type   |
| ------ |
| number |

### `delayLongPress`[​](#delaylongpress "Direct link to delaylongpress")

Duration (in milliseconds) from `onPressIn` before `onLongPress` is called.

| Type   | Default |
| ------ | ------- |
| number | `500`   |

### `disabled`[​](#disabled "Direct link to disabled")

Whether the press behavior is disabled.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

### `hitSlop`[​](#hitslop "Direct link to hitslop")

Sets additional distance outside of element in which a press can be detected.

| Type                         |
| ---------------------------- |
| [Rect](/docs/rect) or number |

### `onHoverIn`[​](#onhoverin "Direct link to onhoverin")

Called when the hover is activated to provide visual feedback.

| Type                                    |
| --------------------------------------- |
| `({ nativeEvent: MouseEvent }) => void` |

### `onHoverOut`[​](#onhoverout "Direct link to onhoverout")

Called when the hover is deactivated to undo visual feedback.

| Type                                    |
| --------------------------------------- |
| `({ nativeEvent: MouseEvent }) => void` |

### `onLongPress`[​](#onlongpress "Direct link to onlongpress")

Called if the time after `onPressIn` lasts longer than 500 milliseconds. This time period can be customized with [`delayLongPress`](#delaylongpress).

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `onPress`[​](#onpress "Direct link to onpress")

Called after `onPressOut`.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `onPressIn`[​](#onpressin "Direct link to onpressin")

Called immediately when a touch is engaged, before `onPressOut` and `onPress`.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `onPressMove`[​](#onpressmove "Direct link to onpressmove")

Called when the press location moves.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `onPressOut`[​](#onpressout "Direct link to onpressout")

Called when a touch is released.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

### `pressRetentionOffset`[​](#pressretentionoffset "Direct link to pressretentionoffset")

Additional distance outside of this view in which a touch is considered a press before `onPressOut` is triggered.

| Type                         | Default                                      |
| ---------------------------- | -------------------------------------------- |
| [Rect](/docs/rect) or number | `{bottom: 30, left: 20, right: 20, top: 20}` |

### `style`[​](#style "Direct link to style")

Either view styles or a function that receives a boolean reflecting whether the component is currently pressed and returns view styles.

| Type                                                                           |
| ------------------------------------------------------------------------------ |
| [View Style](/docs/view-style-props) or `({ pressed: boolean }) => View Style` |

### `testOnly_pressed`[​](#testonly_pressed "Direct link to testonly_pressed")

Used only for documentation or testing (e.g. snapshot testing).

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### RippleConfig[​](#rippleconfig "Direct link to RippleConfig")

Ripple effect configuration for the `android_ripple` property.

| Type   |
| ------ |
| object |

**Properties:**

| Name       | Type                                                          | Required | Description                                                                                                                                                                                                                                                  |
| ---------- | ------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| color      | [color](/docs/colors) or [PlatformColor](/docs/platformcolor) | No       | Defines the color of the ripple effect.                                                                                                                                                                                                                      |
| borderless | boolean                                                       | No       | Defines if ripple effect should not include border.                                                                                                                                                                                                          |
| radius     | number                                                        | No       | Defines the radius of the ripple effect.                                                                                                                                                                                                                     |
| foreground | boolean                                                       | No       | Set to true to add the ripple effect to the foreground of the view, instead of the background. This is useful if one of your child views has a background of its own, or you're e.g. displaying images, and you don't want the ripple to be covered by them. |
| alpha      | number                                                        | No       | Controls the opacity of the ripple. Accepts a value between `0.0` (fully transparent) and `1.0` (fully opaque). The value is applied on top of any alpha already present in the color.                                                                       |

* [How it works](#how-it-works)

* [Example](#example)

* [Props](#props)

  * [`android_disableSound`](#android_disablesound-android)

    [Android](#android_disablesound-android)
  * [`android_ripple`](#android_ripple-android)

    [Android](#android_ripple-android)

----
url: https://reactnative.dev/docs/next/statusbarios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/statusbarios)** (0.87).

Version: Next

Removed from React Native

Use [`StatusBar`](/docs/next/statusbar) for mutating the status bar.

***

----
url: https://reactnative.dev/docs/next/animatedvalue
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/animatedvalue)** (0.87).

Version: Next

Standard value for driving animations. One `Animated.Value` can drive multiple properties in a synchronized fashion, but can only be driven by one mechanism at a time. Using a new mechanism (e.g. starting a new animation, or calling `setValue`) will stop any previous ones.

Typically initialized with `useAnimatedValue(0);` or `new Animated.Value(0);` in class components.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `setValue()`[​](#setvalue "Direct link to setvalue")

React TSX

```
setValue(value: number);
```

Directly set the value. This will stop any animations running on the value and update all the bound properties.

**Parameters:**

| Name  | Type   | Required | Description |
| ----- | ------ | -------- | ----------- |
| value | number | Yes      | Value       |

***

### `setOffset()`[​](#setoffset "Direct link to setoffset")

React TSX

```
setOffset(offset: number);
```

Sets an offset that is applied on top of whatever value is set, whether via `setValue`, an animation, or `Animated.event`. Useful for compensating things like the start of a pan gesture.

**Parameters:**

| Name   | Type   | Required | Description  |
| ------ | ------ | -------- | ------------ |
| offset | number | Yes      | Offset value |

***

### `flattenOffset()`[​](#flattenoffset "Direct link to flattenoffset")

React TSX

```
flattenOffset();
```

Merges the offset value into the base value and resets the offset to zero. The final output of the value is unchanged.

***

### `extractOffset()`[​](#extractoffset "Direct link to extractoffset")

React TSX

```
extractOffset();
```

Sets the offset value to the base value, and resets the base value to zero. The final output of the value is unchanged.

***

### `addListener()`[​](#addlistener "Direct link to addlistener")

React TSX

```
addListener(callback: (state: {value: number}) => void): string;
```

Adds an asynchronous listener to the value so you can observe updates from animations. This is useful because there is no way to synchronously read the value because it might be driven natively.

Returns a string that serves as an identifier for the listener.

**Parameters:**

| Name     | Type     | Required | Description                                                                                 |
| -------- | -------- | -------- | ------------------------------------------------------------------------------------------- |
| callback | function | Yes      | The callback function which will receive an object with a `value` key set to the new value. |

***

### `removeListener()`[​](#removelistener "Direct link to removelistener")

React TSX

```
removeListener(id: string);
```

Unregister a listener. The `id` param shall match the identifier previously returned by `addListener()`.

**Parameters:**

| Name | Type   | Required | Description                        |
| ---- | ------ | -------- | ---------------------------------- |
| id   | string | Yes      | Id for the listener being removed. |

***

### `removeAllListeners()`[​](#removealllisteners "Direct link to removealllisteners")

React TSX

```
removeAllListeners();
```

Remove all registered listeners.

***

### `stopAnimation()`[​](#stopanimation "Direct link to stopanimation")

React TSX

```
stopAnimation(callback?: (value: number) => void);
```

Stops any running animation or tracking. `callback` is invoked with the final value after stopping the animation, which is useful for updating state to match the animation position with layout.

**Parameters:**

| Name     | Type     | Required | Description                                   |
| -------- | -------- | -------- | --------------------------------------------- |
| callback | function | No       | A function that will receive the final value. |

***

### `resetAnimation()`[​](#resetanimation "Direct link to resetanimation")

React TSX

```
resetAnimation(callback?: (value: number) => void);
```

Stops any animation and resets the value to its original.

**Parameters:**

| Name     | Type     | Required | Description                                      |
| -------- | -------- | -------- | ------------------------------------------------ |
| callback | function | No       | A function that will receive the original value. |

***

### `interpolate()`[​](#interpolate "Direct link to interpolate")

React TSX

```
interpolate(config: InterpolationConfigType);
```

Interpolates the value before updating the property, e.g. mapping 0-1 to 0-10.

See `AnimatedInterpolation.js`

**Parameters:**

| Name   | Type   | Required | Description |
| ------ | ------ | -------- | ----------- |
| config | object | Yes      | See below.  |

***

### `animate()`[​](#animate "Direct link to animate")

React TSX

```
animate(animation, callback);
```

Typically only used internally, but could be used by a custom Animation class.

**Parameters:**

| Name      | Type      | Required | Description         |
| --------- | --------- | -------- | ------------------- |
| animation | Animation | Yes      | See `Animation.js`. |
| callback  | function  | Yes      | Callback function.  |

----
url: https://reactnative.dev/docs/platform-specific-code
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

When building a cross-platform app, you'll want to re-use as much code as possible. Scenarios may arise where it makes sense for the code to be different, for example you may want to implement separate visual components for Android and iOS.

React Native provides two ways to organize your code and separate it by platform:

* Using the [`Platform` module](/docs/platform-specific-code#platform-module).
* Using [platform-specific file extensions](/docs/platform-specific-code#platform-specific-extensions).

Certain components may have properties that work on one platform only. All of these props are annotated with `@platform` and have a small badge next to them on the website.

## Platform module[​](#platform-module "Direct link to Platform module")

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.

React TSX

```
import {Platform, StyleSheet} from 'react-native';



const styles = StyleSheet.create({

  height: Platform.OS === 'ios' ? 200 : 100,

});
```

`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.

React TSX

```
import {Platform, StyleSheet} from 'react-native';



const styles = StyleSheet.create({

  container: {

    flex: 1,

    ...Platform.select({

      ios: {

        backgroundColor: 'red',

      },

      android: {

        backgroundColor: 'green',

      },

      default: {

        // other platforms, web for example

        backgroundColor: 'blue',

      },

    }),

  },

});
```

This will result in a container having `flex: 1` on all platforms, a red background color on iOS, a green background color on Android, and a blue background color on other platforms.

Since it accepts `any` value, you can also use it to return platform-specific components, like below:

React TSX

```
const Component = Platform.select({

  ios: () => require('ComponentIOS'),

  android: () => require('ComponentAndroid'),

})();



<Component />;
```

React TSX

```
const Component = Platform.select({

  native: () => require('ComponentForNative'),

  default: () => require('ComponentForWeb'),

})();



<Component />;
```

### Detecting the Android versionAndroid[​](#detecting-the-android-version-android "Direct link to detecting-the-android-version-android")

On Android, the `Platform` module can also be used to detect the version of the Android Platform in which the app is running:

React TSX

```
import {Platform} from 'react-native';



if (Platform.Version === 25) {

  console.log('Running on Nougat!');

}
```

**Note**: `Version` is set to the Android API version not the Android OS version. To find a mapping please refer to [Android Version History](https://en.wikipedia.org/wiki/Android_version_history#Overview).

### Detecting the iOS versioniOS[​](#detecting-the-ios-version-ios "Direct link to detecting-the-ios-version-ios")

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:

React TSX

```
import {Platform} from 'react-native';



const majorVersionIOS = parseInt(Platform.Version, 10);

if (majorVersionIOS <= 9) {

  console.log('Work around a change in behavior');

}
```

## Platform-specific extensions[​](#platform-specific-extensions "Direct link to Platform-specific extensions")

When your platform-specific code is more complex, you should consider splitting the code out into separate files. React Native will detect when a file has a `.ios.` or `.android.` extension and load the relevant platform file when required from other components.

For example, say you have the following files in your project:

```
BigButton.ios.js

BigButton.android.js
```

You can then import the component as follows:

React TSX

```
import BigButton from './BigButton';
```

React Native will automatically pick up the right file based on the running platform.

## Native-specific extensions (i.e. sharing code with NodeJS and Web)[​](#native-specific-extensions-ie-sharing-code-with-nodejs-and-web "Direct link to Native-specific extensions (i.e. sharing code with NodeJS and Web)")

You can also use the `.native.js` extension when a module needs to be shared between NodeJS/Web and React Native but it has no Android/iOS differences. This is especially useful for projects that have common code shared among React Native and ReactJS.

For example, say you have the following files in your project:

```
Container.js # picked up by webpack, Rollup or any other Web bundler

Container.native.js # picked up by the React Native bundler for both Android and iOS (Metro)
```

You can still import it without the `.native` extension, as follows:

React TSX

```
import Container from './Container';
```

**Pro tip:** Configure your Web bundler to ignore `.native.js` extensions in order to avoid having unused code in your production bundle, thus reducing the final bundle size.

* [Platform module](#platform-module)

  * [Detecting the Android version](#detecting-the-android-version-android)

    [Android](#detecting-the-android-version-android)
  * [Detecting the iOS version](#detecting-the-ios-version-ios)

    [iOS](#detecting-the-ios-version-ios)

* [Platform-specific extensions](#platform-specific-extensions)

* [Native-specific extensions (i.e. sharing code with NodeJS and Web)](#native-specific-extensions-ie-sharing-code-with-nodejs-and-web)

----
url: https://reactnative.dev/docs/next/global-__DEV__
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-__DEV__)** (0.87).

Version: Next

You can use the `__DEV__` pseudo-global variable in the codebase to guard development-only blocks of code.

It is inlined during compilation and gets completely stripped out with the `if` blocks it guards in the minified build.

----
url: https://reactnative.dev/docs/next/button
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/button)** (0.87).

Version: Next

A basic button component that should render nicely on any platform. Supports a minimal level of customization.

If this button doesn't look right for your app, you can build your own button using [Pressable](/docs/next/pressable). For inspiration, look at the [source code for the Button component](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Components/Button.js).

React TSX

```
<Button

  onPress={onPressLearnMore}

  title="Learn More"

  color="#841584"

  accessibilityLabel="Learn more about this purple button"

/>
```

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### Require&#x64;**`onPress`**[​](#requiredonpress "Direct link to requiredonpress")

Handler to be called when the user taps the button.

| Type                          |
| ----------------------------- |
| `({nativeEvent: PressEvent})` |

***

### Require&#x64;**`title`**[​](#requiredtitle "Direct link to requiredtitle")

Text to display inside the button. On Android the given title will be converted to the uppercased form.

| Type   |
| ------ |
| string |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

Text to display for blindness accessibility features.

| Type   |
| ------ |
| string |

***

### `accessibilityLanguage`iOS[​](#accessibilitylanguage-ios "Direct link to accessibilitylanguage-ios")

A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the [BCP 47 specification](https://www.rfc-editor.org/info/bcp47).

See the [iOS `accessibilityLanguage` doc](https://developer.apple.com/documentation/objectivec/nsobject/1615192-accessibilitylanguage) for more information.

| Type   |
| ------ |
| string |

***

### `accessibilityActions`[​](#accessibilityactions "Direct link to accessibilityactions")

Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The `accessibilityActions` property should contain a list of action objects. Each action object should contain the field name and label.

See the [Accessibility guide](/docs/next/accessibility#accessibility-actions) for more information.

| Type  | Required |
| ----- | -------- |
| array | No       |

***

### `onAccessibilityAction`[​](#onaccessibilityaction "Direct link to onaccessibilityaction")

Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

See the [Accessibility guide](/docs/next/accessibility#accessibility-actions) for more information.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `color`[​](#color "Direct link to color")

Color of the text (iOS), or background color of the button (Android).

| Type                       | Default                             |
| -------------------------- | ----------------------------------- |
| [color](/docs/next/colors) | `'#2196F3'`Android***`'#007AFF'`iOS |

***

### `disabled`[​](#disabled "Direct link to disabled")

If `true`, disable all interactions for this component.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `hasTVPreferredFocus`TV[​](#hastvpreferredfocus-tv "Direct link to hastvpreferredfocus-tv")

TV preferred focus.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `nextFocusDown`AndroidTV[​](#nextfocusdown-androidtv "Direct link to nextfocusdown-androidtv")

Designates the next view to receive focus when the user navigates down. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusDown).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`AndroidTV[​](#nextfocusforward-androidtv "Direct link to nextfocusforward-androidtv")

Designates the next view to receive focus when the user navigates forward. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusForward).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`AndroidTV[​](#nextfocusleft-androidtv "Direct link to nextfocusleft-androidtv")

Designates the next view to receive focus when the user navigates left. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusLeft).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`AndroidTV[​](#nextfocusright-androidtv "Direct link to nextfocusright-androidtv")

Designates the next view to receive focus when the user navigates right. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusRight).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`AndroidTV[​](#nextfocusup-androidtv "Direct link to nextfocusup-androidtv")

Designates the next view to receive focus when the user navigates up. See the [Android documentation](https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusUp).

| Type   |
| ------ |
| number |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

| Type   |
| ------ |
| string |

***

### `touchSoundDisabled`Android[​](#touchsounddisabled-android "Direct link to touchsounddisabled-android")

If `true`, doesn't play system sound on touch.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

* [Example](#example)

* [Props](#props)

  * [Required](#requiredonpress)

    [**`onPress`**](#requiredonpress)
  * [Required](#requiredtitle)

    [**`title`**](#requiredtitle)
  * [`accessibilityLabel`](#accessibilitylabel)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)
  * [`accessibilityActions`](#accessibilityactions)
  * [`onAccessibilityAction`](#onaccessibilityaction)
  * [`color`](#color)
  * [`disabled`](#disabled)
  * [`hasTVPreferredFocus`](#hastvpreferredfocus-tv)

    [TV](#hastvpreferredfocus-tv)
  * [`nextFocusDown`](#nextfocusdown-androidtv)

    [Android](#nextfocusdown-androidtv)

    [TV](#nextfocusdown-androidtv)
  * [`nextFocusForward`](#nextfocusforward-androidtv)

    [Android](#nextfocusforward-androidtv)

    [TV](#nextfocusforward-androidtv)
  * [`nextFocusLeft`](#nextfocusleft-androidtv)

    [Android](#nextfocusleft-androidtv)

    [TV](#nextfocusleft-androidtv)
  * [`nextFocusRight`](#nextfocusright-androidtv)

    [Android](#nextfocusright-androidtv)

    [TV](#nextfocusright-androidtv)
  * [`nextFocusUp`](#nextfocusup-androidtv)

    [Android](#nextfocusup-androidtv)

    [TV](#nextfocusup-androidtv)
  * [`testID`](#testid)
  * [`touchSoundDisabled`](#touchsounddisabled-android)

    [Android](#touchsounddisabled-android)

----
url: https://reactnative.dev/docs/next/pushnotificationios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/pushnotificationios)** (0.87).

Version: Next

Deprecated

Use one of the [community packages](https://reactnative.directory/?search=notification) instead.

### Projects with Native Code Only

The following section only applies to projects with native code exposed. If you are using the managed Expo workflow, see the guide on [Notifications](https://docs.expo.dev/versions/latest/sdk/notifications/) in the Expo documentation for the appropriate alternative.

Handle notifications for your app, including scheduling and permissions.

***

## Getting Started[​](#getting-started "Direct link to Getting Started")

To enable push notifications, [configure your notifications with Apple](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server) and your server-side system.

Then, [enable remote notifications](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app#2980038) in your project. This will automatically enable the required settings.

Push notification registration and delivery callbacks belong to `UIApplicationDelegate`, so implement them in your `AppDelegate` even when React Native is bootstrapped from `SceneDelegate`.

### Enable support for `register` events[​](#enable-support-for-register-events "Direct link to enable-support-for-register-events")

In your `AppDelegate.m`, add:

Objective-C

```
#import <React/RCTPushNotificationManager.h>
```

Then implement the following in order to handle remote notification registration events:

Objective-C

```
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

{

 // This will trigger 'register' events on PushNotificationIOS

 [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error

{

 // This will trigger 'registrationError' events on PushNotificationIOS

 [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];

}
```

### Handle notifications[​](#handle-notifications "Direct link to Handle notifications")

You'll need to implement `UNUserNotificationCenterDelegate` in your `AppDelegate`:

Objective-C

```
#import <UserNotifications/UserNotifications.h>



@interface YourAppDelegate () <UNUserNotificationCenterDelegate>

@end
```

Set the delegate on app launch:

Objective-C

```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

  ...

  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

  center.delegate = self;



  return YES;

}
```

#### Foreground notifications[​](#foreground-notifications "Direct link to Foreground notifications")

Implement `userNotificationCenter:willPresentNotification:withCompletionHandler:` to handle notifications that arrive when the app is in the foreground. Use the completionHandler to determine if the notification will be shown to the user and notify `RCTPushNotificationManager` accordingly:

Objective-C

```
// Called when a notification is delivered to a foreground app.

- (void)userNotificationCenter:(UNUserNotificationCenter *)center

       willPresentNotification:(UNNotification *)notification

         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler

{

  // This will trigger 'notification' and 'localNotification' events on PushNotificationIOS

  [RCTPushNotificationManager didReceiveNotification:notification];

  // Decide if and how the notification will be shown to the user

  completionHandler(UNNotificationPresentationOptionNone);

}
```

#### Background notifications[​](#background-notifications "Direct link to Background notifications")

Implement `userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:` to handle when a notification is tapped, typically called for background notifications which the user taps to open the app. However, if you had set foreground notifications to be shown in `userNotificationCenter:willPresentNotification:withCompletionHandler:`, this method will also be invoked on foreground notifications when tapped. In this case, you should only notify `RCTPushNotificationManager` in one of these callbacks.

If the tapped notification resulted in app launch, call `setInitialNotification:`. If the notification was not previously handled by `userNotificationCenter:willPresentNotification:withCompletionHandler:`, call `didReceiveNotification:` as well:

Objective-C

```
- (void)  userNotificationCenter:(UNUserNotificationCenter *)center

  didReceiveNotificationResponse:(UNNotificationResponse *)response

           withCompletionHandler:(void (^)(void))completionHandler

{

  // This condition passes if the notification was tapped to launch the app

  if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {

    // Allow the notification to be retrieved on the JS side using getInitialNotification()

    [RCTPushNotificationManager setInitialNotification:response.notification];

  }

  // This will trigger 'notification' and 'localNotification' events on PushNotificationIOS

  [RCTPushNotificationManager didReceiveNotification:response.notification];

  completionHandler();

}
```

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `presentLocalNotification()`[​](#presentlocalnotification "Direct link to presentlocalnotification")

React TSX

```
static presentLocalNotification(details: PresentLocalNotificationDetails);
```

Schedules a local notification for immediate presentation.

**Parameters:**

| Name    | Type   | Required | Description |
| ------- | ------ | -------- | ----------- |
| details | object | Yes      | See below.  |

***

### `scheduleLocalNotification()`[​](#schedulelocalnotification "Direct link to schedulelocalnotification")

React TSX

```
static scheduleLocalNotification(details: ScheduleLocalNotificationDetails);
```

Schedules a local notification for future presentation.

**Parameters:**

| Name    | Type   | Required | Description |
| ------- | ------ | -------- | ----------- |
| details | object | Yes      | See below.  |

***

### `cancelAllLocalNotifications()`[​](#cancelalllocalnotifications "Direct link to cancelalllocalnotifications")

React TSX

```
static cancelAllLocalNotifications();
```

Cancels all scheduled local notifications.

***

### `removeAllDeliveredNotifications()`[​](#removealldeliverednotifications "Direct link to removealldeliverednotifications")

React TSX

```
static removeAllDeliveredNotifications();
```

Removes all delivered notifications from Notification Center.

***

### `getDeliveredNotifications()`[​](#getdeliverednotifications "Direct link to getdeliverednotifications")

React TSX

```
static getDeliveredNotifications(callback: (notifications: Object[]) => void);
```

Provides a list of the app’s notifications that are currently displayed in Notification Center.

**Parameters:**

| Name     | Type     | Required | Description                                                  |
| -------- | -------- | -------- | ------------------------------------------------------------ |
| callback | function | Yes      | Function which receives an array of delivered notifications. |

***

### `removeDeliveredNotifications()`[​](#removedeliverednotifications "Direct link to removedeliverednotifications")

React TSX

```
static removeDeliveredNotifications(identifiers: string[]);
```

Removes the specified notifications from Notification Center.

**Parameters:**

| Name        | Type  | Required | Description                        |
| ----------- | ----- | -------- | ---------------------------------- |
| identifiers | array | Yes      | Array of notification identifiers. |

***

### `setApplicationIconBadgeNumber()`[​](#setapplicationiconbadgenumber "Direct link to setapplicationiconbadgenumber")

React TSX

```
static setApplicationIconBadgeNumber(num: number);
```

Sets the badge number for the app icon on the Home Screen.

**Parameters:**

| Name   | Type   | Required | Description                    |
| ------ | ------ | -------- | ------------------------------ |
| number | number | Yes      | Badge number for the app icon. |

***

### `getApplicationIconBadgeNumber()`[​](#getapplicationiconbadgenumber "Direct link to getapplicationiconbadgenumber")

React TSX

```
static getApplicationIconBadgeNumber(callback: (num: number) => void);
```

Gets the current badge number for the app icon on the Home Screen.

**Parameters:**

| Name     | Type     | Required | Description                                        |
| -------- | -------- | -------- | -------------------------------------------------- |
| callback | function | Yes      | Function which processes the current badge number. |

***

### `cancelLocalNotifications()`[​](#cancellocalnotifications "Direct link to cancellocalnotifications")

React TSX

```
static cancelLocalNotifications(userInfo: Object);
```

Cancels any scheduled local notifications which match the fields in the provided `userInfo`.

**Parameters:**

| Name     | Type   | Required | Description |
| -------- | ------ | -------- | ----------- |
| userInfo | object | No       |             |

***

### `getScheduledLocalNotifications()`[​](#getscheduledlocalnotifications "Direct link to getscheduledlocalnotifications")

React TSX

```
static getScheduledLocalNotifications(

  callback: (notifications: ScheduleLocalNotificationDetails[]) => void,

);
```

Gets the list of local notifications that are currently scheduled.

**Parameters:**

| Name     | Type     | Required | Description                                                                  |
| -------- | -------- | -------- | ---------------------------------------------------------------------------- |
| callback | function | Yes      | Function which processes an array of objects describing local notifications. |

***

### `addEventListener()`[​](#addeventlistener "Direct link to addeventlistener")

React TSX

```
static addEventListener(

  type: PushNotificationEventName,

  handler:

    | ((notification: PushNotification) => void)

    | ((deviceToken: string) => void)

    | ((error: {message: string; code: number; details: any}) => void),

);
```

Attaches a listener to notification events including local notifications, remote notifications, and notification registration results.

**Parameters:**

| Name    | Type     | Required | Description                         |
| ------- | -------- | -------- | ----------------------------------- |
| type    | string   | Yes      | Event type to listen to. See below. |
| handler | function | Yes      | Listener.                           |

Valid events types include:

* `notification` : Fired when a remote notification is received. The handler will be invoked with an instance of `PushNotificationIOS`. This will handle notifications that arrive in the foreground or were tapped to open the app from the background.
* `localNotification` : Fired when a local notification is received. The handler will be invoked with an instance of `PushNotificationIOS`. This will handle notifications that arrive in the foreground or were tapped to open the app from the background.
* `register`: Fired when the user registers successfully for remote notifications. The handler will be invoked with a hex string representing the deviceToken.
* `registrationError`: Fired when the user fails to register for remote notifications. Typically occurs due to APNS issues or if the device is a simulator. The handler will be invoked with `{message: string, code: number, details: any}`.

***

### `removeEventListener()`[​](#removeeventlistener "Direct link to removeeventlistener")

React TSX

```
static removeEventListener(

  type: PushNotificationEventName,

);
```

Removes the event listener. Do this in `componentWillUnmount` to prevent memory leaks.

**Parameters:**

| Name | Type   | Required | Description                                       |
| ---- | ------ | -------- | ------------------------------------------------- |
| type | string | Yes      | Event type. See `addEventListener()` for options. |

***

### `requestPermissions()`[​](#requestpermissions "Direct link to requestpermissions")

React TSX

```
static requestPermissions(permissions?: PushNotificationPermissions[]);
```

| Name        | Type  | Required | Description            |
| ----------- | ----- | -------- | ---------------------- |
| permissions | array | No       | alert, badge, or sound |

***

### `abandonPermissions()`[​](#abandonpermissions "Direct link to abandonpermissions")

React TSX

```
static abandonPermissions();
```

Unregister for all remote notifications received via Apple Push Notification service.

You should call this method in rare circumstances only, such as when a new version of the app removes support for all types of remote notifications. Users can temporarily prevent apps from receiving remote notifications through the Settings app. Apps unregistered through this method can always re-register.

***

### `checkPermissions()`[​](#checkpermissions "Direct link to checkpermissions")

React TSX

```
static checkPermissions(

  callback: (permissions: PushNotificationPermissions) => void,

);
```

Check which push permissions are currently enabled.

**Parameters:**

| Name     | Type     | Required | Description |
| -------- | -------- | -------- | ----------- |
| callback | function | Yes      | See below.  |

`callback` will be invoked with a `permissions` object:

* `alert: boolean`
* `badge: boolean`
* `sound: boolean`

***

### `getInitialNotification()`[​](#getinitialnotification "Direct link to getinitialnotification")

React TSX

```
static getInitialNotification(): Promise<PushNotification | null>;
```

This method returns a promise. If the app was launched by a push notification, this promise resolves to an object of type `PushNotificationIOS` for the notification that was tapped. Otherwise, it resolves to `null`.

***

### `getAuthorizationStatus()`[​](#getauthorizationstatus "Direct link to getauthorizationstatus")

React TSX

```
static getAuthorizationStatus(): Promise<number>;
```

This method returns a promise that resolves to the current notification authorization status. See [UNAuthorizationStatus](https://developer.apple.com/documentation/usernotifications/unauthorizationstatus?language=objc) for possible values.

***

### `finish()`[​](#finish "Direct link to finish")

React TSX

```
finish(result: string);
```

This method is available for remote notifications that have been received via [`application:didReceiveRemoteNotification:fetchCompletionHandler:`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application?language=objc). However, this is superseded by `UNUserNotificationCenterDelegate` and will no longer be invoked if both `application:didReceiveRemoteNotification:fetchCompletionHandler:` and the newer handlers from `UNUserNotificationCenterDelegate` are implemented.

If for some reason you're still relying on `application:didReceiveRemoteNotification:fetchCompletionHandler:`, you'll need to set up event handling on the iOS side:

Objective-C

```
- (void)           application:(UIApplication *)application

  didReceiveRemoteNotification:(NSDictionary *)userInfo

        fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler

{

  [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:handler];

}
```

Call `finish()` to execute the native completion handlers once you're done handling the notification on the JS side. When calling this block, pass in the fetch result value that best describes the results of your operation. For a list of possible values, see `PushNotificationIOS.FetchResult`.

If you're using `application:didReceiveRemoteNotification:fetchCompletionHandler:`, you *must* call this handler and should do so as soon as possible. See the [official documentation](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application?language=objc) for more details.

***

### `getMessage()`[​](#getmessage "Direct link to getmessage")

React TSX

```
getMessage(): string | Object;
```

An alias for `getAlert` to get the notification's main message string.

***

### `getSound()`[​](#getsound "Direct link to getsound")

React TSX

```
getSound(): string;
```

Gets the sound string from the `aps` object. This will be `null` for local notifications.

***

### `getCategory()`[​](#getcategory "Direct link to getcategory")

React TSX

```
getCategory(): string;
```

Gets the category string from the `aps` object.

***

### `getAlert()`[​](#getalert "Direct link to getalert")

React TSX

```
getAlert(): string | Object;
```

Gets the notification's main message from the `aps` object. Also see the alias: `getMessage()`.

***

### `getContentAvailable()`[​](#getcontentavailable "Direct link to getcontentavailable")

React TSX

```
getContentAvailable(): number;
```

Gets the content-available number from the `aps` object.

***

### `getBadgeCount()`[​](#getbadgecount "Direct link to getbadgecount")

React TSX

```
getBadgeCount(): number;
```

Gets the badge count number from the `aps` object.

***

### `getData()`[​](#getdata "Direct link to getdata")

React TSX

```
getData(): Object;
```

Gets the data object on the notification.

***

### `getThreadID()`[​](#getthreadid "Direct link to getthreadid")

React TSX

```
getThreadID();
```

----
url: https://reactnative.dev/docs/boxshadowvalue
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The `BoxShadowValue` object is taken by the [`boxShadow`](/docs/view-style-props#boxshadow) style prop. It is comprised of 2-4 lengths, an optional color, and an optional `inset` boolean. These values collectively define the box shadow's color, position, size, and blurriness.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

  offsetX: 10,

  offsetY: -3,

  blurRadius: '15px',

  spreadDistance: '10px',

  color: 'red',

  inset: true,

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `offsetX`[​](#offsetx "Direct link to offsetx")

The offset on the x-axis. This can be positive or negative. A positive value indicates right and negative indicates left.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | No       |

### `offsetY`[​](#offsety "Direct link to offsety")

The offset on the y-axis. This can be positive or negative. A positive value indicates up and negative indicates down.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | No       |

### `blurRadius`[​](#blurradius "Direct link to blurradius")

Represents the radius used in the [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) algorithm. The larger the value the blurrier the shadow is. Only non-negative values are valid. The default is 0.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | Yes      |

### `spreadDistance`[​](#spreaddistance "Direct link to spreaddistance")

How much larger or smaller the shadow grows or shrinks. A positive value will grow the shadow, a negative value will shrink the shadow.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | Yes      |

### `color`[​](#color "Direct link to color")

The color of the shadow. The default is `black`.

| Type                  | Optional |
| --------------------- | -------- |
| [color](/docs/colors) | Yes      |

### `inset`[​](#inset "Direct link to inset")

Whether the shadow is inset or not. Inset shadows will appear around the inside of the element's border box as opposed to the outside.

| Type    | Optional |
| ------- | -------- |
| boolean | Yes      |

## Used by[​](#used-by "Direct link to Used by")

* [`boxShadow`](/docs/view-style-props#boxshadow)

----
url: https://reactnative.dev/docs/next/global-navigator
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-navigator)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator) for more information.

The global `navigator` object, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/libraries
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/libraries)** (0.87).

Version: Next

React Native provides a set of built-in [Core Components and APIs](/docs/next/components-and-apis) ready to use in your app. You're not limited to the components and APIs bundled with React Native. React Native has a community of thousands of developers. If the Core Components and APIs don't have what you are looking for, you may be able to find and install a library from the community to add the functionality to your app.

```
npm install react-native-webview
```

```
yarn add react-native-webview
```

The library that we installed includes native code, and we need to link to our app before we use it.

## Linking Native Code on iOS[​](#linking-native-code-on-ios "Direct link to Linking Native Code on iOS")

React Native uses CocoaPods to manage iOS project dependencies and most React Native libraries follow this same convention. If a library you are using does not, then please refer to their README for additional instruction. In most cases, the following instructions will apply.

Run `pod install` in our `ios` directory in order to link it to our native iOS project. A shortcut for doing this without switching to the `ios` directory is to run `npx pod-install`.

```
npx pod-install
```

Once this is complete, re-build the app binary to start using your new library:

* npm
* Yarn

```
npm run ios
```

```
yarn ios
```

## Linking Native Code on Android[​](#linking-native-code-on-android "Direct link to Linking Native Code on Android")

React Native uses Gradle to manage Android project dependencies. After you install a library with native dependencies, you will need to re-build the app binary to use your new library:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

----
url: https://reactnative.dev/docs/flatlist
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

If you need section support, use [`<SectionList>`](/docs/sectionlist).

## Example[​](#example "Direct link to Example")

* TypeScript
* JavaScript

To render multiple columns, use the [`numColumns`](/docs/flatlist#numcolumns) prop. Using this approach instead of a `flexWrap` layout can prevent conflicts with the item height logic.

More complex, selectable example below.

* Passing `extraData={selectedId}` to `FlatList` ensures that `FlatList` re-renders when `selectedId` changes. Because `FlatList` implements `PureComponent`, it only re-renders if its props change. While `renderItem` in this example is recreated on each render because it is defined inline, passing `extraData` is essential whenever `renderItem` has a stable reference (such as when memoized or defined outside the component) so that `FlatList` knows that an external dependency has updated.
* `keyExtractor` tells the list to use the `id`s for the react keys instead of the default `key` property.

- TypeScript
- JavaScript

This is a convenience wrapper around [`<VirtualizedList>`](/docs/virtualizedlist), and thus inherits its props (as well as those of [`<ScrollView>`](/docs/scrollview)) that aren't explicitly listed here, along with the following caveats:

* Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
* This is a `PureComponent` which means that it will not re-render if `props` remain shallow-equal. Make sure that everything your `renderItem` function depends on is passed as a prop (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on changes. This includes the `data` prop and parent component state.
* In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
* By default, the list looks for a `key` prop on each item and uses that for the React key. Alternatively, you can provide a custom `keyExtractor` prop.

***

# Reference

## Props[​](#props "Direct link to Props")

### [VirtualizedList Props](/docs/virtualizedlist#props)[​](#virtualizedlist-props "Direct link to virtualizedlist-props")

Inherits [VirtualizedList Props](/docs/virtualizedlist#props).

***

### Require&#x64;**`renderItem`**[​](#required-renderitem "Direct link to required-renderitem")

React TSX

```
renderItem({

  item: ItemT,

  index: number,

  separators: {

    highlight: () => void;

    unhighlight: () => void;

    updateProps: (select: 'leading' | 'trailing', newProps: any) => void;

  }

}): JSX.Element;
```

Takes an item from `data` and renders it into the list.

Provides additional metadata like `index` if you need it, as well as a more generic `separators.updateProps` function which let you set whatever props you want to change the rendering of either the leading separator or trailing separator in case the more common `highlight` and `unhighlight` (which set the `highlighted: boolean` prop) are insufficient for your use case.

| Type     |
| -------- |
| function |

* `item` (Object): The item from `data` being rendered.

* `index` (number): The index corresponding to this item in the `data` array.

* `separators` (Object)

  * `highlight` (Function)

  * `unhighlight` (Function)

  * `updateProps` (Function)

    * `select` (enum('leading', 'trailing'))
    * `newProps` (Object)

Example usage:

React TSX

```
<FlatList

  ItemSeparatorComponent={

    Platform.OS !== 'android' &&

    (({highlighted}) => (

      <View

        style={[style.separator, highlighted && {marginLeft: 0}]}

      />

    ))

  }

  data={[{title: 'Title Text', key: 'item1'}]}

  renderItem={({item, index, separators}) => (

    <TouchableHighlight

      key={item.key}

      onPress={() => this._onPress(item)}

      onShowUnderlay={separators.highlight}

      onHideUnderlay={separators.unhighlight}>

      <View style={{backgroundColor: 'white'}}>

        <Text>{item.title}</Text>

      </View>

    </TouchableHighlight>

  )}

/>
```

***

### Require&#x64;**`data`**[​](#required-data "Direct link to required-data")

An array (or array-like list) of items to render. Other data types can be used by targeting [`VirtualizedList`](/docs/virtualizedlist) directly.

| Type      |
| --------- |
| ArrayLike |

***

### `ItemSeparatorComponent`[​](#itemseparatorcomponent "Direct link to itemseparatorcomponent")

Rendered in between each item, but not at the top or bottom. By default, `highlighted` and `leadingItem` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` which will update the `highlighted` prop, but you can also add custom props with `separators.updateProps`. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type                         |
| ---------------------------- |
| component, function, element |

***

### `ListEmptyComponent`[​](#listemptycomponent "Direct link to listemptycomponent")

Rendered when the list is empty. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListFooterComponent`[​](#listfootercomponent "Direct link to listfootercomponent")

Rendered at the bottom of all the items. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListFooterComponentStyle`[​](#listfootercomponentstyle "Direct link to listfootercomponentstyle")

Styling for internal View for `ListFooterComponent`.

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

***

### `ListHeaderComponent`[​](#listheadercomponent "Direct link to listheadercomponent")

Rendered at the top of all the items. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListHeaderComponentStyle`[​](#listheadercomponentstyle "Direct link to listheadercomponentstyle")

Styling for internal View for `ListHeaderComponent`.

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

***

### `columnWrapperStyle`[​](#columnwrapperstyle "Direct link to columnwrapperstyle")

Optional custom style for multi-item rows generated when `numColumns > 1`.

| Type                                 |
| ------------------------------------ |
| [View Style](/docs/view-style-props) |

***

### `extraData`[​](#extradata "Direct link to extradata")

A marker property for telling the list to re-render (since it implements `PureComponent`). If any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the `data` prop, stick it here and treat it immutably.

| Type |
| ---- |
| any  |

***

### `getItemLayout`[​](#getitemlayout "Direct link to getitemlayout")

React 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:

React TSX

```
  getItemLayout={(data, index) => (

    {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}

  )}
```

Adding `getItemLayout` can be a great performance boost for lists of several hundred items. Remember to include separator length (height or width) in your offset calculation if you specify `ItemSeparatorComponent`.

| Type     |
| -------- |
| function |

***

### `horizontal`[​](#horizontal "Direct link to horizontal")

If `true`, renders items next to each other horizontally instead of stacked vertically.

| Type    |
| ------- |
| boolean |

***

### `initialNumToRender`[​](#initialnumtorender "Direct link to initialnumtorender")

How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.

| Type   | Default |
| ------ | ------- |
| number | `10`    |

***

### `initialScrollIndex`[​](#initialscrollindex "Direct link to initialscrollindex")

Instead of starting at the top with the first item, start at `initialScrollIndex`. This disables the "scroll to top" optimization that keeps the first `initialNumToRender` items always rendered and immediately renders the items starting at this initial index. Requires `getItemLayout` to be implemented.

| Type   |
| ------ |
| number |

***

### `inverted`[​](#inverted "Direct link to inverted")

Reverses the direction of scroll. Uses scale transforms of `-1`.

| Type    |
| ------- |
| boolean |

***

### `keyExtractor`[​](#keyextractor "Direct link to keyextractor")

React TSX

```
(item: ItemT, index: number) => string;
```

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks `item.key`, then `item.id`, and then falls back to using the index, like React does.

| Type     |
| -------- |
| function |

***

### `numColumns`[​](#numcolumns "Direct link to numcolumns")

Multiple columns can only be rendered with `horizontal={false}` and will zig-zag like a `flexWrap` layout. Items should all be the same height - masonry layouts are not supported.

| Type   |
| ------ |
| number |

***

### `onRefresh`[​](#onrefresh "Direct link to onrefresh")

React TSX

```
() => void;
```

If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the `refreshing` prop correctly.

| Type     |
| -------- |
| function |

***

### `onViewableItemsChanged`[​](#onviewableitemschanged "Direct link to onviewableitemschanged")

Called when the viewability of rows changes, as defined by the `viewabilityConfig` prop.

| Type                                                                     |
| ------------------------------------------------------------------------ |
| `(callback: {changed: ViewToken[], viewableItems: ViewToken[]} => void;` |

***

### `progressViewOffset`[​](#progressviewoffset "Direct link to progressviewoffset")

Set this when offset is needed for the loading indicator to show correctly.

| Type   |
| ------ |
| number |

***

### `refreshing`[​](#refreshing "Direct link to refreshing")

Set this true while waiting for new data from a refresh.

| Type    |
| ------- |
| boolean |

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

warning

Using this property may lead to bugs (missing content) in some circumstances - use at your own risk.

When `true`, offscreen child views are removed from their native backing superview when offscreen. This may improve scroll performance for large lists. On Android the default value is `true`.

| Type    |
| ------- |
| boolean |

***

### `viewabilityConfig`[​](#viewabilityconfig "Direct link to viewabilityconfig")

See [`ViewabilityHelper.js`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Lists/ViewabilityHelper.js) for flow type and further documentation.

| Type              |
| ----------------- |
| ViewabilityConfig |

`viewabilityConfig` takes a type `ViewabilityConfig` an object with following properties

| Property                         | Type    |
| -------------------------------- | ------- |
| minimumViewTime                  | number  |
| viewAreaCoveragePercentThreshold | number  |
| itemVisiblePercentThreshold      | number  |
| waitForInteraction               | boolean |

At least one of the `viewAreaCoveragePercentThreshold` or `itemVisiblePercentThreshold` is required. This needs to be done in the `constructor` to avoid following error ([ref](https://github.com/react/react-native/issues/17408)):

```
  Error: Changing viewabilityConfig on the fly is not supported
```

React TSX

```
constructor (props) {

  super(props)



  this.viewabilityConfig = {

      waitForInteraction: true,

      viewAreaCoveragePercentThreshold: 95

  }

}
```

React TSX

```
<FlatList

    viewabilityConfig={this.viewabilityConfig}

  ...
```

***

### `viewabilityConfigCallbackPairs`[​](#viewabilityconfigcallbackpairs "Direct link to viewabilityconfigcallbackpairs")

List of `ViewabilityConfig`/`onViewableItemsChanged` pairs. A specific `onViewableItemsChanged` will be called when its corresponding `ViewabilityConfig`'s conditions are met. See `ViewabilityHelper.js` for flow type and further documentation.

| Type                                   |
| -------------------------------------- |
| array of ViewabilityConfigCallbackPair |

## Methods[​](#methods "Direct link to Methods")

### `flashScrollIndicators()`[​](#flashscrollindicators "Direct link to flashscrollindicators")

React TSX

```
flashScrollIndicators();
```

Displays the scroll indicators momentarily.

***

### `getNativeScrollRef()`[​](#getnativescrollref "Direct link to getnativescrollref")

React TSX

```
getNativeScrollRef(): React.ElementRef<typeof ScrollViewComponent>;
```

Provides a reference to the underlying scroll component

***

### `getScrollResponder()`[​](#getscrollresponder "Direct link to getscrollresponder")

React TSX

```
getScrollResponder(): ScrollResponderMixin;
```

Provides a handle to the underlying scroll responder.

***

### `getScrollableNode()`[​](#getscrollablenode "Direct link to getscrollablenode")

React TSX

```
getScrollableNode(): any;
```

Provides a handle to the underlying scroll node.

### `scrollToEnd()`[​](#scrolltoend "Direct link to scrolltoend")

React TSX

```
scrollToEnd(params?: {animated?: boolean});
```

Scrolls to the end of the content. May be janky without `getItemLayout` prop.

**Parameters:**

| Name   | Type   |
| ------ | ------ |
| params | object |

Valid `params` keys are:

* 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to `true`.

***

### `scrollToIndex()`[​](#scrolltoindex "Direct link to scrolltoindex")

React TSX

```
scrollToIndex: (params: {

  index: number;

  animated?: boolean;

  viewOffset?: number;

  viewPosition?: number;

});
```

Scrolls to the item at the specified index such that it is positioned in the viewable area such that `viewPosition` 0 places it at the top, 1 at the bottom, and 0.5 centered in the middle.

note

Cannot scroll to locations outside the render window without specifying the `getItemLayout` prop.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| paramsRequired | object |

Valid `params` keys are:

* 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to `true`.
* 'index' (number) - The index to scroll to. Required.
* 'viewOffset' (number) - A fixed number of pixels to offset the final target position.
* 'viewPosition' (number) - A value of `0` places the item specified by index at the top, `1` at the bottom, and `0.5` centered in the middle.

***

### `scrollToItem()`[​](#scrolltoitem "Direct link to scrolltoitem")

React TSX

```
scrollToItem(params: {

  animated?: ?boolean,

  item: Item,

  viewPosition?: number,

});
```

Requires linear scan through data - use `scrollToIndex` instead if possible.

note

Cannot scroll to locations outside the render window without specifying the `getItemLayout` prop.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| paramsRequired | object |

Valid `params` keys are:

* 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to `true`.
* 'item' (object) - The item to scroll to. Required.
* 'viewPosition' (number)

***

### `scrollToOffset()`[​](#scrolltooffset "Direct link to scrolltooffset")

React TSX

```
scrollToOffset(params: {

  offset: number;

  animated?: boolean;

});
```

Scroll to a specific content pixel offset in the list.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| paramsRequired | object |

    [**`renderItem`**](#required-renderitem)
  * [Required](#required-data)

    [**`data`**](#required-data)
  * [`ItemSeparatorComponent`](#itemseparatorcomponent)
  * [`ListEmptyComponent`](#listemptycomponent)
  * [`ListFooterComponent`](#listfootercomponent)
  * [`ListFooterComponentStyle`](#listfootercomponentstyle)
  * [`ListHeaderComponent`](#listheadercomponent)
  * [`ListHeaderComponentStyle`](#listheadercomponentstyle)

----
url: https://reactnative.dev/docs/next/global-console
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-console)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/console) for more information.

The global `console` object, as defined in Web specifications.

***

## Methods[​](#methods "Direct link to Methods")

### `timeStamp()`[​](#timestamp "Direct link to timestamp")

React TSX

```
console.timeStamp(

  label: string,

  start?: string | number,

  end?: string | number,

  trackName?: string,

  trackGroup?: string,

  color?: DevToolsColor

): void;
```

The `console.timeStamp` API allows you to add custom timing entries in the Performance panel timeline.

**Parameters:**

| Name       | Type               | Required | Description                                                                                                                                                                                                                                                                       |
| ---------- | ------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| label      | `string`           | Yes      | The label for the timing entry.                                                                                                                                                                                                                                                   |
| start      | `string \| number` | No       | * If string, the name of a previously recorded timestamp with `console.timeStamp`.
* If number, the [DOMHighResTimeStamp](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp). For example, from `performance.now()`.
* If undefined, the current time is used. |
| end        | `string \| number` | No       | - If string, the name of a previously recorded timestamp with `console.timeStamp`.
- If number, the [DOMHighResTimeStamp](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp). For example, from `performance.now()`.
- If undefined, the current time is used. |
| trackName  | `string`           | No       | The name of the custom track.                                                                                                                                                                                                                                                     |
| trackGroup | `string`           | No       | The name of the track group.                                                                                                                                                                                                                                                      |
| color      | `DevToolsColor`    | No       | The color of the entry.                                                                                                                                                                                                                                                           |

React TSX

```
type DevToolsColor =

  | 'primary'

  | 'primary-light'

  | 'primary-dark'

  | 'secondary'

  | 'secondary-light'

  | 'secondary-dark'

  | 'tertiary'

  | 'tertiary-light'

  | 'tertiary-dark'

  | 'warning'

  | 'error';
```

* [Methods](#methods)
  * [`timeStamp()`](#timestamp)

----
url: https://reactnative.dev/docs/next/dropshadowvalue
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/dropshadowvalue)** (0.87).

Version: Next

The `DropShadowValue` object is taken by the [`filter`](/docs/next/view-style-props#filter) style prop for the `dropShadow` function. It is comprised of 2 or 3 lengths and an optional color. These values collectively define the drop shadow's color, position, and blurriness.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

  offsetX: 10,

  offsetY: -3,

  standardDeviation: '15px',

  color: 'blue',

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `offsetX`[​](#offsetx "Direct link to offsetx")

The offset on the x-axis. This can be positive or negative. A positive value indicates right and negative indicates left.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | No       |

### `offsetY`[​](#offsety "Direct link to offsety")

The offset on the y-axis. This can be positive or negative. A positive value indicates up and negative indicates down.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | No       |

### `standardDeviation`[​](#standarddeviation "Direct link to standarddeviation")

Represents the standard deviation used in the [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) algorithm. The larger the value the blurrier the shadow is. Only non-negative values are valid. The default is 0.

| Type             | Optional |
| ---------------- | -------- |
| number \| string | Yes      |

### `color`[​](#color "Direct link to color")

The color of the shadow. The default is `black`.

| Type                       | Optional |
| -------------------------- | -------- |
| [color](/docs/next/colors) | Yes      |

## Used by[​](#used-by "Direct link to Used by")

* [`filter`](/docs/next/view-style-props#filter)

----
url: https://reactnative.dev/docs/images
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

## Static Image Resources[​](#static-image-resources "Direct link to Static Image Resources")

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:

React TSX

```
<Image source={require('./my-icon.png')} />
```

The image name is resolved the same way JS modules are resolved. In the example above, the bundler will look for `my-icon.png` in the same folder as the component that requires it.

You can use the `@2x` and `@3x` suffixes to provide images for different screen densities. If you have the following file structure:

```
.

├── button.js

└── img

    ├── check.png

    ├── check@2x.png

    └── check@3x.png
```

...and `button.js` code contains:

React TSX

```
<Image source={require('./img/check.png')} />
```

```
// GOOD

<Image source={require('./my-icon.png')} />;



// BAD

const icon = this.props.active

  ? 'my-icon-active'

  : 'my-icon-inactive';

<Image source={require('./' + icon + '.png')} />;



// GOOD

const icon = this.props.active

  ? require('./my-icon-active.png')

  : require('./my-icon-inactive.png');

<Image source={icon} />;
```

Note that image sources required this way include size (width, height) info for the Image. If you need to scale the image dynamically (i.e. via flex), you may need to manually set `{width: undefined, height: undefined}` on the style attribute.

### Bundling images in an asset catalog (iOS)[​](#bundling-images-in-an-asset-catalog-ios "Direct link to Bundling images in an asset catalog (iOS)")

By default the bundler copies each required image, along with every `@2x` and `@3x` variant, into your iOS app as a loose file next to the JavaScript bundle. On iOS you can instead have them compiled into an [asset catalog](https://developer.apple.com/documentation/xcode/managing-assets-with-asset-catalogs), so the system ships only the scale a device needs.

To opt in, set the `RCTUseAssetCatalog` key to `true` in your app's `Info.plist`:

XML

```
<key>RCTUseAssetCatalog</key>

<true/>
```

```
<Image

  source={{uri: 'app_icon'}}

  style={{width: 40, height: 40}}

/>
```

For images in the Android assets folder, use the `asset:/` scheme:

React TSX

```
<Image

  source={{uri: 'asset:/app_icon.png'}}

  style={{width: 40, height: 40}}

/>
```

These approaches provide no safety checks. It's up to you to guarantee that those images are available in the application. Also you have to specify image dimensions manually.

## Network Images[​](#network-images "Direct link to Network Images")

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](https://developer.apple.com/documentation/security/preventing_insecure_network_connections) requirements on iOS.

React TSX

```
// GOOD

<Image source={{uri: 'https://reactjs.org/logo-og.png'}}

       style={{width: 400, height: 400}} />



// BAD

<Image source={{uri: 'https://reactjs.org/logo-og.png'}} />
```

### Network Requests for Images[​](#network-requests-for-images "Direct link to Network Requests for Images")

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:

React TSX

```
<Image

  source={{

    uri: 'https://reactjs.org/logo-og.png',

    method: 'POST',

    headers: {

      Pragma: 'no-cache',

    },

    body: 'Your Body goes here',

  }}

  style={{width: 400, height: 400}}

/>
```

## URI Data Images[​](#uri-data-images "Direct link to URI Data Images")

Sometimes, you might be getting encoded image data from a REST API call. You can use the `'data:'` URI scheme to use these images. Same as for network resources, *you will need to manually specify the dimensions of your image*.

info

This is recommended for very small and dynamic images only, like icons in a list from a DB.

React TSX

```
// include at least width and height!

<Image

  style={{

    width: 51,

    height: 51,

    resizeMode: 'contain',

  }}

  source={{

    uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',

  }}

/>
```

```
<Image

  source={{

    uri: 'https://reactjs.org/logo-og.png',

    cache: 'only-if-cached',

  }}

  style={{width: 400, height: 400}}

/>
```

## Local Filesystem Images[​](#local-filesystem-images "Direct link to Local Filesystem Images")

See [CameraRoll](https://github.com/react-native-community/react-native-cameraroll) for an example of using local resources that are outside of `Images.xcassets`.

### Drawable resources[​](#drawable-resources "Direct link to Drawable resources")

Android supports loading [drawable resources](https://developer.android.com/guide/topics/resources/drawable-resource) via the `xml` file type. This means you can use [vector drawables](https://developer.android.com/develop/ui/views/graphics/vector-drawable-resources) for rendering icons or [shape drawables](https://developer.android.com/guide/topics/resources/drawable-resource#Shape) for, well, drawing shapes! You can import and use these resource types the same as any other [static resource](#static-image-resources) or [hybrid resource](#images-from-hybrid-apps-resources). 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):

React TSX

```
<Image

  source={require('./img/my_icon.xml')}

  style={{width: 40, height: 40}}

/>
```

For drawables included in the Android drawable folder (i.e. `res/drawable`), use the resource name without the extension:

React TSX

```
<Image

  source={{uri: 'my_icon'}}

  style={{width: 40, height: 40}}

/>
```

```
{"__packager_asset":true,"uri":"my-icon.png","width":591,"height":573}
```

## Source as an object[​](#source-as-an-object "Direct link to Source as an object")

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.

React TSX

```
<Image source={{uri: 'something.jpg'}} />
```

On the infrastructure side, the reason is that it allows us to attach metadata to this object. For example if you are using `require('./my-icon.png')`, then we add information about its actual location and size (don't rely on this fact, it might change in the future!). This is also future proofing, for example we may want to support sprites at some point, instead of outputting `{uri: ...}`, we can output `{uri: ..., crop: {left: 10, top: 50, width: 20, height: 40}}` and transparently support spriting on all the existing call sites.

On the user side, this lets you annotate the object with useful attributes such as the dimension of the image in order to compute the size it's going to be displayed in. Feel free to use it as your data structure to store more information about your image.

## Background Image via Nesting[​](#background-image-via-nesting "Direct link to Background Image via Nesting")

To layer content over an image, render an absolutely positioned [`Image`](/docs/image) inside a [`View`](/docs/view), followed by the content that should appear on top.

React TSX

```
return (

  <View style={{width: '100%', height: '100%'}}>

    <Image source={...} style={StyleSheet.absoluteFill} />

    <Text>Inside</Text>

  </View>

);
```

On iOS, we expose an API to override React Native's default image cache limits. This should be called from within your native AppDelegate code (e.g. within `didFinishLaunchingWithOptions`).

Objective-C

```
RCTSetImageCacheLimits(4*1024*1024, 200*1024*1024);
```

**Parameters:**

| Name           | Type   | Required | Description             |
| -------------- | ------ | -------- | ----------------------- |
| imageSizeLimit | number | Yes      | Image cache size limit. |
| totalCostLimit | number | Yes      | Total cache cost limit. |

----
url: https://reactnative.dev/docs/next/progressbarandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/progressbarandroid)** (0.87).

Version: Next

Deprecated

Use one of the [community packages](https://reactnative.directory/?search=progressbar) instead.

Android-only React component used to indicate that the app is loading or there is some activity in the app.

### Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

Inherits [View Props](/docs/next/view#props).

### `animating`[​](#animating "Direct link to animating")

Whether to show the ProgressBar (true, the default) or hide it (false).

| Type | Required |
| ---- | -------- |
| bool | No       |

***

### `color`[​](#color "Direct link to color")

Color of the progress bar.

| Type                       | Required |
| -------------------------- | -------- |
| [color](/docs/next/colors) | No       |

***

### `indeterminate`[​](#indeterminate "Direct link to indeterminate")

If the progress bar will show indeterminate progress. Note that this can only be false if styleAttr is Horizontal, and requires a `progress` value.

| Type              | Required |
| ----------------- | -------- |
| indeterminateType | No       |

***

### `progress`[​](#progress "Direct link to progress")

The progress value (between 0 and 1).

| Type   | Required |
| ------ | -------- |
| number | No       |

***

| Type                                                                                      | Required |
| ----------------------------------------------------------------------------------------- | -------- |
| enum('Horizontal', 'Normal', 'Small', 'Large', 'Inverse', 'SmallInverse', 'LargeInverse') | No       |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

| Type   | Required |
| ------ | -------- |
| string | No       |

----
url: https://reactnative.dev/docs/global-queueMicrotask
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/queueMicrotask) for more information.

The global `queueMicrotask` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/touchablehighlight
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/touchablehighlight)** (0.87).

Version: Next

tip

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the [Pressable](/docs/next/pressable) API.

A wrapper for making views respond properly to touches. On press down, the opacity of the wrapped view is decreased, which allows the underlay color to show through, darkening or tinting the view.

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.

React TSX

```
function MyComponent(props: MyComponentProps) {

  return (

    <View {...props} style={{flex: 1, backgroundColor: '#fff'}}>

      <Text>My Component</Text>

    </View>

  );

}



<TouchableHighlight

  activeOpacity={0.6}

  underlayColor="#DDDDDD"

  onPress={() => alert('Pressed!')}>

  <MyComponent />

</TouchableHighlight>;
```

## Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

### [TouchableWithoutFeedback Props](/docs/next/touchablewithoutfeedback#props)[​](#touchablewithoutfeedback-props "Direct link to touchablewithoutfeedback-props")

Inherits [TouchableWithoutFeedback Props](/docs/next/touchablewithoutfeedback#props).

***

### `activeOpacity`[​](#activeopacity "Direct link to activeopacity")

Determines what the opacity of the wrapped view should be when touch is active. The value should be between 0 and 1. Defaults to 0.85. Requires `underlayColor` to be set.

| Type   |
| ------ |
| number |

***

### `onHideUnderlay`[​](#onhideunderlay "Direct link to onhideunderlay")

Called immediately after the underlay is hidden.

| Type     |
| -------- |
| function |

***

### `onShowUnderlay`[​](#onshowunderlay "Direct link to onshowunderlay")

Called immediately after the underlay is shown.

| Type     |
| -------- |
| function |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/next/element-nodes) when mounted.

***

### `style`[​](#style "Direct link to style")

| Type        |
| ----------- |
| View\.style |

***

### `underlayColor`[​](#underlaycolor "Direct link to underlaycolor")

The color of the underlay that will show through when the touch is active.

| Type                       |
| -------------------------- |
| [color](/docs/next/colors) |

***

### `hasTVPreferredFocus`iOS[​](#hastvpreferredfocus-ios "Direct link to hastvpreferredfocus-ios")

*(Apple TV only)* TV preferred focus (see documentation for the View component).

| Type |
| ---- |
| bool |

***

### `nextFocusDown`Android[​](#nextfocusdown-android "Direct link to nextfocusdown-android")

TV next focus down (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusForward`Android[​](#nextfocusforward-android "Direct link to nextfocusforward-android")

TV next focus forward (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusLeft`Android[​](#nextfocusleft-android "Direct link to nextfocusleft-android")

TV next focus left (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusRight`Android[​](#nextfocusright-android "Direct link to nextfocusright-android")

TV next focus right (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `nextFocusUp`Android[​](#nextfocusup-android "Direct link to nextfocusup-android")

TV next focus up (see documentation for the View component).

| Type   |
| ------ |
| number |

***

### `testOnly_pressed`[​](#testonly_pressed "Direct link to testonly_pressed")

Handy for snapshot tests.

| Type |
| ---- |
| bool |

    [iOS](#hastvpreferredfocus-ios)
  * [`nextFocusDown`](#nextfocusdown-android)

    [Android](#nextfocusdown-android)
  * [`nextFocusForward`](#nextfocusforward-android)

    [Android](#nextfocusforward-android)
  * [`nextFocusLeft`](#nextfocusleft-android)

    [Android](#nextfocusleft-android)
  * [`nextFocusRight`](#nextfocusright-android)

    [Android](#nextfocusright-android)
  * [`nextFocusUp`](#nextfocusup-android)

    [Android](#nextfocusup-android)
  * [`testOnly_pressed`](#testonly_pressed)

----
url: https://reactnative.dev/docs/next/turbo-native-modules-introduction
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/turbo-native-modules-introduction)** (0.87).

Version: Next

```
npx @react-native-community/cli@latest init TurboModuleExample --version "latest"
```

```
import type {TurboModule} from 'react-native';

import {TurboModuleRegistry} from 'react-native';



export interface Spec extends TurboModule {

  setItem(value: string, key: string): void;

  getItem(key: string): string | null;

  removeItem(key: string): void;

  clear(): void;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeLocalStorage',

);
```

NativeLocalStorage.js

```
import type {TurboModule} from 'react-native';

import {TurboModule, TurboModuleRegistry} from 'react-native';



export interface Spec extends TurboModule {

  setItem(value: string, key: string): void;

  getItem(key: string): ?string;

  removeItem(key: string): void;

  clear(): void;

}
```

### 2. Configure Codegen to run[​](#2-configure-codegen-to-run "Direct link to 2. Configure Codegen to run")

The specification is used by the React Native Codegen tools to generate platform specific interfaces and boilerplate for us. To do this, Codegen needs to know where to find our specification and what to do with it. Update your `package.json` to include:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "NativeLocalStorageSpec",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.nativelocalstorage"

     }

   },

   "dependencies": {
```

With everything wired up for Codegen, we need to prepare our native code to hook into our generated code.

* Android
* iOS

Codegen is executed through the `generateCodegenArtifactsFromSchema` Gradle task:

```
cd android

./gradlew generateCodegenArtifactsFromSchema



BUILD SUCCESSFUL in 837ms

14 actionable tasks: 3 executed, 11 up-to-date
```

This is automatically run when you build your Android application.

Codegen is run as part of the script phases that's automatically added to the project generated by CocoaPods.

```
cd ios

bundle install

bundle exec pod install
```

The output will look like this:

```
...

Framework build type is static library

[Codegen] Adding script_phases to ReactCodegen.

[Codegen] Generating ./build/generated/ios/ReactCodegen.podspec.json

[Codegen] Analyzing /Users/me/src/TurboModuleExample/package.json

[Codegen] Searching for codegen-enabled libraries in the app.

[Codegen] Found TurboModuleExample

[Codegen] Searching for codegen-enabled libraries in the project dependencies.

[Codegen] Found react-native

...
```

### 3. Write Application Code using the Turbo Native Module[​](#3-write-application-code-using-the-turbo-native-module "Direct link to 3. Write Application Code using the Turbo Native Module")

Using `NativeLocalStorage`, here’s a modified `App.tsx` that includes some text we want persisted, an input field and some buttons to update this value.

The `TurboModuleRegistry` supports 2 modes of retrieving a Turbo Native Module:

* `get<T>(name: string): T | null` which will return `null` if the Turbo Native Module is unavailable.
* `getEnforcing<T>(name: string): T` which will throw an exception if the Turbo Native Module is unavailable. This assumes the module is always available.

App.tsx

```
import {useEffect, useState, type JSX} from 'react';

import {

  SafeAreaView,

  StyleSheet,

  Text,

  TextInput,

  Button,

} from 'react-native';



import NativeLocalStorage from './specs/NativeLocalStorage';



const EMPTY = '<empty>';



function App(): JSX.Element {

  const [value, setValue] = useState<string | null>(null);



  const [editingValue, setEditingValue] = useState<string | null>(

    null,

  );



  useEffect(() => {

    const storedValue = NativeLocalStorage?.getItem('myKey');

    setValue(storedValue ?? '');

  }, []);



  function saveValue() {

    NativeLocalStorage?.setItem(editingValue ?? EMPTY, 'myKey');

    setValue(editingValue);

  }



  function clearAll() {

    NativeLocalStorage?.clear();

    setValue('');

  }



  function deleteValue() {

    NativeLocalStorage?.removeItem('myKey');

    setValue('');

  }



  return (

    <SafeAreaView style={{flex: 1}}>

      <Text style={styles.text}>

        Current stored value is: {value ?? 'No Value'}

      </Text>

      <TextInput

        placeholder="Enter the text you want to store"

        style={styles.textInput}

        onChangeText={setEditingValue}

      />

      <Button title="Save" onPress={saveValue} />

      <Button title="Delete" onPress={deleteValue} />

      <Button title="Clear" onPress={clearAll} />

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  text: {

    margin: 10,

    fontSize: 20,

  },

  textInput: {

    margin: 10,

    height: 40,

    borderColor: 'black',

    borderWidth: 1,

    paddingLeft: 5,

    paddingRight: 5,

    borderRadius: 5,

  },

});



export default App;
```

```
package com.nativelocalstorage;



import android.content.Context;

import android.content.SharedPreferences;

import com.nativelocalstorage.NativeLocalStorageSpec;

import com.facebook.react.bridge.ReactApplicationContext;



public class NativeLocalStorageModule extends NativeLocalStorageSpec {



  public static final String NAME = "NativeLocalStorage";



  public NativeLocalStorageModule(ReactApplicationContext reactContext) {

    super(reactContext);

  }



  @Override

  public String getName() {

    return NAME;

  }



  @Override

  public void setItem(String value, String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();

    editor.putString(key, value);

    editor.apply();

  }



  @Override

  public String getItem(String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    String username = sharedPref.getString(key, null);

    return username;

  }



  @Override

  public void removeItem(String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    sharedPref.edit().remove(key).apply();

  }



  @Override

  public void clear() {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    sharedPref.edit().clear().apply();

  }

}
```

android/app/src/main/java/com/nativelocalstorage/NativeLocalStorageModule.kt

```
package com.nativelocalstorage



import android.content.Context

import android.content.SharedPreferences

import com.nativelocalstorage.NativeLocalStorageSpec

import com.facebook.react.bridge.ReactApplicationContext



class NativeLocalStorageModule(reactContext: ReactApplicationContext) : NativeLocalStorageSpec(reactContext) {



  override fun getName() = NAME



  override fun setItem(value: String, key: String) {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.putString(key, value)

    editor.apply()

  }



  override fun getItem(key: String): String? {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val username = sharedPref.getString(key, null)

    return username.toString()

  }



  override fun removeItem(key: String) {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.remove(key)

    editor.apply()

  }



  override fun clear() {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.clear()

    editor.apply()

  }



  companion object {

    const val NAME = "NativeLocalStorage"

  }

}
```

Next we need to create `NativeLocalStoragePackage`. It provides an object to register our Module in the React Native runtime, by wrapping it as a Base Native Package:

* Java
* Kotlin

android/app/src/main/java/com/nativelocalstorage/NativeLocalStoragePackage.java

```
package com.nativelocalstorage;



import com.facebook.react.BaseReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.model.ReactModuleInfo;

import com.facebook.react.module.model.ReactModuleInfoProvider;



import java.util.HashMap;

import java.util.Map;



public class NativeLocalStoragePackage extends BaseReactPackage {



  @Override

  public NativeModule getModule(String name, ReactApplicationContext reactContext) {

    if (name.equals(NativeLocalStorageModule.NAME)) {

      return new NativeLocalStorageModule(reactContext);

    } else {

      return null;

    }

  }



  @Override

  public ReactModuleInfoProvider getReactModuleInfoProvider() {

    return new ReactModuleInfoProvider() {

      @Override

      public Map<String, ReactModuleInfo> getReactModuleInfos() {

        Map<String, ReactModuleInfo> map = new HashMap<>();

        map.put(NativeLocalStorageModule.NAME, new ReactModuleInfo(

          NativeLocalStorageModule.NAME,       // name

          NativeLocalStorageModule.NAME,       // className

          false, // canOverrideExistingModule

          false, // needsEagerInit

          false, // isCXXModule

          true   // isTurboModule

        ));

        return map;

      }

    };

  }

}
```

android/app/src/main/java/com/nativelocalstorage/NativeLocalStoragePackage.kt

```
package com.nativelocalstorage



import com.facebook.react.BaseReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.module.model.ReactModuleInfo

import com.facebook.react.module.model.ReactModuleInfoProvider



class NativeLocalStoragePackage : BaseReactPackage() {



  override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =

    if (name == NativeLocalStorageModule.NAME) {

      NativeLocalStorageModule(reactContext)

    } else {

      null

    }



  override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {

    mapOf(

      NativeLocalStorageModule.NAME to ReactModuleInfo(

        name = NativeLocalStorageModule.NAME,

        className = NativeLocalStorageModule.NAME,

        canOverrideExistingModule = false,

        needsEagerInit = false,

        isCxxModule = false,

        isTurboModule = true

      )

    )

  }

}
```

```
package com.inappmodule;



import android.app.Application;

import com.facebook.react.PackageList;

import com.facebook.react.ReactApplication;

import com.facebook.react.ReactHost;

import com.facebook.react.ReactNativeHost;

import com.facebook.react.ReactPackage;

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;

import com.facebook.react.defaults.DefaultReactHost;

import com.facebook.react.defaults.DefaultReactNativeHost;

import com.facebook.soloader.SoLoader;

import com.nativelocalstorage.NativeLocalStoragePackage;



import java.util.ArrayList;

import java.util.List;



public class MainApplication extends Application implements ReactApplication {



  private final ReactNativeHost reactNativeHost = new DefaultReactNativeHost(this) {

    @Override

    public List<ReactPackage> getPackages() {

      List<ReactPackage> packages = new PackageList(this).getPackages();

      // Packages that cannot be autolinked yet can be added manually here, for example:

      // packages.add(new MyReactNativePackage());

      packages.add(new NativeLocalStoragePackage());

      return packages;

    }



    @Override

    public String getJSMainModuleName() {

      return "index";

    }



    @Override

    public boolean getUseDeveloperSupport() {

      return BuildConfig.DEBUG;

    }



    @Override

    public boolean isNewArchEnabled() {

      return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;

    }



    @Override

    public boolean isHermesEnabled() {

      return BuildConfig.IS_HERMES_ENABLED;

    }

  };



  @Override

  public ReactHost getReactHost() {

    return DefaultReactHost.getDefaultReactHost(getApplicationContext(), reactNativeHost);

  }



  @Override

  public void onCreate() {

    super.onCreate();

    SoLoader.init(this, false);

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      // If you opted-in for the New Architecture, we load the native entry point for this app.

      DefaultNewArchitectureEntryPoint.load();

    }

  }

}
```

android/app/src/main/java/com/turobmoduleexample/MainApplication.kt

```
package com.inappmodule



import android.app.Application

import com.facebook.react.PackageList

import com.facebook.react.ReactApplication

import com.facebook.react.ReactHost

import com.facebook.react.ReactNativeHost

import com.facebook.react.ReactPackage

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

import com.facebook.react.defaults.DefaultReactNativeHost

import com.facebook.soloader.SoLoader

import com.nativelocalstorage.NativeLocalStoragePackage



class MainApplication : Application(), ReactApplication {



  override val reactNativeHost: ReactNativeHost =

      object : DefaultReactNativeHost(this) {

        override fun getPackages(): List<ReactPackage> =

            PackageList(this).packages.apply {

              // Packages that cannot be autolinked yet can be added manually here, for example:

              // add(MyReactNativePackage())

              add(NativeLocalStoragePackage())

            }



        override fun getJSMainModuleName(): String = "index"



        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG



        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

      }



  override val reactHost: ReactHost

    get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

    SoLoader.init(this, false)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      // If you opted-in for the New Architecture, we load the native entry point for this app.

      load()

    }

  }

}
```

You can now build and run your code on an emulator:

* npm
* Yarn

```
npm run android
```

```
yarn run android
```

Now it's time to write some iOS platform code to make sure `localStorage` survives after the application is closed.

## Prepare your Xcode Project[​](#prepare-your-xcode-project "Direct link to Prepare your Xcode Project")

We need to prepare your iOS project using Xcode. After completing these **6 steps** you'll have `RCTNativeLocalStorage` that implements the generated `NativeLocalStorageSpec` interface.

1. Open the CocoaPods generated Xcode Workspace:

```
cd ios

open TurboModuleExample.xcworkspace
```

```
//  RCTNativeLocalStorage.h

//  TurboModuleExample



#import <Foundation/Foundation.h>

#import <NativeLocalStorageSpec/NativeLocalStorageSpec.h>



NS_ASSUME_NONNULL_BEGIN



@interface RCTNativeLocalStorage : NSObject

@interface RCTNativeLocalStorage : NSObject <NativeLocalStorageSpec>



@end
```

Then update our implementation to use `NSUserDefaults` with a custom [suite name](https://developer.apple.com/documentation/foundation/nsuserdefaults/1409957-initwithsuitename).

NativeLocalStorage/RCTNativeLocalStorage.mm

```
//  RCTNativeLocalStorage.m

//  TurboModuleExample



#import "RCTNativeLocalStorage.h"



static NSString *const RCTNativeLocalStorageKey = @"local-storage";



@interface RCTNativeLocalStorage()

@property (strong, nonatomic) NSUserDefaults *localStorage;

@end



@implementation RCTNativeLocalStorage



- (id) init {

  if (self = [super init]) {

    _localStorage = [[NSUserDefaults alloc] initWithSuiteName:RCTNativeLocalStorageKey];

  }

  return self;

}



- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {

  return std::make_shared<facebook::react::NativeLocalStorageSpecJSI>(params);

}



- (NSString * _Nullable)getItem:(NSString *)key {

  return [self.localStorage stringForKey:key];

}



- (void)setItem:(NSString *)value

          key:(NSString *)key {

  [self.localStorage setObject:value forKey:key];

}



- (void)removeItem:(NSString *)key {

  [self.localStorage removeObjectForKey:key];

}



- (void)clear {

  NSDictionary *keys = [self.localStorage dictionaryRepresentation];

  for (NSString *key in keys) {

    [self removeItem:key];

  }

}



+ (NSString *)moduleName

{

  return @"NativeLocalStorage";

}



@end
```

Important things to note:

* You can use Xcode to jump to the Codegen `@protocol NativeLocalStorageSpec`. You can also use Xcode to generate stubs for you.

## Register the Native Module in your app[​](#register-the-native-module-in-your-app "Direct link to Register the Native Module in your app")

The last step consist in updating the `package.json` to tell React Native about the link between the JS specs of the Native Module and the concrete implementation of those specs in native code.

Modify the `package.json` as it follows:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "NativeLocalStorageSpec",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.nativelocalstorage"

     },

     "ios": {

        "modulesProvider": {

          "NativeLocalStorage": "RCTNativeLocalStorage"

        }

     }

   },



   "dependencies": {
```

At this point, you need to re-install the pods to make sure that codegen runs again to generate the new files:

```
# from the ios folder

bundle exec pod install

open TurboModuleExample.xcworkspace
```

If you now build your application from Xcode, you should be able to build successfully.

## Build and run your code on a Simulator[​](#build-and-run-your-code-on-a-simulator "Direct link to Build and run your code on a Simulator")

* npm
* Yarn

```
npm run ios
```

```
yarn run ios
```

* [Native Persistent Storage](#native-persistent-storage)

  * [1. Declare Typed Specification](#1-declare-typed-specification)
  * [2. Configure Codegen to run](#2-configure-codegen-to-run)
  * [3. Write Application Code using the Turbo Native Module](#3-write-application-code-using-the-turbo-native-module)
  * [4. Write your Native Platform code](#4-write-your-native-platform-code)

----
url: https://reactnative.dev/docs/running-on-simulator-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

## Starting the simulator[​](#starting-the-simulator "Direct link to Starting the simulator")

Once you have your React Native project initialized, you can run the following command inside the newly created project directory.

* npm
* Yarn

```
npm run ios
```

```
yarn ios
```

If everything is set up correctly, you should see your new app running in the iOS Simulator shortly.

## Specifying a device[​](#specifying-a-device "Direct link to Specifying a device")

You can specify the device the simulator should run with the `--simulator` flag, followed by the device name as a string. The default is `"iPhone 14"`. If you wish to run your app on an iPhone SE (3rd generation), run the following command:

* npm
* Yarn

```
npm run ios -- --simulator="iPhone SE (3rd generation)"
```

```
yarn ios --simulator "iPhone SE (3rd generation)"
```

The device names correspond to the list of devices available in Xcode. You can check your available devices by running `xcrun simctl list devices` from the console.

### Specifying a version of device[​](#specifying-a-version-of-device "Direct link to Specifying a version of device")

If you have multiple iOS versions installed, you also need to specify its appropriate version. E.g. To run your app on an iPhone 14 Pro (16.0) run the following command:

* npm
* Yarn

```
npm run ios -- --simulator="iPhone 14 Pro (16.0)"
```

```
yarn ios --simulator "iPhone 14 Pro (16.0)"
```

## Specifying an UDID[​](#specifying-an-udid "Direct link to Specifying an UDID")

You can specify the device UDID returned from `xcrun simctl list devices` command. E.g. To run your app with UDID `AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA` run the following command:

* npm
* Yarn

```
npm run ios -- --udid="AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"
```

```
yarn ios --udid "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"
```

* [Starting the simulator](#starting-the-simulator)
* [Specifying a device](#specifying-a-device)
  * [Specifying a version of device](#specifying-a-version-of-device)
* [Specifying an UDID](#specifying-an-udid)

----
url: https://reactnative.dev/docs/next/build-speed
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/build-speed)** (0.87).

Version: Next

```
$ yarn react-native run-android --active-arch-only



[ ... ]

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.

Jetifier found 1037 file(s) to forward-jetify. Using 32 workers...

info JS server already running.

info Detected architectures arm64-v8a

info Installing the app...
```

This mechanism relies on the `reactNativeArchitectures` Gradle property.

Therefore, if you're building directly with Gradle from the command line and without the CLI, you can specify the ABI you want to build as follows:

```
$ ./gradlew :app:assembleDebug -PreactNativeArchitectures=x86,x86_64
```

This can be useful if you wish to build your Android App on a CI and use a matrix to parallelize the build of the different architectures.

If you wish, you can also override this value locally, using the `gradle.properties` file you have in the [top-level folder](https://github.com/react/react-native/blob/19cf70266eb8ca151aa0cc46ac4c09cb987b2ceb/template/android/gradle.properties#L30-L33) of your project:

```
# Use this property to specify which architecture you want to build.

# You can also override it from the CLI using

# ./gradlew <task> -PreactNativeArchitectures=x86_64

reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
```

```
org.gradle.configuration-cache=true
```

Please refer to the [official Gradle documentation](https://docs.gradle.org/current/userguide/configuration_cache.html) for more resources on Configuration Caching.

## Using a Maven Mirror (Android-only)[​](#using-a-maven-mirror-android-only "Direct link to Using a Maven Mirror (Android-only)")

When building Android apps, your Gradle builds will need to download the necessary dependencies from Maven Central and other repositories from the internet.

If your organization is running a Maven repository mirror, you should consider using it as it will speed up your build, by downloading the artifacts from the mirror rather than from the internet.

You can configure a mirror by specifying the `exclusiveEnterpriseRepository` property in your `android/gradle.properties` file:

Diff

```
# Use this property to enable or disable the Hermes JS engine.

# If set to false, you will be using JSC instead.

hermesEnabled=true



# Use this property to configure a Maven enterprise repository

# that will be used exclusively to fetch all of your dependencies.

+exclusiveEnterpriseRepository=https://my.internal.proxy.net/
```

```
$ ccache -s

Summary:

  Hits:             196 /  3068 (6.39 %)

    Direct:           0 /  3068 (0.00 %)

    Preprocessed:   196 /  3068 (6.39 %)

  Misses:          2872

    Direct:        3068

    Preprocessed:  2872

  Uncacheable:        1

Primary storage:

  Hits:             196 /  6136 (3.19 %)

  Misses:          5940

  Cache size (GB): 0.60 / 20.00 (3.00 %)
```

Note that `ccache` aggregates the stats over all builds. You can use `ccache --zero-stats` to reset them before a build to verify the cache-hit ratio.

Should you need to wipe your cache, you can do so with `ccache --clear`

#### Xcode Specific Setup[​](#xcode-specific-setup "Direct link to Xcode Specific Setup")

To make sure `ccache` works correctly with iOS and Xcode, you need to enable React Native support for ccache in `ios/Podfile`.

Open `ios/Podfile` in your editor and uncomment the `ccache_enabled` line.

Ruby

```
  post_install do |installer|

    # https://github.com/react/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202

    react_native_post_install(

      installer,

      config[:reactNativePath],

      :mac_catalyst_enabled => false,

      # TODO: Uncomment the line below

      :ccache_enabled => true

    )

  end
```

----
url: https://reactnative.dev/docs/fabric-native-components-introduction
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
npx @react-native-community/cli@latest init Demo --install-pods false
```

## Creating a WebView Component[​](#creating-a-webview-component "Direct link to Creating a WebView Component")

This guide will show you how to create a Web View component. We will be creating the component by using the Android's [`WebView`](https://developer.android.com/reference/android/webkit/WebView) component, and the iOS [`WKWebView`](https://developer.apple.com/documentation/webkit/wkwebview?language=objc) component.

Let's start by creating the folders structure to hold our component's code:

```
mkdir -p Demo/{specs,android/app/src/main/java/com/webview}
```

This gives you the following layout where you'll working:

```
Demo

├── android/app/src/main/java/com/webview

└── ios

└── specs
```

* The `android/app/src/main/java/com/webview` folder is the folder that will contain our Android code.
* The `ios` folder is the folder that will contain our iOS code.
* The `specs` folder is the folder that will contain the Codegen's specification file.

## 1. Define Specification for Codegen[​](#1-define-specification-for-codegen "Direct link to 1. Define Specification for Codegen")

Your specification must be defined in either [TypeScript](https://www.typescriptlang.org/) or [Flow](https://flow.org/) (see [Codegen](/docs/the-new-architecture/what-is-codegen) documentation for more details). This is used by Codegen to generate the C++, Objective-C++ and Java to connect your platform code to the JavaScript runtime that React runs in.

The specification file must be named `<MODULE_NAME>NativeComponent.{ts|js}` to work with Codegen. The suffix `NativeComponent` is not only a convention, it is actually used by Codegen to detect a spec file.

Use this specification for our WebView Component:

* TypeScript
* Flow

Demo/specs/WebViewNativeComponent.ts

```
import type {

  CodegenTypes,

  HostComponent,

  ViewProps,

} from 'react-native';

import {codegenNativeComponent} from 'react-native';



type WebViewScriptLoadedEvent = {

  result: 'success' | 'error';

};



export interface NativeProps extends ViewProps {

  sourceURL?: string;

  onScriptLoaded?: CodegenTypes.BubblingEventHandler<WebViewScriptLoadedEvent> | null;

}



export default codegenNativeComponent<NativeProps>(

  'CustomWebView',

) as HostComponent<NativeProps>;
```

Demo/RCTWebView/js/RCTWebViewNativeComponent.js

```
// @flow strict-local



import type {CodegenTypes, HostComponent, ViewProps} from 'react-native';

import {codegenNativeComponent} from 'react-native';



type WebViewScriptLoadedEvent = $ReadOnly<{|

  result: "success" | "error",

|}>;



type NativeProps = $ReadOnly<{|

  ...ViewProps,

  sourceURL?: string;

  onScriptLoaded?: CodegenTypes.BubblingEventHandler<WebViewScriptLoadedEvent>?;

|}>;



export default (codegenNativeComponent<NativeProps>(

  'CustomWebView',

): HostComponent<NativeProps>);
```

This specification is composed of three main parts, excluding the imports:

* The `WebViewScriptLoadedEvent` is a supporting data type for the data the event needs to pass from native to JavaScript.
* The `NativeProps` is a definition of the props that we can set on the component.
* The `codegenNativeComponent` statement allows us to codegenerate the code for the custom component and that defines a name for the component used to match the native implementations.

As with Native Modules, you can have multiple specification files in the `specs/` directory. For more information about the types you can use, and the platform types these map to, see the [appendix](/docs/appendix#ii-codegen-typings).

## 2. Configure Codegen to run[​](#2-configure-codegen-to-run "Direct link to 2. Configure Codegen to run")

The specification is used by the React Native's Codegen tools to generate platform specific interfaces and boilerplate for us. To do this, Codegen needs to know where to find our specification and what to do with it. Update your `package.json` to include:

JSON

```
    "start": "react-native start",

    "test": "jest"

  },

  "codegenConfig": {

    "name": "AppSpec",

    "type": "components",

    "jsSrcsDir": "specs",

    "android": {

      "javaPackageName": "com.webview"

    },

    "ios": {

      "componentProvider": {

        "CustomWebView": "RCTWebView"

      }

    }

  },

  "dependencies": {
```

```
cd android

./gradlew generateCodegenArtifactsFromSchema
```

```
package com.webview;



import android.content.Context;

import android.util.AttributeSet;

import android.webkit.WebView;

import android.webkit.WebViewClient;



import com.facebook.react.bridge.Arguments;

import com.facebook.react.bridge.WritableMap;

import com.facebook.react.bridge.ReactContext;

import com.facebook.react.uimanager.UIManagerHelper;

import com.facebook.react.uimanager.events.Event;



public class ReactWebView extends WebView {

  public ReactWebView(Context context) {

    super(context);

    configureComponent();

  }



  public ReactWebView(Context context, AttributeSet attrs) {

    super(context, attrs);

    configureComponent();

  }



  public ReactWebView(Context context, AttributeSet attrs, int defStyleAttr) {

    super(context, attrs, defStyleAttr);

    configureComponent();

  }



  private void configureComponent() {

    this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    this.setWebViewClient(new WebViewClient() {

      @Override

      public void onPageFinished(WebView view, String url) {

        emitOnScriptLoaded(OnScriptLoadedEventResult.success);

      }

    });

  }



  public void emitOnScriptLoaded(OnScriptLoadedEventResult result) {

    ReactContext reactContext = (ReactContext) context;

    int surfaceId = UIManagerHelper.getSurfaceId(reactContext);

    EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());

    WritableMap payload = Arguments.createMap();

    payload.putString("result", result.name());



    OnScriptLoadedEvent event = new OnScriptLoadedEvent(surfaceId, getId(), payload);

    if (eventDispatcher != null) {

      eventDispatcher.dispatchEvent(event);

    }

  }



  public enum OnScriptLoadedEventResult {

    success,

    error

  }



  private class OnScriptLoadedEvent extends Event<OnScriptLoadedEvent> {

    private final WritableMap payload;



    OnScriptLoadedEvent(int surfaceId, int viewId, WritableMap payload) {

      super(surfaceId, viewId);

      this.payload = payload;

    }



    @Override

    public String getEventName() {

      return "onScriptLoaded";

    }



    @Override

    public WritableMap getEventData() {

      return payload;

    }

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebView\.kt

```
package com.webview



import android.content.Context

import android.util.AttributeSet

import android.webkit.WebView

import android.webkit.WebViewClient

import com.facebook.react.bridge.Arguments

import com.facebook.react.bridge.WritableMap

import com.facebook.react.bridge.ReactContext

import com.facebook.react.uimanager.UIManagerHelper

import com.facebook.react.uimanager.events.Event



class ReactWebView: WebView {

  constructor(context: Context) : super(context) {

    configureComponent()

  }



  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {

    configureComponent()

  }



  constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {

    configureComponent()

  }



  private fun configureComponent() {

    this.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)

    this.webViewClient = object : WebViewClient() {

      override fun onPageFinished(view: WebView, url: String) {

        emitOnScriptLoaded(OnScriptLoadedEventResult.success)

      }

    }

  }



  fun emitOnScriptLoaded(result: OnScriptLoadedEventResult) {

    val reactContext = context as ReactContext

    val surfaceId = UIManagerHelper.getSurfaceId(reactContext)

    val eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, id)

    val payload =

        Arguments.createMap().apply {

          putString("result", result.name)

        }

    val event = OnScriptLoadedEvent(surfaceId, id, payload)



    eventDispatcher?.dispatchEvent(event)

  }



  enum class OnScriptLoadedEventResult {

    success,

    error;

  }



  inner class OnScriptLoadedEvent(

      surfaceId: Int,

      viewId: Int,

      private val payload: WritableMap

  ) : Event<OnScriptLoadedEvent>(surfaceId, viewId) {

    override fun getEventName() = "onScriptLoaded"



    override fun getEventData() = payload

  }

}
```

```
package com.webview;



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.annotations.ReactModule;

import com.facebook.react.uimanager.SimpleViewManager;

import com.facebook.react.uimanager.ThemedReactContext;

import com.facebook.react.uimanager.ViewManagerDelegate;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;

import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;



import java.util.HashMap;

import java.util.Map;



@ReactModule(name = ReactWebViewManager.REACT_CLASS)

class ReactWebViewManager extends SimpleViewManager<ReactWebView> implements CustomWebViewManagerInterface<ReactWebView> {

  private final CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> delegate =

          new CustomWebViewManagerDelegate<>(this);



  @Override

  public ViewManagerDelegate<ReactWebView> getDelegate() {

    return delegate;

  }



  @Override

  public String getName() {

    return REACT_CLASS;

  }



  @Override

  public ReactWebView createViewInstance(ThemedReactContext context) {

    return new ReactWebView(context);

  }



  @ReactProp(name = "sourceUrl")

  @Override

  public void setSourceURL(ReactWebView view, String sourceURL) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error);

      return;

    }

    view.loadUrl(sourceURL, new HashMap<>());

  }



  public static final String REACT_CLASS = "CustomWebView";



  @Override

  public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {

    Map<String, Object> map = new HashMap<>();

    Map<String, Object> bubblingMap = new HashMap<>();

    bubblingMap.put("phasedRegistrationNames", new HashMap<String, String>() {{

      put("bubbled", "onScriptLoaded");

      put("captured", "onScriptLoadedCapture");

    }});

    map.put("onScriptLoaded", bubblingMap);

    return map;

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebViewManager.kt

```
package com.webview



import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.annotations.ReactModule;

import com.facebook.react.uimanager.SimpleViewManager;

import com.facebook.react.uimanager.ThemedReactContext;

import com.facebook.react.uimanager.ViewManagerDelegate;

import com.facebook.react.uimanager.annotations.ReactProp;

import com.facebook.react.viewmanagers.CustomWebViewManagerInterface;

import com.facebook.react.viewmanagers.CustomWebViewManagerDelegate;



@ReactModule(name = ReactWebViewManager.REACT_CLASS)

class ReactWebViewManager(context: ReactApplicationContext) : SimpleViewManager<ReactWebView>(), CustomWebViewManagerInterface<ReactWebView> {

  private val delegate: CustomWebViewManagerDelegate<ReactWebView, ReactWebViewManager> =

    CustomWebViewManagerDelegate(this)



  override fun getDelegate(): ViewManagerDelegate<ReactWebView> = delegate



  override fun getName(): String = REACT_CLASS



  override fun createViewInstance(context: ThemedReactContext): ReactWebView = ReactWebView(context)



  @ReactProp(name = "sourceUrl")

  override fun setSourceURL(view: ReactWebView, sourceURL: String?) {

    if (sourceURL == null) {

      view.emitOnScriptLoaded(ReactWebView.OnScriptLoadedEventResult.error)

      return;

    }

    view.loadUrl(sourceURL, emptyMap())

  }



  companion object {

    const val REACT_CLASS = "CustomWebView"

  }



  override fun getExportedCustomBubblingEventTypeConstants(): Map<String, Any> =

      mapOf(

          "onScriptLoaded" to

              mapOf(

                  "phasedRegistrationNames" to

                      mapOf(

                          "bubbled" to "onScriptLoaded",

                          "captured" to "onScriptLoadedCapture"

                      )))

}
```

```
package com.webview;



import com.facebook.react.BaseReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.model.ReactModuleInfo;

import com.facebook.react.module.model.ReactModuleInfoProvider;

import com.facebook.react.uimanager.ViewManager;



import java.util.Collections;

import java.util.HashMap;

import java.util.List;

import java.util.Map;



public class ReactWebViewPackage extends BaseReactPackage {

  @Override

  public List<ViewManager<?, ?>> createViewManagers(ReactApplicationContext reactContext) {

    return Collections.singletonList(new ReactWebViewManager(reactContext));

  }



  @Override

  public NativeModule getModule(String s, ReactApplicationContext reactApplicationContext) {

    if (ReactWebViewManager.REACT_CLASS.equals(s)) {

      return new ReactWebViewManager(reactApplicationContext);

    }

    return null;

  }



  @Override

  public ReactModuleInfoProvider getReactModuleInfoProvider() {

    return new ReactModuleInfoProvider() {

      @Override

      public Map<String, ReactModuleInfo> getReactModuleInfos() {

        Map<String, ReactModuleInfo> map = new HashMap<>();

        map.put(ReactWebViewManager.REACT_CLASS, new ReactModuleInfo(

                ReactWebViewManager.REACT_CLASS, // name

                ReactWebViewManager.REACT_CLASS, // className

                false,                           // canOverrideExistingModule

                false,                           // needsEagerInit

                false,                           // isCxxModule

                true                             // isTurboModule

        ));

        return map;

      }

    };

  }

}
```

Demo/android/src/main/java/com/webview/ReactWebViewPackage.kt

```
package com.webview



import com.facebook.react.BaseReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.module.model.ReactModuleInfo

import com.facebook.react.module.model.ReactModuleInfoProvider

import com.facebook.react.uimanager.ViewManager



class ReactWebViewPackage : BaseReactPackage() {

  override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {

    return listOf(ReactWebViewManager(reactContext))

  }



  override fun getModule(s: String, reactApplicationContext: ReactApplicationContext): NativeModule? {

    when (s) {

      ReactWebViewManager.REACT_CLASS -> ReactWebViewManager(reactApplicationContext)

    }

    return null

  }



  override fun getReactModuleInfoProvider(): ReactModuleInfoProvider = ReactModuleInfoProvider {

    mapOf(ReactWebViewManager.REACT_CLASS to ReactModuleInfo(

      name = ReactWebViewManager.REACT_CLASS,

      className = ReactWebViewManager.REACT_CLASS,

      canOverrideExistingModule = false,

      needsEagerInit = false,

      isCxxModule = false,

      isTurboModule = true,

    )

    )

  }

}
```

```
package com.demo



import android.app.Application

import com.facebook.react.PackageList

import com.facebook.react.ReactApplication

import com.facebook.react.ReactHost

import com.facebook.react.ReactNativeHost

import com.facebook.react.ReactPackage

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

import com.facebook.react.defaults.DefaultReactNativeHost

import com.facebook.react.soloader.OpenSourceMergedSoMapping

import com.facebook.soloader.SoLoader

import com.webview.ReactWebViewPackage



class MainApplication : Application(), ReactApplication {



  override val reactNativeHost: ReactNativeHost =

      object : DefaultReactNativeHost(this) {

        override fun getPackages(): List<ReactPackage> =

            PackageList(this).packages.apply {

              add(ReactWebViewPackage())

            }



        override fun getJSMainModuleName(): String = "index"



        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG



        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

      }



  override val reactHost: ReactHost

    get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

    SoLoader.init(this, OpenSourceMergedSoMapping)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      load()

    }

  }

}
```

Now it's time to write some iOS platform code to be able to render the web view. The steps you need to follow are:

* Run Codegen.
* Write the code for the `RCTWebView`
* Register the `RCTWebView` in the application

### 1. Run Codegen[​](#1-run-codegen "Direct link to 1. Run Codegen")

You can [manually run](/docs/the-new-architecture/codegen-cli) the Codegen, however it's simpler to use the application you're going to demo the component in to do this for you.

```
cd ios

bundle install

bundle exec pod install
```

Importantly you will see logging output from Codegen, which we're going to use in Xcode to build our WebView native component.

warning

You should be careful about committing generated code to your repository. Generated code is specific to each version of React Native. Use npm [peerDependencies](https://nodejs.org/en/blog/npm/peer-dependencies) to restrict compatibility with version of React Native.

### 3. Write the `RCTWebView`[​](#3-write-the-rctwebview "Direct link to 3-write-the-rctwebview")

We need to prepare your iOS project using Xcode by completing these **5 steps**:

1. Open the CocoaPods generated Xcode Workspace:

```
cd ios

open Demo.xcworkspace
```

2. Right click on app and select `New Group`, call the new group `WebView`.

3) In the `WebView` group, create `New`→`File from Template`.

4. Use the `Objective-C File` template, and name it `RCTWebView`.

5) Repeat step 4 and create a header file named `RCTWebView.h`.

6) Rename `RCTWebView.m` → `RCTWebView.mm` making it an Objective-C++ file.

Demo/ios

```
Podfile

...

Demo

├── AppDelegate.swift

...

├── RCTWebView.h

└── RCTWebView.mm
```

After creating the header file and the implementation file, you can start implementing them.

This is the code for the `RCTWebView.h` file, which declares the component interface.

Demo/RCTWebView/RCTWebView\.h

```
#import <React/RCTViewComponentView.h>

#import <UIKit/UIKit.h>



NS_ASSUME_NONNULL_BEGIN



@interface RCTWebView : RCTViewComponentView



// You would declare native methods you'd want to access from the view here



@end



NS_ASSUME_NONNULL_END
```

This class defines an `RCTWebView` which extends the `RCTViewComponentView` class. This is the base class for all the native components and it is provided by React Native.

The code for the implementation file (`RCTWebView.mm`) is the following:

Demo/RCTWebView/RCTWebView\.mm

```
#import "RCTWebView.h"



#import <react/renderer/components/AppSpec/ComponentDescriptors.h>

#import <react/renderer/components/AppSpec/EventEmitters.h>

#import <react/renderer/components/AppSpec/Props.h>

#import <react/renderer/components/AppSpec/RCTComponentViewHelpers.h>

#import <WebKit/WebKit.h>



using namespace facebook::react;



@interface RCTWebView () <RCTCustomWebViewViewProtocol, WKNavigationDelegate>

@end



@implementation RCTWebView {

  NSURL * _sourceURL;

  WKWebView * _webView;

}



-(instancetype)init

{

  if(self = [super init]) {

    _webView = [WKWebView new];

    _webView.navigationDelegate = self;

    [self addSubview:_webView];

  }

  return self;

}



- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps

{

  const auto &oldViewProps = *std::static_pointer_cast<CustomWebViewProps const>(_props);

  const auto &newViewProps = *std::static_pointer_cast<CustomWebViewProps const>(props);



  // Handle your props here

  if (oldViewProps.sourceURL != newViewProps.sourceURL) {

    NSString *urlString = [NSString stringWithCString:newViewProps.sourceURL.c_str() encoding:NSUTF8StringEncoding];

    _sourceURL = [NSURL URLWithString:urlString];

    if ([self urlIsValid:newViewProps.sourceURL]) {

      [_webView loadRequest:[NSURLRequest requestWithURL:_sourceURL]];

    }

  }



  [super updateProps:props oldProps:oldProps];

}



-(void)layoutSubviews

{

  [super layoutSubviews];

  _webView.frame = self.bounds;



}



#pragma mark - WKNavigationDelegate



-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{

  CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Success};

  self.eventEmitter.onScriptLoaded(result);

}



- (BOOL)urlIsValid:(std::string)propString

{

  if (propString.length() > 0 && !_sourceURL) {

    CustomWebViewEventEmitter::OnScriptLoaded result = CustomWebViewEventEmitter::OnScriptLoaded{CustomWebViewEventEmitter::OnScriptLoadedResult::Error};



    self.eventEmitter.onScriptLoaded(result);

    return NO;

  }

  return YES;

}



// Event emitter convenience method

- (const CustomWebViewEventEmitter &)eventEmitter

{

  return static_cast<const CustomWebViewEventEmitter &>(*_eventEmitter);

}



+ (ComponentDescriptorProvider)componentDescriptorProvider

{

  return concreteComponentDescriptorProvider<CustomWebViewComponentDescriptor>();

}



@end
```

```
import {Alert, StyleSheet, View} from 'react-native';

import WebView from './specs/WebViewNativeComponent';



function App(): React.JSX.Element {

  return (

    <View style={styles.container}>

      <WebView

        sourceURL="https://react.dev/"

        style={styles.webview}

        onScriptLoaded={() => {

          Alert.alert('Page Loaded');

        }}

      />

    </View>

  );

}



const styles = StyleSheet.create({

  container: {

    flex: 1,

    alignItems: 'center',

    alignContent: 'center',

  },

  webview: {

    width: '100%',

    height: '100%',

  },

});



export default App;
```

This code creates an app that uses the new `WebView` component we created to load the `react.dev` website.

The app also shows an alert when the web page is loaded.

## 4. Run your App using the WebView Component[​](#4-run-your-app-using-the-webview-component "Direct link to 4. Run your App using the WebView Component")

* Android
* iOS

```
yarn run android
```

```
yarn run ios
```

| Android | iOS |
| ------- | --- |
|         |     |

* [Creating a WebView Component](#creating-a-webview-component)
* [1. Define Specification for Codegen](#1-define-specification-for-codegen)
* [2. Configure Codegen to run](#2-configure-codegen-to-run)
* [2. Building your Native Code](#2-building-your-native-code)
* [3. Use your Native Component](#3-use-your-native-component)
* [4. Run your App using the WebView Component](#4-run-your-app-using-the-webview-component)

----
url: https://reactnative.dev/docs/progressbarandroid
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Deprecated

Use one of the [community packages](https://reactnative.directory/?search=progressbar) instead.

Android-only React component used to indicate that the app is loading or there is some activity in the app.

### Example[​](#example "Direct link to Example")

***

# Reference

## Props[​](#props "Direct link to Props")

Inherits [View Props](/docs/view#props).

### `animating`[​](#animating "Direct link to animating")

Whether to show the ProgressBar (true, the default) or hide it (false).

| Type | Required |
| ---- | -------- |
| bool | No       |

***

### `color`[​](#color "Direct link to color")

Color of the progress bar.

| Type                  | Required |
| --------------------- | -------- |
| [color](/docs/colors) | No       |

***

### `indeterminate`[​](#indeterminate "Direct link to indeterminate")

If the progress bar will show indeterminate progress. Note that this can only be false if styleAttr is Horizontal, and requires a `progress` value.

| Type              | Required |
| ----------------- | -------- |
| indeterminateType | No       |

***

### `progress`[​](#progress "Direct link to progress")

The progress value (between 0 and 1).

| Type   | Required |
| ------ | -------- |
| number | No       |

***

| Type                                                                                      | Required |
| ----------------------------------------------------------------------------------------- | -------- |
| enum('Horizontal', 'Normal', 'Small', 'Large', 'Inverse', 'SmallInverse', 'LargeInverse') | No       |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

| Type   | Required |
| ------ | -------- |
| string | No       |

----
url: https://reactnative.dev/docs/next/animated
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/animated)** (0.87).

Version: Next

The `Animated` library is designed to make animations fluid, powerful, and painless to build and maintain. `Animated` focuses on declarative relationships between inputs and outputs, configurable transforms in between, and `start`/`stop` methods to control time-based animation execution.

The core workflow for creating an animation is to create an `Animated.Value`, hook it up to one or more style attributes of an animated component, and then drive updates via animations using `Animated.timing()`.

note

Don't modify the animated value directly. You can use the [`useRef` Hook](https://react.dev/reference/react/useRef) to return a mutable ref object. This ref object's `current` property is initialized as the given argument and persists throughout the component lifecycle.

## Example[​](#example "Direct link to Example")

The following example contains a `View` which will fade in and fade out based on the animated value `fadeAnim`

Refer to the [Animations](/docs/next/animations#animated-api) guide to see additional examples of `Animated` in action.

## Overview[​](#overview "Direct link to Overview")

There are two value types you can use with `Animated`:

* [`Animated.Value()`](/docs/next/animated#value) for single values
* [`Animated.ValueXY()`](/docs/next/animated#valuexy) for vectors

`Animated.Value` can bind to style properties or other props, and can be interpolated as well. A single `Animated.Value` can drive any number of properties.

### Configuring animations[​](#configuring-animations "Direct link to Configuring animations")

`Animated` provides three types of animation types. Each animation type provides a particular animation curve that controls how your values animate from their initial value to the final value:

* [`Animated.decay()`](/docs/next/animated#decay) starts with an initial velocity and gradually slows to a stop.
* [`Animated.spring()`](/docs/next/animated#spring) provides a basic spring physics model.
* [`Animated.timing()`](/docs/next/animated#timing) animates a value over time using [easing functions](/docs/next/easing).

In most cases, you will be using `timing()`. By default, it uses a symmetric easeInOut curve that conveys the gradual acceleration of an object to full speed and concludes by gradually decelerating to a stop.

### Working with animations[​](#working-with-animations "Direct link to 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}`.

React TSX

```
Animated.timing({}).start(({finished}) => {

  /* completion callback */

});
```

### Using the native driver[​](#using-the-native-driver "Direct link to Using the native driver")

By using the native driver, we send everything about the animation to native before starting the animation, allowing native code to perform the animation on the UI thread without having to go through the bridge on every frame. Once the animation has started, the JS thread can be blocked without affecting the animation.

You can use the native driver by specifying `useNativeDriver: true` in your animation configuration. See the [Animations](/docs/next/animations#using-the-native-driver) guide to learn more.

### Animatable components[​](#animatable-components "Direct link to Animatable components")

Only animatable components can be animated. These unique components do the magic of binding the animated values to the properties, and do targeted native updates to avoid the cost of the React render and reconciliation process on every frame. They also handle cleanup on unmount so they are safe by default.

* [`createAnimatedComponent()`](/docs/next/animated#createanimatedcomponent) can be used to make a component animatable.

* [`Animated.delay()`](/docs/next/animated#delay) starts an animation after a given delay.
* [`Animated.parallel()`](/docs/next/animated#parallel) starts a number of animations at the same time.
* [`Animated.sequence()`](/docs/next/animated#sequence) starts the animations in order, waiting for each to complete before starting the next.
* [`Animated.stagger()`](/docs/next/animated#stagger) starts animations in order and in parallel, but with successive delays.

Animations can also be chained together by setting the `toValue` of one animation to be another `Animated.Value`. See [Tracking dynamic values](/docs/next/animations#tracking-dynamic-values) in the Animations guide.

By default, if one animation is stopped or interrupted, then all other animations in the group are also stopped.

### Combining animated values[​](#combining-animated-values "Direct link to Combining animated values")

You can combine two animated values via addition, subtraction, multiplication, division, or modulo to make a new animated value:

* [`Animated.add()`](/docs/next/animated#add)
* [`Animated.subtract()`](/docs/next/animated#subtract)
* [`Animated.divide()`](/docs/next/animated#divide)
* [`Animated.modulo()`](/docs/next/animated#modulo)
* [`Animated.multiply()`](/docs/next/animated#multiply)

### Interpolation[​](#interpolation "Direct link to Interpolation")

The `interpolate()` function allows input ranges to map to different output ranges. By default, it will extrapolate the curve beyond the ranges given, but you can also have it clamp the output value. It uses linear interpolation by default but also supports easing functions.

* [`interpolate()`](/docs/next/animatedvalue#interpolate)

Read more about interpolation in the [Animation](/docs/next/animations#interpolation) guide.

### Handling gestures and other events[​](#handling-gestures-and-other-events "Direct link to Handling gestures and other events")

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.

* [`Animated.event()`](/docs/next/animated#event)

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`):

React TSX

```
 onScroll={Animated.event(

   // scrollX = e.nativeEvent.contentOffset.x

   [{nativeEvent: {

        contentOffset: {

          x: scrollX

        }

      }

    }],

    {useNativeEvent: true}

 )}
```

***

# Reference

## Methods[​](#methods "Direct link to Methods")

When the given value is a ValueXY instead of a Value, each config option may be a vector of the form `{x: ..., y: ...}` instead of a scalar.

### `decay()`[​](#decay "Direct link to decay")

React TSX

```
static decay(value, config): CompositeAnimation;
```

Animates a value from an initial velocity to zero based on a decay coefficient.

Config is an object that may have the following options:

* `velocity`: Initial velocity. Required.
* `deceleration`: Rate of decay. Default 0.997.
* `isInteraction`: Whether or not this animation creates an "interaction handle". Default true.
* `useNativeDriver`: Uses the native driver when true. Required.

***

### `timing()`[​](#timing "Direct link to timing")

React TSX

```
static timing(value, config): CompositeAnimation;
```

Animates a value along a timed easing curve. The [`Easing`](/docs/next/easing) module has tons of predefined curves, or you can use your own function.

Config is an object that may have the following options:

* `duration`: Length of animation (milliseconds). Default 500.
* `easing`: Easing function to define curve. Default is `Easing.inOut(Easing.ease)`.
* `delay`: Start the animation after delay (milliseconds). Default 0.
* `isInteraction`: Whether or not this animation creates an "interaction handle". Default true.
* `useNativeDriver`: Uses the native driver when true. Required.

***

### `spring()`[​](#spring "Direct link to spring")

React TSX

```
static spring(value, config): CompositeAnimation;
```

***

### `add()`[​](#add "Direct link to add")

React TSX

```
static add(a: Animated, b: Animated): AnimatedAddition;
```

Creates a new Animated value composed from two Animated values added together.

***

### `subtract()`[​](#subtract "Direct link to subtract")

React TSX

```
static subtract(a: Animated, b: Animated): AnimatedSubtraction;
```

Creates a new Animated value composed by subtracting the second Animated value from the first Animated value.

***

### `divide()`[​](#divide "Direct link to divide")

React TSX

```
static divide(a: Animated, b: Animated): AnimatedDivision;
```

Creates a new Animated value composed by dividing the first Animated value by the second Animated value.

***

### `multiply()`[​](#multiply "Direct link to multiply")

React TSX

```
static multiply(a: Animated, b: Animated): AnimatedMultiplication;
```

Creates a new Animated value composed from two Animated values multiplied together.

***

### `modulo()`[​](#modulo "Direct link to modulo")

React TSX

```
static modulo(a: Animated, modulus: number): AnimatedModulo;
```

Creates a new Animated value that is the (non-negative) modulo of the provided Animated value

***

### `diffClamp()`[​](#diffclamp "Direct link to diffclamp")

React TSX

```
static diffClamp(a: Animated, min: number, max: number): AnimatedDiffClamp;
```

Create a new Animated value that is limited between 2 values. It uses the difference between the last value so even if the value is far from the bounds it will start changing when the value starts getting closer again. (`value = clamp(value + diff, min, max)`).

This is useful with scroll events, for example, to show the navbar when scrolling up and to hide it when scrolling down.

***

### `delay()`[​](#delay "Direct link to delay")

React TSX

```
static delay(time: number): CompositeAnimation;
```

Starts an animation after the given delay.

***

### `sequence()`[​](#sequence "Direct link to sequence")

React TSX

```
static sequence(animations: CompositeAnimation[]): CompositeAnimation;
```

Starts an array of animations in order, waiting for each to complete before starting the next. If the current running animation is stopped, no following animations will be started.

***

### `parallel()`[​](#parallel "Direct link to parallel")

React TSX

```
static parallel(

  animations: CompositeAnimation[],

  config?: ParallelConfig

): CompositeAnimation;
```

Starts an array of animations all at the same time. By default, if one of the animations is stopped, they will all be stopped. You can override this with the `stopTogether` flag.

***

### `stagger()`[​](#stagger "Direct link to stagger")

React TSX

```
static stagger(

  time: number,

  animations: CompositeAnimation[]

): CompositeAnimation;
```

Array of animations may run in parallel (overlap), but are started in sequence with successive delays. Nice for doing trailing effects.

***

### `loop()`[​](#loop "Direct link to loop")

React TSX

```
static loop(

  animation: CompositeAnimation[],

  config?: LoopAnimationConfig

): CompositeAnimation;
```

Loops a given animation continuously, so that each time it reaches the end, it resets and begins again from the start. Will loop without blocking the JS thread if the child animation is set to `useNativeDriver: true`. In addition, loops can prevent `VirtualizedList`-based components from rendering more rows while the animation is running. You can pass `isInteraction: false` in the child animation config to fix this.

Config is an object that may have the following options:

* `iterations`: Number of times the animation should loop. Default `-1` (infinite).

***

### `event()`[​](#event "Direct link to event")

React TSX

```
static event(

  argMapping: Mapping[],

  config?: EventConfig

): (...args: any[]) => void;
```

Takes an array of mappings and extracts values from each arg accordingly, then calls `setValue` on the mapped outputs. e.g.

React TSX

```
onScroll={Animated.event(

  [{nativeEvent: {contentOffset: {x: this._scrollX}}}],

  {listener: (event: ScrollEvent) => console.log(event)}, // Optional async listener

)}

 ...

onPanResponderMove: Animated.event(

  [

    null, // raw event arg ignored

    {dx: this._panX},

  ], // gestureState arg

  {

    listener: (

      event: GestureResponderEvent,

      gestureState: PanResponderGestureState

    ) => console.log(event, gestureState),

  } // Optional async listener

);
```

Config is an object that may have the following options:

* `listener`: Optional async listener.
* `useNativeDriver`: Uses the native driver when true. Required.

***

### `forkEvent()`[​](#forkevent "Direct link to forkevent")

React JSX

```
static forkEvent(event: AnimatedEvent, listener: Function): AnimatedEvent;
```

Advanced imperative API for snooping on animated events that are passed in through props. It permits to add a new javascript listener to an existing `AnimatedEvent`. If `animatedEvent` is a javascript listener, it will merge the 2 listeners into a single one, and if `animatedEvent` is null/undefined, it will assign the javascript listener directly. Use values directly where possible.

***

### `unforkEvent()`[​](#unforkevent "Direct link to unforkevent")

React JSX

```
static unforkEvent(event: AnimatedEvent, listener: Function);
```

***

### `start()`[​](#start "Direct link to start")

React TSX

```
static start(callback?: (result: {finished: boolean}) => void);
```

Animations are started by calling start() on your animation. start() takes a completion callback that will be called when the animation is done or when the animation is done because stop() was called on it before it could finish.

**Parameters:**

| Name     | Type                                    | Required | Description                                                                                                                                                     |
| -------- | --------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 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:

React TSX

```
Animated.timing({}).start(({finished}) => {

  /* completion callback */

});
```

***

### `stop()`[​](#stop "Direct link to stop")

React TSX

```
static stop();
```

Stops any running animation.

***

### `reset()`[​](#reset "Direct link to reset")

React TSX

```
static reset();
```

Stops any running animation and resets the value to its original.

## Properties[​](#properties "Direct link to Properties")

### `Value`[​](#value "Direct link to value")

Standard value class for driving animations. Typically initialized with `useAnimatedValue(0);` or `new Animated.Value(0);` in class components.

You can read more about `Animated.Value` API on the separate [page](/docs/next/animatedvalue).

***

### `ValueXY`[​](#valuexy "Direct link to valuexy")

2D value class for driving 2D animations, such as pan gestures.

You can read more about `Animated.ValueXY` API on the separate [page](/docs/next/animatedvaluexy).

***

### `Interpolation`[​](#interpolation-1 "Direct link to interpolation-1")

Exported to use the Interpolation type in flow.

***

### `Node`[​](#node "Direct link to node")

Exported for ease of type checking. All animated values derive from this class.

***

### `createAnimatedComponent`[​](#createanimatedcomponent "Direct link to createanimatedcomponent")

Make any React component Animatable. Used to create `Animated.View`, etc.

***

----
url: https://reactnative.dev/docs/headless-js-android
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.

## The JS API[​](#the-js-api "Direct link to The JS API")

A task is an async function that you register on `AppRegistry`, similar to registering React applications:

React TSX

```
import {AppRegistry} from 'react-native';

AppRegistry.registerHeadlessTask('SomeTaskName', () =>

  require('SomeTaskName'),

);
```

Then, in `SomeTaskName.js`:

React TSX

```
module.exports = async taskData => {

  // do stuff

};
```

You can do anything in your task such as network requests, timers and so on, as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved), React Native will go into "paused" mode (unless there are other tasks running, or there is a foreground app).

## The Platform API[​](#the-platform-api "Direct link to The Platform API")

Yes, this does still require some native code, but it's pretty thin. You need to extend `HeadlessJsTaskService` and override `getTaskConfig`, e.g.:

* Java
* Kotlin

Java

```
package com.your_application_name;



import android.content.Intent;

import android.os.Bundle;

import com.facebook.react.HeadlessJsTaskService;

import com.facebook.react.bridge.Arguments;

import com.facebook.react.jstasks.HeadlessJsTaskConfig;

import javax.annotation.Nullable;



public class MyTaskService extends HeadlessJsTaskService {



  @Override

  protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {

    Bundle extras = intent.getExtras();

    if (extras != null) {

      return new HeadlessJsTaskConfig(

          "SomeTaskName",

          Arguments.fromBundle(extras),

          5000, // timeout in milliseconds for the task

          false // optional: defines whether or not the task is allowed in foreground. Default is false

        );

    }

    return null;

  }

}
```

Kotlin

```
package com.your_application_name;



import android.content.Intent

import com.facebook.react.HeadlessJsTaskService

import com.facebook.react.bridge.Arguments

import com.facebook.react.jstasks.HeadlessJsTaskConfig



class MyTaskService : HeadlessJsTaskService() {

    override fun getTaskConfig(intent: Intent?): HeadlessJsTaskConfig? {

        return intent.extras?.let {

            HeadlessJsTaskConfig(

                "SomeTaskName",

                Arguments.fromBundle(it),

                5000, // timeout for the task

                false // optional: defines whether or not the task is allowed in foreground.

                // Default is false

            )

        }

    }

}
```

Then add the service to your `AndroidManifest.xml` file inside the `application` tag:

XML

```
<service android:name="com.example.MyTaskService" />
```

Now, whenever you [start your service](https://developer.android.com/reference/android/content/Context.html#startService\(android.content.Intent\)), e.g. as a periodic task or in response to some system event / broadcast, JS will spin up, run your task, then spin down.

Example:

* Java
* Kotlin

Java

```
Intent service = new Intent(getApplicationContext(), MyTaskService.class);

Bundle bundle = new Bundle();



bundle.putString("foo", "bar");

service.putExtras(bundle);



getApplicationContext().startForegroundService(service);
```

Kotlin

```
val service = Intent(applicationContext, MyTaskService::class.java)

val bundle = Bundle()



bundle.putString("foo", "bar")



service.putExtras(bundle)



applicationContext.startForegroundService(service)
```

## Retries[​](#retries "Direct link to Retries")

By default, the headless JS task will not perform any retries. In order to do so, you need to create a `HeadlessJsRetryPolicy` and throw a specific `Error`.

`LinearCountingRetryPolicy` is an implementation of `HeadlessJsRetryPolicy` that allows you to specify a maximum number of retries with a fixed delay between each attempt. If that does not suit your needs then you can implement your own `HeadlessJsRetryPolicy`. These policies can be passed as an extra argument to the `HeadlessJsTaskConfig` constructor, e.g.

* Java
* Kotlin

Java

```
HeadlessJsRetryPolicy retryPolicy = new LinearCountingRetryPolicy(

  3, // Max number of retry attempts

  1000 // Delay between each retry attempt

);



return new HeadlessJsTaskConfig(

  'SomeTaskName',

  Arguments.fromBundle(extras),

  5000,

  false,

  retryPolicy

);
```

Kotlin

```
val retryPolicy: HeadlessJsTaskRetryPolicy =

    LinearCountingRetryPolicy(

        3, // Max number of retry attempts

        1000 // Delay between each retry attempt

    )



return HeadlessJsTaskConfig("SomeTaskName", Arguments.fromBundle(extras), 5000, false, retryPolicy)
```

A retry attempt will only be made when a specific `Error` is thrown. Inside a headless JS task, you can import the error and throw it when a retry attempt is required.

Example:

React TSX

```
import {HeadlessJsTaskError} from 'HeadlessJsTask';



module.exports = async taskData => {

  const condition = ...;

  if (!condition) {

    throw new HeadlessJsTaskError();

  }

};
```

```
<receiver android:name=".NetworkChangeReceiver" >

  <intent-filter>

    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

  </intent-filter>

</receiver>
```

Broadcast receiver then handles intent that was broadcasted in onReceive function. This is a great place to check whether your app is on foreground or not. If app is not on foreground we can prepare our intent to be started, with no information or additional information bundled using `putExtra` (keep in mind bundle can handle only parcelable values). In the end service is started and wakelock is acquired.

* Java
* Kotlin

Java

```
import android.app.ActivityManager;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.net.ConnectivityManager;

import android.net.Network;

import android.net.NetworkCapabilities;

import android.net.NetworkInfo;

import android.os.Build;



import com.facebook.react.HeadlessJsTaskService;



public class NetworkChangeReceiver extends BroadcastReceiver {



    @Override

    public void onReceive(final Context context, final Intent intent) {

        /**

         This part will be called every time network connection is changed

         e.g. Connected -> Not Connected

         **/

        if (!isAppOnForeground((context))) {

            /**

             We will start our service and send extra info about

             network connections

             **/

            boolean hasInternet = isNetworkAvailable(context);

            Intent serviceIntent = new Intent(context, MyTaskService.class);

            serviceIntent.putExtra("hasInternet", hasInternet);

            context.startForegroundService(serviceIntent);

            HeadlessJsTaskService.acquireWakeLockNow(context);

        }

    }



    private boolean isAppOnForeground(Context context) {

        /**

         We need to check if app is in foreground otherwise the app will crash.

         https://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not

         **/

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningAppProcessInfo> appProcesses =

                activityManager.getRunningAppProcesses();

        if (appProcesses == null) {

            return false;

        }

        final String packageName = context.getPackageName();

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {

            if (appProcess.importance ==

                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&

                    appProcess.processName.equals(packageName)) {

                return true;

            }

        }

        return false;

    }



    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager cm = (ConnectivityManager)

                context.getSystemService(Context.CONNECTIVITY_SERVICE);



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            Network networkCapabilities = cm.getActiveNetwork();



            if(networkCapabilities == null) {

                return false;

            }



            NetworkCapabilities actNw = cm.getNetworkCapabilities(networkCapabilities);



            if(actNw == null) {

                return false;

            }



            if(actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {

                return true;

            }



            return false;

        }



        // deprecated in API level 29

        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        return (netInfo != null && netInfo.isConnected());

    }

}
```

Kotlin

```
import android.app.ActivityManager

import android.app.ActivityManager.RunningAppProcessInfo

import android.content.BroadcastReceiver

import android.content.Context

import android.content.Intent

import android.net.ConnectivityManager

import android.net.NetworkCapabilities

import android.os.Build

import com.facebook.react.HeadlessJsTaskService



class NetworkChangeReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent?) {

        /**

         * This part will be called every time network connection is changed e.g. Connected -> Not

         * Connected

         */

        if (!isAppOnForeground(context)) {

            /** We will start our service and send extra info about network connections */

            val hasInternet = isNetworkAvailable(context)

            val serviceIntent = Intent(context, MyTaskService::class.java)

            serviceIntent.putExtra("hasInternet", hasInternet)

            context.startForegroundService(serviceIntent)

            HeadlessJsTaskService.acquireWakeLockNow(context)

        }

    }



    private fun isAppOnForeground(context: Context): Boolean {

        /**

         * We need to check if app is in foreground otherwise the app will crash.

         * https://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not

         */

        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

        val appProcesses = activityManager.runningAppProcesses ?: return false

        val packageName: String = context.getPackageName()

        for (appProcess in appProcesses) {

            if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&

                    appProcess.processName == packageName

            ) {

                return true

            }

        }

        return false

    }



    companion object {

        fun isNetworkAvailable(context: Context): Boolean {

            val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

            var result = false



            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                val networkCapabilities = cm.activeNetwork ?: return false



                val actNw = cm.getNetworkCapabilities(networkCapabilities) ?: return false



                result =

                    when {

                        actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true

                        actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true

                        actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true

                        else -> false

                    }



                return result

            } else {

                cm.run {

                    // deprecated in API level 29

                    cm.activeNetworkInfo?.run {

                        result =

                            when (type) {

                                ConnectivityManager.TYPE_WIFI -> true

                                ConnectivityManager.TYPE_MOBILE -> true

                                ConnectivityManager.TYPE_ETHERNET -> true

                                else -> false

                            }

                    }

                }

            }

            return result

        }

    }

}
```

* [The JS API](#the-js-api)
* [The Platform API](#the-platform-api)
* [Retries](#retries)
* [Caveats](#caveats)
* [Example Usage](#example-usage)

----
url: https://reactnative.dev/docs/next/platform-specific-code
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/platform-specific-code)** (0.87).

Version: Next

When building a cross-platform app, you'll want to re-use as much code as possible. Scenarios may arise where it makes sense for the code to be different, for example you may want to implement separate visual components for Android and iOS.

React Native provides two ways to organize your code and separate it by platform:

* Using the [`Platform` module](/docs/next/platform-specific-code#platform-module).
* Using [platform-specific file extensions](/docs/next/platform-specific-code#platform-specific-extensions).

Certain components may have properties that work on one platform only. All of these props are annotated with `@platform` and have a small badge next to them on the website.

## Platform module[​](#platform-module "Direct link to Platform module")

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.

React TSX

```
import {Platform, StyleSheet} from 'react-native';



const styles = StyleSheet.create({

  height: Platform.OS === 'ios' ? 200 : 100,

});
```

`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.

React TSX

```
import {Platform, StyleSheet} from 'react-native';



const styles = StyleSheet.create({

  container: {

    flex: 1,

    ...Platform.select({

      ios: {

        backgroundColor: 'red',

      },

      android: {

        backgroundColor: 'green',

      },

      default: {

        // other platforms, web for example

        backgroundColor: 'blue',

      },

    }),

  },

});
```

This will result in a container having `flex: 1` on all platforms, a red background color on iOS, a green background color on Android, and a blue background color on other platforms.

Since it accepts `any` value, you can also use it to return platform-specific components, like below:

React TSX

```
const Component = Platform.select({

  ios: () => require('ComponentIOS'),

  android: () => require('ComponentAndroid'),

})();



<Component />;
```

React TSX

```
const Component = Platform.select({

  native: () => require('ComponentForNative'),

  default: () => require('ComponentForWeb'),

})();



<Component />;
```

### Detecting the Android versionAndroid[​](#detecting-the-android-version-android "Direct link to detecting-the-android-version-android")

On Android, the `Platform` module can also be used to detect the version of the Android Platform in which the app is running:

React TSX

```
import {Platform} from 'react-native';



if (Platform.Version === 25) {

  console.log('Running on Nougat!');

}
```

**Note**: `Version` is set to the Android API version not the Android OS version. To find a mapping please refer to [Android Version History](https://en.wikipedia.org/wiki/Android_version_history#Overview).

### Detecting the iOS versioniOS[​](#detecting-the-ios-version-ios "Direct link to detecting-the-ios-version-ios")

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:

React TSX

```
import {Platform} from 'react-native';



const majorVersionIOS = parseInt(Platform.Version, 10);

if (majorVersionIOS <= 9) {

  console.log('Work around a change in behavior');

}
```

## Platform-specific extensions[​](#platform-specific-extensions "Direct link to Platform-specific extensions")

When your platform-specific code is more complex, you should consider splitting the code out into separate files. React Native will detect when a file has a `.ios.` or `.android.` extension and load the relevant platform file when required from other components.

For example, say you have the following files in your project:

```
BigButton.ios.js

BigButton.android.js
```

You can then import the component as follows:

React TSX

```
import BigButton from './BigButton';
```

React Native will automatically pick up the right file based on the running platform.

## Native-specific extensions (i.e. sharing code with NodeJS and Web)[​](#native-specific-extensions-ie-sharing-code-with-nodejs-and-web "Direct link to Native-specific extensions (i.e. sharing code with NodeJS and Web)")

You can also use the `.native.js` extension when a module needs to be shared between NodeJS/Web and React Native but it has no Android/iOS differences. This is especially useful for projects that have common code shared among React Native and ReactJS.

For example, say you have the following files in your project:

```
Container.js # picked up by webpack, Rollup or any other Web bundler

Container.native.js # picked up by the React Native bundler for both Android and iOS (Metro)
```

You can still import it without the `.native` extension, as follows:

React TSX

```
import Container from './Container';
```

**Pro tip:** Configure your Web bundler to ignore `.native.js` extensions in order to avoid having unused code in your production bundle, thus reducing the final bundle size.

* [Platform module](#platform-module)

  * [Detecting the Android version](#detecting-the-android-version-android)

    [Android](#detecting-the-android-version-android)
  * [Detecting the iOS version](#detecting-the-ios-version-ios)

    [iOS](#detecting-the-ios-version-ios)

* [Platform-specific extensions](#platform-specific-extensions)

* [Native-specific extensions (i.e. sharing code with NodeJS and Web)](#native-specific-extensions-ie-sharing-code-with-nodejs-and-web)

----
url: https://reactnative.dev/docs/handling-touches
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Users interact with mobile apps mainly through touch. They can use a combination of gestures, such as tapping on a button, scrolling a list, or zooming on a map. React Native provides components to handle all sorts of common gestures, as well as a comprehensive [gesture responder system](/docs/gesture-responder-system) to allow for more advanced gesture recognition, but the one component you will most likely be interested in is the basic Button.

## Displaying a basic button[​](#displaying-a-basic-button "Direct link to Displaying a basic button")

[Button](/docs/button) provides a basic button component that is rendered nicely on all platforms. The minimal example to display a button looks like this:

React TSX

```
<Button

  onPress={() => {

    console.log('You tapped the button!');

  }}

  title="Press Me"

/>
```

This will render a blue label on iOS, and a blue rounded rectangle with light text on Android. Pressing the button will call the "onPress" function, which in this case displays an alert popup. If you like, you can specify a "color" prop to change the color of your button.

Go ahead and play around with the `Button` component using the example below. You can select which platform your app is previewed in by clicking on the toggle in the bottom right and then clicking on "Tap to Play" to preview the app.

## Touchables[​](#touchables "Direct link to Touchables")

If the basic button doesn't look right for your app, you can build your own button using any of the "Touchable" components provided by React Native. These components provide the capability to capture tapping gestures and can display feedback when a gesture is recognized. However, these components do not provide any default styling, so you will need to do a bit of work to get them looking nice in your app.

Which "Touchable" component you use will depend on what kind of feedback you want to provide:

* Generally, you can use [**TouchableHighlight**](/docs/touchablehighlight) anywhere you would use a button or link on web. The view's background will be darkened when the user presses down on the button.

* You may consider using [**TouchableNativeFeedback**](/docs/touchablenativefeedback) on Android to display ink surface reaction ripples that respond to the user's touch.

* [**TouchableOpacity**](/docs/touchableopacity) can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down.

* If you need to handle a tap gesture but you don't want any feedback to be displayed, use [**TouchableWithoutFeedback**](/docs/touchablewithoutfeedback).

In some cases, you may want to detect when a user presses and holds a view for a set amount of time. These long presses can be handled by passing a function to the `onLongPress` props of any of the "Touchable" components.

Let's see all of these in action:

## Scrolling and swiping[​](#scrolling-and-swiping "Direct link to Scrolling and swiping")

Gestures commonly used on devices with touchable screens include swipes and pans. These allow the user to scroll through a list of items, or swipe through pages of content. For these, check out the [ScrollView](/docs/scrollview) Core Component.

## Known issues[​](#known-issues "Direct link to Known issues")

* [react-native#29308](https://github.com/react/react-native/issues/29308#issuecomment-792864162): The touch area never extends past the parent view bounds and on Android negative margin is not supported.

- [Displaying a basic button](#displaying-a-basic-button)
- [Touchables](#touchables)
- [Scrolling and swiping](#scrolling-and-swiping)
- [Known issues](#known-issues)

----
url: https://reactnative.dev/docs/legacy/native-modules-ios
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

info

Native Module and Native Components are our stable technologies used by the legacy architecture. They will be deprecated in the future when the New Architecture will be stable. The New Architecture uses [Turbo Native Module](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/turbo-modules.md) and [Fabric Native Components](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/fabric-native-components.md) to achieve similar results.

Welcome to Native Modules for iOS. Please start by reading the [Native Modules Intro](/docs/legacy/native-modules-intro) for an intro to what native modules are.

```
//  RCTCalendarModule.h

#import <React/RCTBridgeModule.h>

@interface RCTCalendarModule : NSObject <RCTBridgeModule>

@end
```

You can use any name that fits the native module you are building. Name the class `RCTCalendarModule` since you are creating a calendar native module. Since ObjC does not have language-level support for namespaces like Java or C++, convention is to prepend the class name with a substring. This could be an abbreviation of your application name or your infra name. RCT, in this example, refers to React.

As you can see below, the CalendarModule class implements the `RCTBridgeModule` protocol. A native module is an Objective-C class that implements the `RCTBridgeModule` protocol.

Next up, let’s start implementing the native module. Create the corresponding implementation file using cocoa touch class in xcode, `RCTCalendarModule.m`, in the same folder and include the following content:

Objective-C

```
// RCTCalendarModule.m

#import "RCTCalendarModule.h"



@implementation RCTCalendarModule



// To export a module named RCTCalendarModule

RCT_EXPORT_MODULE();



@end
```

### Module Name[​](#module-name "Direct link to Module Name")

For now, your `RCTCalendarModule.m` native module only includes a `RCT_EXPORT_MODULE` macro, which exports and registers the native module class with React Native. The `RCT_EXPORT_MODULE` macro also takes an optional argument that specifies the name that the module will be accessible as in your JavaScript code.

This argument is not a string literal. In the example below `RCT_EXPORT_MODULE(CalendarModuleFoo)` is passed, not `RCT_EXPORT_MODULE("CalendarModuleFoo")`.

Objective-C

```
// To export a module named CalendarModuleFoo

RCT_EXPORT_MODULE(CalendarModuleFoo);
```

The native module can then be accessed in JS like this:

React TSX

```
const {CalendarModuleFoo} = ReactNative.NativeModules;
```

If you do not specify a name, the JavaScript module name will match the Objective-C class name, with any "RCT" or "RK" prefixes removed.

Let's follow the example below and call `RCT_EXPORT_MODULE` without any arguments. As a result, the module will be exposed to React Native using the name `CalendarModule`, since that is the Objective-C class name, with RCT removed.

Objective-C

```
// Without passing in a name this will export the native module name as the Objective-C class name with “RCT” removed

RCT_EXPORT_MODULE();
```

The native module can then be accessed in JS like this:

React TSX

```
const {CalendarModule} = ReactNative.NativeModules;
```

### Export a Native Method to JavaScript[​](#export-a-native-method-to-javascript "Direct link to Export a Native Method to JavaScript")

React Native will not expose any methods in a native module to JavaScript unless explicitly told to. This can be done using the `RCT_EXPORT_METHOD` macro. Methods written in the `RCT_EXPORT_METHOD` macro are asynchronous and the return type is therefore always void. In order to pass a result from a `RCT_EXPORT_METHOD` method to JavaScript you can use callbacks or emit events (covered below). Let’s go ahead and set up a native method for our `CalendarModule` native module using the `RCT_EXPORT_METHOD` macro. Call it `createCalendarEvent()` and for now have it take in name and location arguments as strings. Argument type options will be covered shortly.

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)name location:(NSString *)location)

{

}
```

note

Please note that the `RCT_EXPORT_METHOD` macro will not be necessary with TurboModules unless your method relies on RCT argument conversion (see argument types below). Ultimately, React Native will remove `RCT_EXPORT_MACRO,` so we discourage people from using `RCTConvert`. Instead, you can do the argument conversion within the method body.

Before you build out the `createCalendarEvent()` method’s functionality, add a console log in the method so you can confirm it has been invoked from JavaScript in your React Native application. Use the `RCTLog` APIs from React. Let’s import that header at the top of your file and then add the log call.

Objective-C

```
#import <React/RCTLog.h>

RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)name location:(NSString *)location)

{

 RCTLogInfo(@"Pretending to create an event %@ at %@", name, location);

}
```

### Synchronous Methods[​](#synchronous-methods "Direct link to Synchronous Methods")

You can use the `RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD` to create a synchronous native method.

Objective-C

```
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getName)

{

return [[UIDevice currentDevice] name];

}
```

The return type of this method must be of object type (id) and should be serializable to JSON. This means that the hook can only return nil or JSON values (e.g. NSNumber, NSString, NSArray, NSDictionary).

At the moment, we do not recommend using synchronous methods, since calling methods synchronously can have strong performance penalties and introduce threading-related bugs to your native modules. Additionally, please note that if you choose to use `RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD`, your app can no longer use the Google Chrome debugger. This is because synchronous methods require the JS VM to share memory with the app. For the Google Chrome debugger, React Native runs inside the JS VM in Google Chrome, and communicates asynchronously with the mobile devices via WebSockets.

### Test What You Have Built[​](#test-what-you-have-built "Direct link to Test What You Have Built")

At this point you have set up the basic scaffolding for your native module in iOS. Test that out by accessing the native module and invoking it’s exported method in JavaScript.

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.

React TSX

```
import {Button} from 'react-native';



const NewModuleButton = () => {

  const onPress = () => {

    console.log('We will invoke the native module here!');

  };



  return (

    <Button

      title="Click to invoke your native module!"

      color="#841584"

      onPress={onPress}

    />

  );

};



export default NewModuleButton;
```

In order to access your native module from JavaScript you need to first import `NativeModules` from React Native:

React TSX

```
import {NativeModules} from 'react-native';
```

You can then access the `CalendarModule` native module off of `NativeModules`.

React 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`:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEvent('testName', 'testLocation');

};
```

The final step is to rebuild the React Native app so that you can have the latest native code (with your new native module!) available. In your command line, where the react native application is located, run the following :

* npm
* Yarn

```
npm run ios
```

```
yarn ios
```

```
/**

* This exposes the native CalendarModule module as a JS module. This has a

* function 'createCalendarEvent' which takes the following parameters:



* 1. String name: A string representing the name of the event

* 2. String location: A string representing the location of the event

*/

import {NativeModules} from 'react-native';

const {CalendarModule} = NativeModules;

export default CalendarModule;
```

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:

React TSX

```
/**

 * This exposes the native CalendarModule module as a JS module. This has a

 * function 'createCalendarEvent' which takes the following parameters:

 *

 * 1. String name: A string representing the name of the event

 * 2. String location: A string representing the location of the event

 */

import {NativeModules} from 'react-native';

const {CalendarModule} = NativeModules;

interface CalendarInterface {

  createCalendarEvent(name: string, location: string): void;

}

export default CalendarModule as CalendarInterface;
```

In your other JavaScript files you can access the native module and invoke its method like this:

React TSX

```
import NativeCalendarModule from './NativeCalendarModule';

NativeCalendarModule.createCalendarEvent('foo', 'bar');
```

note

This assumes that the place you are importing `CalendarModule` is in the same hierarchy as `NativeCalendarModule.js`. Please update the relative import as necessary.

### Argument Types[​](#argument-types "Direct link to Argument Types")

When a native module method is invoked in JavaScript, React Native converts the arguments from JS objects to their Objective-C/Swift object analogues. So for example, if your Objective-C Native Module method accepts a NSNumber, in JS you need to call the method with a number. React Native will handle the conversion for you. Below is a list of the argument types supported for native module methods and the JavaScript equivalents they map to.

| Objective-C                                   | JavaScript         |
| --------------------------------------------- | ------------------ |
| NSString                                      | string, ?string    |
| BOOL                                          | boolean            |
| double                                        | number             |
| NSNumber                                      | ?number            |
| NSArray                                       | Array, ?Array      |
| NSDictionary                                  | Object, ?Object    |
| RCTResponseSenderBlock                        | Function (success) |
| RCTResponseSenderBlock, RCTResponseErrorBlock | Function (failure) |
| RCTPromiseResolveBlock, RCTPromiseRejectBlock | Promise            |

```
- (NSDictionary *)constantsToExport

{

 return @{ @"DEFAULT_EVENT_NAME": @"New Event" };

}
```

The constant can then be accessed by invoking `getConstants()` on the native module in JS like so:

React TSX

```
const {DEFAULT_EVENT_NAME} = CalendarModule.getConstants();

console.log(DEFAULT_EVENT_NAME);
```

```
RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)title

                location:(NSString *)location

                myCallback:(RCTResponseSenderBlock)callback)
```

You can then invoke the callback in your native function, providing whatever result you want to pass to JavaScript in an array. Note that `RCTResponseSenderBlock` accepts only one argument - an array of parameters to pass to the JavaScript callback. Below you will pass back the ID of an event created in an earlier call.

info

It is important to highlight that the callback is not invoked immediately after the native function completes—remember the communication is asynchronous.

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)title location:(NSString *)location callback: (RCTResponseSenderBlock)callback)

{

 NSInteger eventId = ...

 callback(@[@(eventId)]);



 RCTLogInfo(@"Pretending to create an event %@ at %@", title, location);

}
```

This method could then be accessed in JavaScript using the following:

React TSX

```
const onSubmit = () => {

  CalendarModule.createCalendarEvent(

    'Party',

    '04-12-2020',

    eventId => {

      console.log(`Created a new event with id ${eventId}`);

    },

  );

};
```

A native module is supposed to invoke its callback only once. It can, however, store the callback and invoke it later. This pattern is often used to wrap iOS APIs that require delegates— see [`RCTAlertManager`](https://github.com/react/react-native/blob/main/packages/react-native/React/CoreModules/RCTAlertManager.mm) for an example. If the callback is never invoked, some memory is leaked.

There are two approaches to error handling with callbacks. The first is to follow Node’s convention and treat the first argument passed to the callback array as an error object.

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEventCallback:(NSString *)title location:(NSString *)location callback: (RCTResponseSenderBlock)callback)

{

  NSNumber *eventId = [NSNumber numberWithInt:123];

  callback(@[[NSNull null], eventId]);

}
```

In JavaScript, you can then check the first argument to see if an error was passed through:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEventCallback(

    'testName',

    'testLocation',

    (error, eventId) => {

      if (error) {

        console.error(`Error found! ${error}`);

      }

      console.log(`event id ${eventId} returned`);

    },

  );

};
```

Another option is to use two separate callbacks: onFailure and onSuccess.

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEventCallback:(NSString *)title

                  location:(NSString *)location

                  errorCallback: (RCTResponseSenderBlock)errorCallback

                  successCallback: (RCTResponseSenderBlock)successCallback)

{

  @try {

    NSNumber *eventId = [NSNumber numberWithInt:123];

    successCallback(@[eventId]);

  }



  @catch ( NSException *e ) {

    errorCallback(@[e]);

  }

}
```

Then in JavaScript you can add a separate callback for error and success responses:

React TSX

```
const onPress = () => {

  CalendarModule.createCalendarEventCallback(

    'testName',

    'testLocation',

    error => {

      console.error(`Error found! ${error}`);

    },

    eventId => {

      console.log(`event id ${eventId} returned`);

    },

  );

};
```

If you want to pass error-like objects to JavaScript, use `RCTMakeError` from [`RCTUtils.h.`](https://github.com/react/react-native/blob/main/packages/react-native/React/Base/RCTUtils.h) Right now this only passes an Error-shaped dictionary to JavaScript, but React Native aims to automatically generate real JavaScript Error objects in the future. You can also provide a `RCTResponseErrorBlock` argument, which is used for error callbacks and accepts an `NSError \* object`. Please note that this argument type will not be supported with TurboModules.

### Promises[​](#promises "Direct link to Promises")

Native modules can also fulfill a promise, which can simplify your JavaScript, especially when using ES2016's `async/await` syntax. When the last parameter of a native module method is a `RCTPromiseResolveBlock` and `RCTPromiseRejectBlock`, its corresponding JS method will return a JS Promise object.

Refactoring the above code to use a promise instead of callbacks looks like this:

Objective-C

```
RCT_EXPORT_METHOD(createCalendarEvent:(NSString *)title

                 location:(NSString *)location

                 resolver:(RCTPromiseResolveBlock)resolve

                 rejecter:(RCTPromiseRejectBlock)reject)

{

 NSInteger eventId = createCalendarEvent();

 if (eventId) {

    resolve(@(eventId));

  } else {

    reject(@"event_failure", @"no event id returned", nil);

  }

}
```

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:

React TSX

```
const onSubmit = async () => {

  try {

    const eventId = await CalendarModule.createCalendarEvent(

      'Party',

      'my house',

    );

    console.log(`Created a new event with id ${eventId}`);

  } catch (e) {

    console.error(e);

  }

};
```

### Sending Events to JavaScript[​](#sending-events-to-javascript "Direct link to Sending Events to JavaScript")

Native modules can signal events to JavaScript without being invoked directly. For example, you might want to signal to JavaScript a reminder that a calendar event from the native iOS calendar app will occur soon. The preferred way to do this is to subclass `RCTEventEmitter`, implement `supportedEvents` and call self `sendEventWithName`:

Update your header class to import `RCTEventEmitter` and subclass `RCTEventEmitter`:

Objective-C

```
//  CalendarModule.h



#import <React/RCTBridgeModule.h>

#import <React/RCTEventEmitter.h>



@interface CalendarModule : RCTEventEmitter <RCTBridgeModule>

@end
```

JavaScript code can subscribe to these events by creating a new `NativeEventEmitter` instance around your module.

You will receive a warning if you expend resources unnecessarily by emitting an event while there are no listeners. To avoid this, and to optimize your module's workload (e.g. by unsubscribing from upstream notifications or pausing background tasks), you can override `startObserving` and `stopObserving` in your `RCTEventEmitter` subclass.

Objective-C

```
@implementation CalendarModule

{

  bool hasListeners;

}



// Will be called when this module's first listener is added.

-(void)startObserving {

    hasListeners = YES;

    // Set up any upstream listeners or background tasks as necessary

}



// Will be called when this module's last listener is removed, or on dealloc.

-(void)stopObserving {

    hasListeners = NO;

    // Remove upstream listeners, stop unnecessary background tasks

}



- (void)calendarEventReminderReceived:(NSNotification *)notification

{

  NSString *eventName = notification.userInfo[@"name"];

  if (hasListeners) {// Only send events if anyone is listening

    [self sendEventWithName:@"EventReminder" body:@{@"name": eventName}];

  }

}
```

### Threading[​](#threading "Direct link to Threading")

Unless the native module provides its own method queue, it shouldn't make any assumptions about what thread it's being called on. Currently, if a native module doesn't provide a method queue, React Native will create a separate GCD queue for it and invoke its methods there. Please note that this is an implementation detail and might change. If you want to explicitly provide a method queue for a native module, override the `(dispatch_queue_t) methodQueue` method in the native module. For example, if it needs to use a main-thread-only iOS API, it should specify this via:

Objective-C

```
- (dispatch_queue_t)methodQueue

{

  return dispatch_get_main_queue();

}
```

Similarly, if an operation may take a long time to complete, the native module can specify its own queue to run operations on. Again, currently React Native will provide a separate method queue for your native module, but this is an implementation detail you should not rely on. If you don't provide your own method queue, in the future, your native module's long running operations may end up blocking async calls being executed on other unrelated native modules. The `RCTAsyncLocalStorage` module here, for example, creates its own queue so the React queue isn't blocked waiting on potentially slow disk access.

Objective-C

```
- (dispatch_queue_t)methodQueue

{

 return dispatch_queue_create("com.facebook.React.AsyncLocalStorageQueue", DISPATCH_QUEUE_SERIAL);

}
```

The specified `methodQueue` will be shared by all of the methods in your module. If only one of your methods is long-running (or needs to be run on a different queue than the others for some reason), you can use `dispatch_async` inside the method to perform that particular method's code on another queue, without affecting the others:

Objective-C

```
RCT_EXPORT_METHOD(doSomethingExpensive:(NSString *)param callback:(RCTResponseSenderBlock)callback)

{

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

   // Call long-running code on background thread

   ...

   // You can invoke callback from any thread/queue

   callback(@[...]);

 });

}
```

Sharing dispatch queues between modules

The `methodQueue` method will be called once when the module is initialized, and then retained by React Native, so there is no need to keep a reference to the queue yourself, unless you wish to make use of it within your module. However, if you wish to share the same queue between multiple modules then you will need to ensure that you retain and return the same queue instance for each of them.

### Dependency Injection[​](#dependency-injection "Direct link to Dependency Injection")

React Native will create and initialize any registered native modules automatically. However, you may wish to create and initialize your own module instances to, for example, inject dependencies.

You can do this by creating a class that implements the `RCTBridgeDelegate` Protocol, initializing an `RCTBridge` with the delegate as an argument and initialising a `RCTRootView` with the initialized bridge.

Objective-C

```
id<RCTBridgeDelegate> moduleInitialiser = [[classThatImplementsRCTBridgeDelegate alloc] init];



RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:moduleInitialiser launchOptions:nil];



RCTRootView *rootView = [[RCTRootView alloc]

                        initWithBridge:bridge

                            moduleName:kModuleName

                     initialProperties:nil];
```

### Exporting Swift[​](#exporting-swift "Direct link to Exporting Swift")

Swift doesn't have support for macros, so exposing native modules and their methods to JavaScript inside React Native requires a bit more setup. However, it works relatively the same. Let's say you have the same `CalendarModule` but as a Swift class:

Swift

```
// CalendarModule.swift



@objc(CalendarModule)

class CalendarModule: NSObject {



 @objc(addEvent:location:date:)

 func addEvent(_ name: String, location: String, date: NSNumber) -> Void {

   // Date is ready to use!

 }



 @objc

 func constantsToExport() -> [String: Any]! {

   return ["someKey": "someValue"]

 }



}
```

note

It is important to use the `@objc` modifiers to ensure the class and functions are exported properly to the Objective-C runtime.

Then create a private implementation file that will register the required information with React Native:

Objective-C

```
// CalendarModuleBridge.m

#import <React/RCTBridgeModule.h>



@interface RCT_EXTERN_MODULE(CalendarModule, NSObject)



RCT_EXTERN_METHOD(addEvent:(NSString *)name location:(NSString *)location date:(nonnull NSNumber *)date)



@end
```

For those of you new to Swift and Objective-C, whenever you [mix the two languages in an iOS project](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html), you will also need an additional bridging file, known as a bridging header, to expose the Objective-C files to Swift. Xcode will offer to create this header file for you if you add your Swift file to your app through the Xcode `File>New File` menu option. You will need to import `RCTBridgeModule.h` in this header file.

Objective-C

```
// CalendarModule-Bridging-Header.h

#import <React/RCTBridgeModule.h>
```

----
url: https://reactnative.dev/docs/next/global-clearInterval
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-clearInterval)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearInterval) for more information.

The global `clearInterval` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/global-FileReader
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-FileReader)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) for more information.

The global `FileReader` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/testing-overview
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/testing-overview)** (0.87).

Version: Next

React Native comes with two such tools configured out of the box: [ESLint](https://eslint.org/) for linting and [TypeScript](/docs/next/typescript) for type checking.

```
it('given a date in the past, colorForDueDate() returns red', () => {

  expect(colorForDueDate('2000-10-20')).toBe('red');

});
```

```
function GroceryShoppingList() {

  const [groceryItem, setGroceryItem] = useState('');

  const [items, setItems] = useState<string[]>([]);



  const addNewItemToShoppingList = useCallback(() => {

    setItems([groceryItem, ...items]);

    setGroceryItem('');

  }, [groceryItem, items]);



  return (

    <>

      <TextInput

        value={groceryItem}

        placeholder="Enter grocery item"

        onChangeText={text => setGroceryItem(text)}

      />

      <Button

        title="Add the item to list"

        onPress={addNewItemToShoppingList}

      />

      {items.map(item => (

        <Text key={item}>{item}</Text>

      ))}

    </>

  );

}
```

```
test('given empty GroceryShoppingList, user can add an item to it', () => {

  const {getByPlaceholderText, getByText, getAllByText} = render(

    <GroceryShoppingList />,

  );



  fireEvent.changeText(

    getByPlaceholderText('Enter grocery item'),

    'banana',

  );

  fireEvent.press(getByText('Add the item to list'));



  const bananaElements = getAllByText('banana');

  expect(bananaElements).toHaveLength(1); // expect 'banana' to be on the list

});
```

This example is not testing how some state changes when you call a function. It tests what happens when a user changes text in the `TextInput` and presses the `Button`!

### Testing Rendered Output[​](#testing-rendered-output "Direct link to Testing Rendered Output")

[Snapshot testing](https://jestjs.io/docs/en/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:

React TSX

```
<Text

  style={

    Object {

      "fontSize": 20,

      "textAlign": "center",

    }

  }>

  Welcome to React Native!

</Text>
```

***

----
url: https://reactnative.dev/docs/react-node
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

----
url: https://reactnative.dev/docs/next/global-intersectionobserverentry
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-intersectionobserverentry)** (0.87).

Version: Next

Canary 🧪

**This API is currently only available in React Native’s Canary and Experimental channels.**

If you want to try it out, please [enable the Canary Channel](/docs/next/release-levels) in your app.

The [`IntersectionObserverEntry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry) interface, as defined in Web specifications. It describes the intersection between the target element and its root container at a specific moment of transition.

Instances of `IntersectionObserverEntry` are delivered to an [`IntersectionObserver`](/docs/next/global-intersectionobserver) callback in its `entries` parameter.

***

```
get rnRootIntersectionRatio(): number;
```

----
url: https://reactnative.dev/docs/next/global-setTimeout
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-setTimeout)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout) for more information.

The global `setTimeout` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/next/pressevent
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/pressevent)** (0.87).

Version: Next

`PressEvent` object is returned in the callback as a result of user press interaction, for example `onPress` in [Button](/docs/next/button) component.

## Example[​](#example "Direct link to Example")

JavaScript

```
{

    changedTouches: [PressEvent],

    identifier: 1,

    locationX: 8,

    locationY: 4.5,

    pageX: 24,

    pageY: 49.5,

    target: 1127,

    timestamp: 85131876.58868201,

    touches: []

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `changedTouches`[​](#changedtouches "Direct link to changedtouches")

Array of all PressEvents that have changed since the last event.

| Type                 | Optional |
| -------------------- | -------- |
| array of PressEvents | No       |

### `force`iOS[​](#force-ios "Direct link to force-ios")

Amount of force used during the 3D Touch press. Returns the float value in range from `0.0` to `1.0`.

| Type   | Optional |
| ------ | -------- |
| number | Yes      |

### `identifier`[​](#identifier "Direct link to identifier")

Unique numeric identifier assigned to the event.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `locationX`[​](#locationx "Direct link to locationx")

Touch origin X coordinate inside touchable area (relative to the element).

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `locationY`[​](#locationy "Direct link to locationy")

Touch origin Y coordinate inside touchable area (relative to the element).

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `pageX`[​](#pagex "Direct link to pagex")

Touch origin X coordinate on the screen (relative to the root view).

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `pageY`[​](#pagey "Direct link to pagey")

Touch origin Y coordinate on the screen (relative to the root view).

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `target`[​](#target "Direct link to target")

The node id of the element receiving the PressEvent.

| Type                        | Optional |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

### `timestamp`[​](#timestamp "Direct link to timestamp")

Timestamp value when a PressEvent occurred. Value is represented in milliseconds.

| Type   | Optional |
| ------ | -------- |
| number | No       |

### `touches`[​](#touches "Direct link to touches")

Array of all current PressEvents on the screen.

| Type                 | Optional |
| -------------------- | -------- |
| array of PressEvents | No       |

## Used by[​](#used-by "Direct link to Used by")

* [`Button`](/docs/next/button)
* [`PanResponder`](/docs/next/panresponder)
* [`Pressable`](/docs/next/pressable)
* [`ScrollView`](/docs/next/scrollview)
* [`Text`](/docs/next/text)
* [`TextInput`](/docs/next/textinput)
* [`TouchableHighlight`](/docs/next/touchablenativefeedback)
* [`TouchableOpacity`](/docs/next/touchablewithoutfeedback)
* [`TouchableNativeFeedback`](/docs/next/touchablenativefeedback)
* [`TouchableWithoutFeedback`](/docs/next/touchablewithoutfeedback)
* [`View`](/docs/next/view)

- [Example](#example)

- [Keys and values](#keys-and-values)

  * [`changedTouches`](#changedtouches)
  * [`force`](#force-ios)

    [iOS](#force-ios)

----
url: https://reactnative.dev/docs/global-File
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/File) for more information.

The global `File` class, as defined in Web specifications.

----
url: https://reactnative.dev/docs/linking
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

| Scheme           | Description                                  | iOS | Android |
| ---------------- | -------------------------------------------- | --- | ------- |
| `mailto`         | Open mail app, eg: mailto: <hello@world.dev> | ✅   | ✅       |
| `tel`            | Open phone app, eg: tel:+123456789           | ✅   | ✅       |
| `sms`            | Open SMS app, eg: sms:+123456789             | ✅   | ✅       |
| `https` / `http` | Open web browser app, eg: <https://expo.dev> | ✅   | ✅       |

```
<activity

  android:name=".MainActivity"

  android:launchMode="singleTask">
```

note

On iOS, you'll need to add the `LinkingIOS` folder into your header search paths as described in step 3 [here](/docs/linking-libraries-ios#step-3). If you also want to listen to incoming app links during your app's execution, you'll need to add the following lines to your `*AppDelegate.m`:

* ObjectiveC
* Swift

AppDelegate.mm

```
// iOS 9.x or newer

#import <React/RCTLinkingManager.h>



- (BOOL)application:(UIApplication *)application

   openURL:(NSURL *)url

   options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options

{

  return [RCTLinkingManager application:application openURL:url options:options];

}
```

If your app is using [Universal Links](https://developer.apple.com/ios/universal-links/), you'll need to add the following code as well:

AppDelegate.mm

```
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity

 restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler

{

 return [RCTLinkingManager application:application

                  continueUserActivity:userActivity

                    restorationHandler:restorationHandler];

}
```

AppDelegate.swift

```
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

  return RCTLinkingManager.application(app, open: url, options: options)

}
```

If your app is using [Universal Links](https://developer.apple.com/ios/universal-links/), you'll need to add the following code as well:

AppDelegate.swift

```
func application(

  _ application: UIApplication,

  continue userActivity: NSUserActivity,

  restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {

    return RCTLinkingManager.application(

      application,

      continue: userActivity,

      restorationHandler: restorationHandler

    )

  }
```

### Handling Deep Links[​](#handling-deep-links "Direct link to Handling Deep Links")

There are two ways to handle URLs that open your app.

#### 1. If the app is already open, the app is foregrounded and a Linking 'url' event is fired[​](#1-if-the-app-is-already-open-the-app-is-foregrounded-and-a-linking-url-event-is-fired "Direct link to 1. If the app is already open, the app is foregrounded and a Linking 'url' event is fired")

You can handle these events with `Linking.addEventListener('url', callback)` - it calls `callback({url})` with the linked URL

#### 2. If the app is not already open, it is opened and the url is passed in as the initialURL[​](#2-if-the-app-is-not-already-open-it-is-opened-and-the-url-is-passed-in-as-the-initialurl "Direct link to 2. If the app is not already open, it is opened and the url is passed in as the initialURL")

You can handle these events with `Linking.getInitialURL()` - it returns a Promise that resolves to the URL, if there is one.

***

```
static addEventListener(

  type: 'url',

  handler: (event: {url: string}) => void,

): EventSubscription;
```

Add a handler to Linking changes by listening to the `url` event type and providing the handler.

***

### `canOpenURL()`[​](#canopenurl "Direct link to canopenurl")

React TSX

```
static canOpenURL(url: string): Promise<boolean>;
```

Determine whether or not an installed app can handle a given URL.

The method returns a `Promise` object. When it is determined whether or not the given URL can be handled, the promise is resolved and the first parameter is whether or not it can be opened.

The `Promise` will reject on Android if it was impossible to check if the URL can be opened or when targeting Android 11 (SDK 30) if you didn't specify the relevant intent queries in `AndroidManifest.xml`. Similarly on iOS, the promise will reject if you didn't add the specific scheme in the `LSApplicationQueriesSchemes` key inside `Info.plist` (see bellow).

**Parameters:**

| Name        | Type   | Description      |
| ----------- | ------ | ---------------- |
| urlRequired | string | The URL to open. |

```
<manifest ...>

  <queries>

    <intent>

      <action android:name="android.intent.action.VIEW" />

      <data android:scheme="https"/>

    </intent>

  </queries>

</manifest>
```

***

### `getInitialURL()`[​](#getinitialurl "Direct link to getinitialurl")

React TSX

```
static getInitialURL(): Promise<string | null>;
```

If the app launch was triggered by an app link, it will give the link url, otherwise it will give `null`.

info

To support deep linking on Android, refer <https://developer.android.com/training/app-indexing/deep-linking.html#handling-intents>.

tip

`getInitialURL` may return `null` when Remote JS Debugging is active. Disable the debugger to ensure it gets passed.

***

### `openSettings()`[​](#opensettings "Direct link to opensettings")

React TSX

```
static openSettings(): Promise<void>;
```

Open the Settings app and displays the app’s custom settings, if it has any.

***

### `openURL()`[​](#openurl "Direct link to openurl")

React TSX

```
static openURL(url: string): Promise<any>;
```

Try to open the given `url` with any of the installed apps.

You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386" on Android or "<https://maps.apple.com/?ll=37.484847,-122.148386>" on iOS), a contact, or any other URL that can be opened with the installed apps.

The method returns a `Promise` object. If the user confirms the open dialog or the url automatically opens, the promise is resolved. If the user cancels the open dialog or there are no registered applications for the url, the promise is rejected.

**Parameters:**

| Name        | Type   | Description      |
| ----------- | ------ | ---------------- |
| urlRequired | string | The URL to open. |

note

This method will fail if the system doesn't know how to open the specified URL. If you're passing in a non-http(s) URL, it's best to check `canOpenURL()` first. For web URLs, the protocol (`"http://"`, `"https://"`) must be set accordingly!

warning

This method may behave differently in a simulator e.g. `"tel:"` links are not able to be handled in the iOS simulator as there's no access to the dialer app.

***

### `sendIntent()`Android[​](#sendintent-android "Direct link to sendintent-android")

React TSX

```
static sendIntent(

  action: string,

  extras?: Array<{key: string; value: string | number | boolean}>,

): Promise<void>;
```

Launch an Android intent with extras.

**Parameters:**

| Name           | Type                                                     |
| -------------- | -------------------------------------------------------- |
| actionRequired | string                                                   |
| extras         | `Array<{key: string, value: string ｜ number ｜ boolean}>` |

    [Android](#sendintent-android)

----
url: https://reactnative.dev/docs/the-new-architecture/layout-measurements
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Sometimes, you need to measure the current layout to apply some changes to the overall layout or to make decisions and call some specific logic.

React Native provides some native methods to know what are the measurements of the views.

The best way to invoke those methods is in a `useLayoutEffect` hook: this will give you the most recent values for those measurements and it will let you apply changes in the same frame when the measurements are computed.

Typical code will look like this:

React TSX

```
function AComponent(children) {

  const targetRef = useRef(null)



  useLayoutEffect(() => {

    targetRef.current?.measure((x, y, width, height, pageX, pageY) => {

      //do something with the measurements

    });

  }, [ /* add dependencies here */]);



  return (

    <View ref={targetRef}>

     {children}

    <View />

  );

}
```

----
url: https://reactnative.dev/docs/refreshcontrol
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This component is used inside a ScrollView or ListView to add pull to refresh functionality. When the ScrollView is at `scrollY: 0`, swiping down triggers an `onRefresh` event.

## Example[​](#example "Direct link to Example")

note

`refreshing` is a controlled prop, this is why it needs to be set to `true` in the `onRefresh` function otherwise the refresh indicator will stop immediately.

***

# Reference

## Props[​](#props "Direct link to Props")

### [View Props](/docs/view#props)[​](#view-props "Direct link to view-props")

Inherits [View Props](/docs/view#props).

***

### Require&#x64;**`refreshing`**[​](#requiredrefreshing "Direct link to requiredrefreshing")

Whether the view should be indicating an active refresh.

| Type    |
| ------- |
| boolean |

***

### `colors`Android[​](#colors-android "Direct link to colors-android")

The colors (at least one) that will be used to draw the refresh indicator.

| Type                            |
| ------------------------------- |
| array of [colors](/docs/colors) |

***

### `enabled`Android[​](#enabled-android "Direct link to enabled-android")

Whether the pull to refresh functionality is enabled.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

***

### `onRefresh`[​](#onrefresh "Direct link to onrefresh")

Called when the view starts refreshing.

| Type     |
| -------- |
| function |

***

### `progressBackgroundColor`Android[​](#progressbackgroundcolor-android "Direct link to progressbackgroundcolor-android")

The background color of the refresh indicator.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `progressViewOffset`[​](#progressviewoffset "Direct link to progressviewoffset")

Progress view top offset.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

***

### `size`Android[​](#size-android "Direct link to size-android")

Size of the refresh indicator.

| Type                         | Default     |
| ---------------------------- | ----------- |
| enum(`'default'`, `'large'`) | `'default'` |

***

### `tintColor`iOS[​](#tintcolor-ios "Direct link to tintcolor-ios")

The color of the refresh indicator.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `title`iOS[​](#title-ios "Direct link to title-ios")

The title displayed under the refresh indicator.

| Type   |
| ------ |
| string |

***

### `titleColor`iOS[​](#titlecolor-ios "Direct link to titlecolor-ios")

The color of the refresh indicator title.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

* [Example](#example)

* [Props](#props)

  * [View Props](#view-props)
  * [Required](#requiredrefreshing)

    [**`refreshing`**](#requiredrefreshing)
  * [`colors`](#colors-android)

    [Android](#colors-android)
  * [`enabled`](#enabled-android)

    [Android](#enabled-android)
  * [`onRefresh`](#onrefresh)
  * [`progressBackgroundColor`](#progressbackgroundcolor-android)

    [Android](#progressbackgroundcolor-android)
  * [`progressViewOffset`](#progressviewoffset)
  * [`size`](#size-android)

    [Android](#size-android)
  * [`tintColor`](#tintcolor-ios)

    [iOS](#tintcolor-ios)
  * [`title`](#title-ios)

    [iOS](#title-ios)
  * [`titleColor`](#titlecolor-ios)

    [iOS](#titlecolor-ios)

----
url: https://reactnative.dev/docs/next/devsettings
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/devsettings)** (0.87).

Version: Next

The `DevSettings` module exposes methods for customizing settings for developers in development.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `addMenuItem()`[​](#addmenuitem "Direct link to addmenuitem")

React TSX

```
static addMenuItem(title: string, handler: () => any);
```

Add a custom menu item to the Dev Menu.

**Parameters:**

| Name            | Type     |
| --------------- | -------- |
| titleRequired   | string   |
| handlerRequired | function |

**Example:**

React TSX

```
DevSettings.addMenuItem('Show Secret Dev Screen', () => {

  Alert.alert('Showing secret dev screen!');

});
```

***

### `reload()`[​](#reload "Direct link to reload")

React TSX

```
static reload(reason?: string): void;
```

Reload the application. Can be invoked directly or on user interaction.

**Example:**

React TSX

```
<Button title="Reload" onPress={() => DevSettings.reload()} />
```

* [Methods](#methods)

  * [`addMenuItem()`](#addmenuitem)
  * [`reload()`](#reload)

----
url: https://reactnative.dev/docs/next/publishing-to-app-store
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/publishing-to-app-store)** (0.87).

Version: Next

```
 if [ "${CONFIGURATION}" == "Debug" ]; then

  export SKIP_BUNDLING=true

 fi
```

----
url: https://reactnative.dev/docs/building-for-tv
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

TV devices support has been implemented with the intention of making existing React Native applications work on Apple TV and Android TV, with few or no changes needed in the JavaScript code for the applications.

Deprecated

TV support has moved to the [React Native for TV](https://github.com/react-native-tvos/react-native-tvos#readme) repository. Please see the **README** there for information on projects for Apple TV or Android TV.

----
url: https://reactnative.dev/docs/stylesheet
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

A StyleSheet is an abstraction similar to CSS StyleSheets.

Code quality tips:

* By moving styles away from the render function, you're making the code easier to understand.
* Naming the styles is a good way to add meaning to the low level components in the render function, and encourage reuse.
* In most IDEs, using `StyleSheet.create()` will offer static type checking and suggestions to help you write valid styles.

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `compose()`[​](#compose "Direct link to compose")

React TSX

```
static compose(style1: Object, style2: Object): Object | Object[];
```

Combines two styles such that `style2` will override any styles in `style1`. If either style is falsy, the other one is returned without allocating an array, saving allocations and maintaining reference equality for PureComponent checks.

***

### `create()`[​](#create "Direct link to create")

React TSX

```
static create(styles: Object extends Record<string, ViewStyle | ImageStyle | TextStyle>): Object;
```

An identity function for creating styles. The main practical benefit of creating styles inside `StyleSheet.create()` is static type checking against native style properties.

***

### `flatten()`[​](#flatten "Direct link to flatten")

React TSX

```
static flatten(style: Array<Object extends Record<string, ViewStyle | ImageStyle | TextStyle>>): Object;
```

Flattens an array of style objects, into one aggregated style object.

***

### `setStyleAttributePreprocessor()`[​](#setstyleattributepreprocessor "Direct link to setstyleattributepreprocessor")

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.

React TSX

```
static setStyleAttributePreprocessor(

  property: string,

  process: (propValue: any) => any,

);
```

Sets a function to use to pre-process a style property value. This is used internally to process color and transform values. You should not use this unless you really know what you are doing and have exhausted other options.

## Properties[​](#properties "Direct link to Properties")

***

### `absoluteFill`[​](#absolutefill "Direct link to absolutefill")

A very common pattern is to create overlays with position absolute and zero positioning (`position: 'absolute', left: 0, right: 0, top: 0, bottom: 0`), so `absoluteFill` can be used for convenience and to reduce duplication of these repeated styles. If you want, absoluteFill can be used to create a customized entry in a StyleSheet, e.g.:

***

----
url: https://reactnative.dev/docs/text-nodes
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Text nodes represent raw text content on the tree (similar to [`Text`](https://developer.mozilla.org/en-US/docs/Web/API/Text) nodes on Web). They are not directly accessible via `refs`, but can be accessed using methods like [`childNodes`](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes) on element refs.

***

    * ℹ️ Will return the [document node](/docs/next/document-nodes) where this component was rendered.

    * ℹ️ Will return a reference to itself if the component is not mounted.
  * [`hasChildNodes()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes)

- [Reference](#reference)
  * [Web-compatible API](#web-compatible-api)

----
url: https://reactnative.dev/docs/next/animatedvaluexy
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/animatedvaluexy)** (0.87).

Version: Next

2D Value for driving 2D animations, such as pan gestures. Almost identical API to normal [`Animated.Value`](/docs/next/animatedvalue), but multiplexed. Contains two regular `Animated.Value`s under the hood.

## Example[​](#example "Direct link to Example")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `setValue()`[​](#setvalue "Direct link to setvalue")

React TSX

```
setValue(value: {x: number; y: number});
```

Directly set the value. This will stop any animations running on the value and update all the bound properties.

**Parameters:**

| Name  | Type                     | Required | Description |
| ----- | ------------------------ | -------- | ----------- |
| value | `{x: number; y: number}` | Yes      | Value       |

***

### `setOffset()`[​](#setoffset "Direct link to setoffset")

React TSX

```
setOffset(offset: {x: number; y: number});
```

Sets an offset that is applied on top of whatever value is set, whether via `setValue`, an animation, or `Animated.event`. Useful for compensating things like the start of a pan gesture.

**Parameters:**

| Name   | Type                     | Required | Description  |
| ------ | ------------------------ | -------- | ------------ |
| offset | `{x: number; y: number}` | Yes      | Offset value |

***

### `flattenOffset()`[​](#flattenoffset "Direct link to flattenoffset")

React TSX

```
flattenOffset();
```

Merges the offset value into the base value and resets the offset to zero. The final output of the value is unchanged.

***

### `extractOffset()`[​](#extractoffset "Direct link to extractoffset")

React TSX

```
extractOffset();
```

Sets the offset value to the base value, and resets the base value to zero. The final output of the value is unchanged.

***

### `addListener()`[​](#addlistener "Direct link to addlistener")

React TSX

```
addListener(callback: (value: {x: number; y: number}) => void);
```

Adds an asynchronous listener to the value so you can observe updates from animations. This is useful because there is no way to synchronously read the value because it might be driven natively.

Returns a string that serves as an identifier for the listener.

**Parameters:**

| Name     | Type     | Required | Description                                                                                 |
| -------- | -------- | -------- | ------------------------------------------------------------------------------------------- |
| callback | function | Yes      | The callback function which will receive an object with a `value` key set to the new value. |

***

### `removeListener()`[​](#removelistener "Direct link to removelistener")

React TSX

```
removeListener(id: string);
```

Unregister a listener. The `id` param shall match the identifier previously returned by `addListener()`.

**Parameters:**

| Name | Type   | Required | Description                        |
| ---- | ------ | -------- | ---------------------------------- |
| id   | string | Yes      | Id for the listener being removed. |

***

### `removeAllListeners()`[​](#removealllisteners "Direct link to removealllisteners")

React TSX

```
removeAllListeners();
```

Remove all registered listeners.

***

### `stopAnimation()`[​](#stopanimation "Direct link to stopanimation")

React TSX

```
stopAnimation(callback?: (value: {x: number; y: number}) => void);
```

Stops any running animation or tracking. `callback` is invoked with the final value after stopping the animation, which is useful for updating state to match the animation position with layout.

**Parameters:**

| Name     | Type     | Required | Description                                   |
| -------- | -------- | -------- | --------------------------------------------- |
| callback | function | No       | A function that will receive the final value. |

***

### `resetAnimation()`[​](#resetanimation "Direct link to resetanimation")

React TSX

```
resetAnimation(callback?: (value: {x: number; y: number}) => void);
```

Stops any animation and resets the value to its original.

**Parameters:**

| Name     | Type     | Required | Description                                      |
| -------- | -------- | -------- | ------------------------------------------------ |
| callback | function | No       | A function that will receive the original value. |

***

### `getLayout()`[​](#getlayout "Direct link to getlayout")

React TSX

```
getLayout(): {left: Animated.Value, top: Animated.Value};
```

Converts `{x, y}` into `{left, top}` for use in style, e.g.

React TSX

```
style={this.state.anim.getLayout()}
```

***

### `getTranslateTransform()`[​](#gettranslatetransform "Direct link to gettranslatetransform")

React TSX

```
getTranslateTransform(): [

  {translateX: Animated.Value},

  {translateY: Animated.Value},

];
```

Converts `{x, y}` into a useable translation transform, e.g.

React TSX

```
style={{

  transform: this.state.anim.getTranslateTransform()

}}
```

----
url: https://reactnative.dev/docs/next/roottag
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/roottag)** (0.87).

Version: Next

```
import {RootTagContext} from 'react-native';

import NativeAnalytics from 'native-analytics';

import NativeNavigation from 'native-navigation';



function ScreenA() {

  const rootTag = useContext(RootTagContext);



  const updateTitle = title => {

    NativeNavigation.setTitle(rootTag, title);

  };



  const handleOneEvent = () => {

    NativeAnalytics.logEvent(rootTag, 'one_event');

  };



  // ...

}



class ScreenB extends React.Component {

  static contextType: typeof RootTagContext = RootTagContext;



  updateTitle(title) {

    NativeNavigation.setTitle(this.context, title);

  }



  handleOneEvent() {

    NativeAnalytics.logEvent(this.context, 'one_event');

  }



  // ...

}
```

----
url: https://reactnative.dev/docs/turbo-native-modules-introduction
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
npx @react-native-community/cli@latest init TurboModuleExample --version "0.87.0"
```

```
import type {TurboModule} from 'react-native';

import {TurboModuleRegistry} from 'react-native';



export interface Spec extends TurboModule {

  setItem(value: string, key: string): void;

  getItem(key: string): string | null;

  removeItem(key: string): void;

  clear(): void;

}



export default TurboModuleRegistry.getEnforcing<Spec>(

  'NativeLocalStorage',

);
```

NativeLocalStorage.js

```
import type {TurboModule} from 'react-native';

import {TurboModule, TurboModuleRegistry} from 'react-native';



export interface Spec extends TurboModule {

  setItem(value: string, key: string): void;

  getItem(key: string): ?string;

  removeItem(key: string): void;

  clear(): void;

}
```

### 2. Configure Codegen to run[​](#2-configure-codegen-to-run "Direct link to 2. Configure Codegen to run")

The specification is used by the React Native Codegen tools to generate platform specific interfaces and boilerplate for us. To do this, Codegen needs to know where to find our specification and what to do with it. Update your `package.json` to include:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "NativeLocalStorageSpec",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.nativelocalstorage"

     }

   },

   "dependencies": {
```

With everything wired up for Codegen, we need to prepare our native code to hook into our generated code.

* Android
* iOS

Codegen is executed through the `generateCodegenArtifactsFromSchema` Gradle task:

```
cd android

./gradlew generateCodegenArtifactsFromSchema



BUILD SUCCESSFUL in 837ms

14 actionable tasks: 3 executed, 11 up-to-date
```

This is automatically run when you build your Android application.

Codegen is run as part of the script phases that's automatically added to the project generated by CocoaPods.

```
cd ios

bundle install

bundle exec pod install
```

The output will look like this:

```
...

Framework build type is static library

[Codegen] Adding script_phases to ReactCodegen.

[Codegen] Generating ./build/generated/ios/ReactCodegen.podspec.json

[Codegen] Analyzing /Users/me/src/TurboModuleExample/package.json

[Codegen] Searching for codegen-enabled libraries in the app.

[Codegen] Found TurboModuleExample

[Codegen] Searching for codegen-enabled libraries in the project dependencies.

[Codegen] Found react-native

...
```

### 3. Write Application Code using the Turbo Native Module[​](#3-write-application-code-using-the-turbo-native-module "Direct link to 3. Write Application Code using the Turbo Native Module")

Using `NativeLocalStorage`, here’s a modified `App.tsx` that includes some text we want persisted, an input field and some buttons to update this value.

The `TurboModuleRegistry` supports 2 modes of retrieving a Turbo Native Module:

* `get<T>(name: string): T | null` which will return `null` if the Turbo Native Module is unavailable.
* `getEnforcing<T>(name: string): T` which will throw an exception if the Turbo Native Module is unavailable. This assumes the module is always available.

App.tsx

```
import {useEffect, useState, type JSX} from 'react';

import {

  SafeAreaView,

  StyleSheet,

  Text,

  TextInput,

  Button,

} from 'react-native';



import NativeLocalStorage from './specs/NativeLocalStorage';



const EMPTY = '<empty>';



function App(): JSX.Element {

  const [value, setValue] = useState<string | null>(null);



  const [editingValue, setEditingValue] = useState<string | null>(

    null,

  );



  useEffect(() => {

    const storedValue = NativeLocalStorage?.getItem('myKey');

    setValue(storedValue ?? '');

  }, []);



  function saveValue() {

    NativeLocalStorage?.setItem(editingValue ?? EMPTY, 'myKey');

    setValue(editingValue);

  }



  function clearAll() {

    NativeLocalStorage?.clear();

    setValue('');

  }



  function deleteValue() {

    NativeLocalStorage?.removeItem('myKey');

    setValue('');

  }



  return (

    <SafeAreaView style={{flex: 1}}>

      <Text style={styles.text}>

        Current stored value is: {value ?? 'No Value'}

      </Text>

      <TextInput

        placeholder="Enter the text you want to store"

        style={styles.textInput}

        onChangeText={setEditingValue}

      />

      <Button title="Save" onPress={saveValue} />

      <Button title="Delete" onPress={deleteValue} />

      <Button title="Clear" onPress={clearAll} />

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  text: {

    margin: 10,

    fontSize: 20,

  },

  textInput: {

    margin: 10,

    height: 40,

    borderColor: 'black',

    borderWidth: 1,

    paddingLeft: 5,

    paddingRight: 5,

    borderRadius: 5,

  },

});



export default App;
```

```
package com.nativelocalstorage;



import android.content.Context;

import android.content.SharedPreferences;

import com.nativelocalstorage.NativeLocalStorageSpec;

import com.facebook.react.bridge.ReactApplicationContext;



public class NativeLocalStorageModule extends NativeLocalStorageSpec {



  public static final String NAME = "NativeLocalStorage";



  public NativeLocalStorageModule(ReactApplicationContext reactContext) {

    super(reactContext);

  }



  @Override

  public String getName() {

    return NAME;

  }



  @Override

  public void setItem(String value, String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();

    editor.putString(key, value);

    editor.apply();

  }



  @Override

  public String getItem(String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    String username = sharedPref.getString(key, null);

    return username;

  }



  @Override

  public void removeItem(String key) {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    sharedPref.edit().remove(key).apply();

  }



  @Override

  public void clear() {

    SharedPreferences sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

    sharedPref.edit().clear().apply();

  }

}
```

android/app/src/main/java/com/nativelocalstorage/NativeLocalStorageModule.kt

```
package com.nativelocalstorage



import android.content.Context

import android.content.SharedPreferences

import com.nativelocalstorage.NativeLocalStorageSpec

import com.facebook.react.bridge.ReactApplicationContext



class NativeLocalStorageModule(reactContext: ReactApplicationContext) : NativeLocalStorageSpec(reactContext) {



  override fun getName() = NAME



  override fun setItem(value: String, key: String) {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.putString(key, value)

    editor.apply()

  }



  override fun getItem(key: String): String? {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val username = sharedPref.getString(key, null)

    return username.toString()

  }



  override fun removeItem(key: String) {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.remove(key)

    editor.apply()

  }



  override fun clear() {

    val sharedPref = getReactApplicationContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE)

    val editor = sharedPref.edit()

    editor.clear()

    editor.apply()

  }



  companion object {

    const val NAME = "NativeLocalStorage"

  }

}
```

Next we need to create `NativeLocalStoragePackage`. It provides an object to register our Module in the React Native runtime, by wrapping it as a Base Native Package:

* Java
* Kotlin

android/app/src/main/java/com/nativelocalstorage/NativeLocalStoragePackage.java

```
package com.nativelocalstorage;



import com.facebook.react.BaseReactPackage;

import com.facebook.react.bridge.NativeModule;

import com.facebook.react.bridge.ReactApplicationContext;

import com.facebook.react.module.model.ReactModuleInfo;

import com.facebook.react.module.model.ReactModuleInfoProvider;



import java.util.HashMap;

import java.util.Map;



public class NativeLocalStoragePackage extends BaseReactPackage {



  @Override

  public NativeModule getModule(String name, ReactApplicationContext reactContext) {

    if (name.equals(NativeLocalStorageModule.NAME)) {

      return new NativeLocalStorageModule(reactContext);

    } else {

      return null;

    }

  }



  @Override

  public ReactModuleInfoProvider getReactModuleInfoProvider() {

    return new ReactModuleInfoProvider() {

      @Override

      public Map<String, ReactModuleInfo> getReactModuleInfos() {

        Map<String, ReactModuleInfo> map = new HashMap<>();

        map.put(NativeLocalStorageModule.NAME, new ReactModuleInfo(

          NativeLocalStorageModule.NAME,       // name

          NativeLocalStorageModule.NAME,       // className

          false, // canOverrideExistingModule

          false, // needsEagerInit

          false, // isCXXModule

          true   // isTurboModule

        ));

        return map;

      }

    };

  }

}
```

android/app/src/main/java/com/nativelocalstorage/NativeLocalStoragePackage.kt

```
package com.nativelocalstorage



import com.facebook.react.BaseReactPackage

import com.facebook.react.bridge.NativeModule

import com.facebook.react.bridge.ReactApplicationContext

import com.facebook.react.module.model.ReactModuleInfo

import com.facebook.react.module.model.ReactModuleInfoProvider



class NativeLocalStoragePackage : BaseReactPackage() {



  override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =

    if (name == NativeLocalStorageModule.NAME) {

      NativeLocalStorageModule(reactContext)

    } else {

      null

    }



  override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {

    mapOf(

      NativeLocalStorageModule.NAME to ReactModuleInfo(

        name = NativeLocalStorageModule.NAME,

        className = NativeLocalStorageModule.NAME,

        canOverrideExistingModule = false,

        needsEagerInit = false,

        isCxxModule = false,

        isTurboModule = true

      )

    )

  }

}
```

```
package com.inappmodule;



import android.app.Application;

import com.facebook.react.PackageList;

import com.facebook.react.ReactApplication;

import com.facebook.react.ReactHost;

import com.facebook.react.ReactNativeHost;

import com.facebook.react.ReactPackage;

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;

import com.facebook.react.defaults.DefaultReactHost;

import com.facebook.react.defaults.DefaultReactNativeHost;

import com.facebook.soloader.SoLoader;

import com.nativelocalstorage.NativeLocalStoragePackage;



import java.util.ArrayList;

import java.util.List;



public class MainApplication extends Application implements ReactApplication {



  private final ReactNativeHost reactNativeHost = new DefaultReactNativeHost(this) {

    @Override

    public List<ReactPackage> getPackages() {

      List<ReactPackage> packages = new PackageList(this).getPackages();

      // Packages that cannot be autolinked yet can be added manually here, for example:

      // packages.add(new MyReactNativePackage());

      packages.add(new NativeLocalStoragePackage());

      return packages;

    }



    @Override

    public String getJSMainModuleName() {

      return "index";

    }



    @Override

    public boolean getUseDeveloperSupport() {

      return BuildConfig.DEBUG;

    }



    @Override

    public boolean isNewArchEnabled() {

      return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;

    }



    @Override

    public boolean isHermesEnabled() {

      return BuildConfig.IS_HERMES_ENABLED;

    }

  };



  @Override

  public ReactHost getReactHost() {

    return DefaultReactHost.getDefaultReactHost(getApplicationContext(), reactNativeHost);

  }



  @Override

  public void onCreate() {

    super.onCreate();

    SoLoader.init(this, false);

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      // If you opted-in for the New Architecture, we load the native entry point for this app.

      DefaultNewArchitectureEntryPoint.load();

    }

  }

}
```

android/app/src/main/java/com/turobmoduleexample/MainApplication.kt

```
package com.inappmodule



import android.app.Application

import com.facebook.react.PackageList

import com.facebook.react.ReactApplication

import com.facebook.react.ReactHost

import com.facebook.react.ReactNativeHost

import com.facebook.react.ReactPackage

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

import com.facebook.react.defaults.DefaultReactNativeHost

import com.facebook.soloader.SoLoader

import com.nativelocalstorage.NativeLocalStoragePackage



class MainApplication : Application(), ReactApplication {



  override val reactNativeHost: ReactNativeHost =

      object : DefaultReactNativeHost(this) {

        override fun getPackages(): List<ReactPackage> =

            PackageList(this).packages.apply {

              // Packages that cannot be autolinked yet can be added manually here, for example:

              // add(MyReactNativePackage())

              add(NativeLocalStoragePackage())

            }



        override fun getJSMainModuleName(): String = "index"



        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG



        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

      }



  override val reactHost: ReactHost

    get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

    SoLoader.init(this, false)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

      // If you opted-in for the New Architecture, we load the native entry point for this app.

      load()

    }

  }

}
```

You can now build and run your code on an emulator:

* npm
* Yarn

```
npm run android
```

```
yarn run android
```

Now it's time to write some iOS platform code to make sure `localStorage` survives after the application is closed.

## Prepare your Xcode Project[​](#prepare-your-xcode-project "Direct link to Prepare your Xcode Project")

We need to prepare your iOS project using Xcode. After completing these **6 steps** you'll have `RCTNativeLocalStorage` that implements the generated `NativeLocalStorageSpec` interface.

1. Open the CocoaPods generated Xcode Workspace:

```
cd ios

open TurboModuleExample.xcworkspace
```

```
//  RCTNativeLocalStorage.h

//  TurboModuleExample



#import <Foundation/Foundation.h>

#import <NativeLocalStorageSpec/NativeLocalStorageSpec.h>



NS_ASSUME_NONNULL_BEGIN



@interface RCTNativeLocalStorage : NSObject

@interface RCTNativeLocalStorage : NSObject <NativeLocalStorageSpec>



@end
```

Then update our implementation to use `NSUserDefaults` with a custom [suite name](https://developer.apple.com/documentation/foundation/nsuserdefaults/1409957-initwithsuitename).

NativeLocalStorage/RCTNativeLocalStorage.mm

```
//  RCTNativeLocalStorage.m

//  TurboModuleExample



#import "RCTNativeLocalStorage.h"



static NSString *const RCTNativeLocalStorageKey = @"local-storage";



@interface RCTNativeLocalStorage()

@property (strong, nonatomic) NSUserDefaults *localStorage;

@end



@implementation RCTNativeLocalStorage



- (id) init {

  if (self = [super init]) {

    _localStorage = [[NSUserDefaults alloc] initWithSuiteName:RCTNativeLocalStorageKey];

  }

  return self;

}



- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {

  return std::make_shared<facebook::react::NativeLocalStorageSpecJSI>(params);

}



- (NSString * _Nullable)getItem:(NSString *)key {

  return [self.localStorage stringForKey:key];

}



- (void)setItem:(NSString *)value

          key:(NSString *)key {

  [self.localStorage setObject:value forKey:key];

}



- (void)removeItem:(NSString *)key {

  [self.localStorage removeObjectForKey:key];

}



- (void)clear {

  NSDictionary *keys = [self.localStorage dictionaryRepresentation];

  for (NSString *key in keys) {

    [self removeItem:key];

  }

}



+ (NSString *)moduleName

{

  return @"NativeLocalStorage";

}



@end
```

Important things to note:

* You can use Xcode to jump to the Codegen `@protocol NativeLocalStorageSpec`. You can also use Xcode to generate stubs for you.

## Register the Native Module in your app[​](#register-the-native-module-in-your-app "Direct link to Register the Native Module in your app")

The last step consist in updating the `package.json` to tell React Native about the link between the JS specs of the Native Module and the concrete implementation of those specs in native code.

Modify the `package.json` as it follows:

package.json

```
     "start": "react-native start",

     "test": "jest"

   },

   "codegenConfig": {

     "name": "NativeLocalStorageSpec",

     "type": "modules",

     "jsSrcsDir": "specs",

     "android": {

       "javaPackageName": "com.nativelocalstorage"

     },

     "ios": {

        "modulesProvider": {

          "NativeLocalStorage": "RCTNativeLocalStorage"

        }

     }

   },



   "dependencies": {
```

At this point, you need to re-install the pods to make sure that codegen runs again to generate the new files:

```
# from the ios folder

bundle exec pod install

open TurboModuleExample.xcworkspace
```

If you now build your application from Xcode, you should be able to build successfully.

## Build and run your code on a Simulator[​](#build-and-run-your-code-on-a-simulator "Direct link to Build and run your code on a Simulator")

* npm
* Yarn

```
npm run ios
```

```
yarn run ios
```

* [Native Persistent Storage](#native-persistent-storage)

  * [1. Declare Typed Specification](#1-declare-typed-specification)
  * [2. Configure Codegen to run](#2-configure-codegen-to-run)
  * [3. Write Application Code using the Turbo Native Module](#3-write-application-code-using-the-turbo-native-module)
  * [4. Write your Native Platform code](#4-write-your-native-platform-code)

----
url: https://reactnative.dev/docs/next/global-alert
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-alert)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert) for more information.

The global `alert` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/asyncstorage
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Removed from React Native

Use one of the [community packages](https://reactnative.directory/?search=storage) instead.

----
url: https://reactnative.dev/docs/next/sectionlist
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/sectionlist)** (0.87).

Version: Next

If you don't need section support and want a simpler interface, use [`<FlatList>`](/docs/next/flatlist).

## Example[​](#example "Direct link to Example")

This is a convenience wrapper around [`<VirtualizedList>`](/docs/next/virtualizedlist), and thus inherits its props (as well as those of [`<ScrollView>`](/docs/next/scrollview)) that aren't explicitly listed here, along with the following caveats:

* Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
* This is a `PureComponent` which means that it will not re-render if `props` remain shallow-equal. Make sure that everything your `renderItem` function depends on is passed as a prop (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on changes. This includes the `data` prop and parent component state.
* In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
* By default, the list looks for a `key` prop on each item and uses that for the React key. Alternatively, you can provide a custom `keyExtractor` prop.

***

# Reference

## Props[​](#props "Direct link to Props")

### [VirtualizedList Props](/docs/next/virtualizedlist#props)[​](#virtualizedlist-props "Direct link to virtualizedlist-props")

Inherits [VirtualizedList Props](/docs/next/virtualizedlist#props).

***

### Require&#x64;**`renderItem`**[​](#requiredrenderitem "Direct link to requiredrenderitem")

Default renderer for every item in every section. Can be over-ridden on a per-section basis. Should return a React element.

| Type     |
| -------- |
| function |

    * 'select' (enum) - possible values are 'leading', 'trailing'
    * 'newProps' (object)

***

### Require&#x64;**`sections`**[​](#requiredsections "Direct link to requiredsections")

The actual data to render, akin to the `data` prop in [`FlatList`](/docs/next/flatlist).

| Type                                                |
| --------------------------------------------------- |
| array of [Section](/docs/next/sectionlist#section)s |

***

### `extraData`[​](#extradata "Direct link to extradata")

A marker property for telling the list to re-render (since it implements `PureComponent`). If any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the `data` prop, stick it here and treat it immutably.

| Type |
| ---- |
| any  |

***

### `initialNumToRender`[​](#initialnumtorender "Direct link to initialnumtorender")

How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.

| Type   | Default |
| ------ | ------- |
| number | `10`    |

***

### `inverted`[​](#inverted "Direct link to inverted")

Reverses the direction of scroll. Uses scale transforms of -1.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `ItemSeparatorComponent`[​](#itemseparatorcomponent "Direct link to itemseparatorcomponent")

Rendered in between each item, but not at the top or bottom. By default, `highlighted`, `section`, and `[leading/trailing][Item/Section]` props are provided. `renderItem` provides `separators.highlight`/`unhighlight` which will update the `highlighted` prop, but you can also add custom props with `separators.updateProps`. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type                         |
| ---------------------------- |
| component, function, element |

***

### `keyExtractor`[​](#keyextractor "Direct link to keyextractor")

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the React key to track item re-ordering. The default extractor checks `item.key`, then `item.id`, and then falls back to using the index, like React does. Note that this sets keys for each item, but each overall section still needs its own key.

| Type                                    |
| --------------------------------------- |
| (item: object, index: number) => string |

***

### `ListEmptyComponent`[​](#listemptycomponent "Direct link to listemptycomponent")

Rendered when the list is empty. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListFooterComponent`[​](#listfootercomponent "Direct link to listfootercomponent")

Rendered at the very end of the list. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `ListHeaderComponent`[​](#listheadercomponent "Direct link to listheadercomponent")

Rendered at the very beginning of the list. Can be a React Component (e.g. `SomeComponent`), or a React element (e.g. `<SomeComponent />`).

| Type               |
| ------------------ |
| component, element |

***

### `onRefresh`[​](#onrefresh "Direct link to onrefresh")

If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the `refreshing` prop correctly. To offset the RefreshControl from the top (e.g. by 100 pts), use `progressViewOffset={100}`.

| Type     |
| -------- |
| function |

***

### `onViewableItemsChanged`[​](#onviewableitemschanged "Direct link to onviewableitemschanged")

Called when the viewability of rows changes, as defined by the `viewabilityConfig` prop.

| Type                                                                     |
| ------------------------------------------------------------------------ |
| `(callback: {changed: ViewToken[], viewableItems: ViewToken[]}) => void` |

***

### `refreshing`[​](#refreshing "Direct link to refreshing")

Set this true while waiting for new data from a refresh.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `removeClippedSubviews`[​](#removeclippedsubviews "Direct link to removeclippedsubviews")

warning

Using this property may lead to bugs (missing content) in some circumstances - use at your own risk.

When `true`, offscreen child views are removed from their native backing superview when offscreen. This may improve scroll performance for large lists. On Android the default value is `true`.

| Type    |
| ------- |
| boolean |

***

### `renderSectionFooter`[​](#rendersectionfooter "Direct link to rendersectionfooter")

Rendered at the bottom of each section.

| Type                                           |
| ---------------------------------------------- |
| `(info: {section: Section}) => element ｜ null` |

***

### `renderSectionHeader`[​](#rendersectionheader "Direct link to rendersectionheader")

Rendered at the top of each section. These stick to the top of the `ScrollView` by default on iOS. See `stickySectionHeadersEnabled`.

| Type                                           |
| ---------------------------------------------- |
| `(info: {section: Section}) => element ｜ null` |

***

### `SectionSeparatorComponent`[​](#sectionseparatorcomponent "Direct link to sectionseparatorcomponent")

Rendered at the top and bottom of each section (note this is different from `ItemSeparatorComponent` which is only rendered between items). These are intended to separate sections from the headers above and below and typically have the same highlight response as `ItemSeparatorComponent`. Also receives `highlighted`, `[leading/trailing][Item/Section]`, and any custom props from `separators.updateProps`.

| Type               |
| ------------------ |
| component, element |

***

### `stickySectionHeadersEnabled`[​](#stickysectionheadersenabled "Direct link to stickysectionheadersenabled")

Makes section headers stick to the top of the screen until the next one pushes it off. Only enabled by default on iOS because that is the platform standard there.

| Type    | Default                    |
| ------- | -------------------------- |
| boolean | `false`Android***`true`iOS |

## Methods[​](#methods "Direct link to Methods")

### `flashScrollIndicators()`iOS[​](#flashscrollindicators-ios "Direct link to flashscrollindicators-ios")

React TSX

```
flashScrollIndicators();
```

Displays the scroll indicators momentarily.

***

### `recordInteraction()`[​](#recordinteraction "Direct link to recordinteraction")

React TSX

```
recordInteraction();
```

Tells the list an interaction has occurred, which should trigger viewability calculations, e.g. if `waitForInteractions` is true and the user has not scrolled. This is typically called by taps on items or by navigation actions.

***

### `scrollToLocation()`[​](#scrolltolocation "Direct link to scrolltolocation")

React TSX

```
scrollToLocation(params: SectionListScrollParams);
```

Scrolls to the item at the specified `sectionIndex` and `itemIndex` (within the section) positioned in the viewable area such that `viewPosition` set to `0` places it at the top (and may be covered by a sticky header), `1` at the bottom, and `0.5` centered in the middle.

note

You cannot scroll to locations outside the render window without specifying the `getItemLayout` or `onScrollToIndexFailed` prop.

**Parameters:**

| Name           | Type   |
| -------------- | ------ |
| paramsRequired | object |

| Type |
| ---- |
| any  |

**Properties:**

| Name                   | Type               | Description                                                                                                                                                                    |
| ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| dataRequired           | array              | The data for rendering items in this section. Array of objects, much like [`FlatList`'s data prop](/docs/next/flatlist#required-data).                                         |
| key                    | string             | Optional key to keep track of section re-ordering. If you don't plan on re-ordering sections, the array index will be used by default.                                         |
| renderItem             | function           | Optionally define an arbitrary item renderer for this section, overriding the default [`renderItem`](/docs/next/sectionlist#requiredrenderitem) for the list.                  |
| ItemSeparatorComponent | component, element | Optionally define an arbitrary item separator for this section, overriding the default [`ItemSeparatorComponent`](/docs/next/sectionlist#itemseparatorcomponent) for the list. |
| keyExtractor           | function           | Optionally define an arbitrary key extractor for this section, overriding the default [`keyExtractor`](/docs/next/sectionlist#keyextractor).                                   |

* [Example](#example)

* [Props](#props)

  * [VirtualizedList Props](#virtualizedlist-props)
  * [Required](#requiredrenderitem)

    [**`renderItem`**](#requiredrenderitem)
  * [Required](#requiredsections)

    [**`sections`**](#requiredsections)

    [iOS](#flashscrollindicators-ios)
  * [`recordInteraction()`](#recordinteraction)
  * [`scrollToLocation()`](#scrolltolocation)

* [Type Definitions](#type-definitions)
  * [Section](#section)

----
url: https://reactnative.dev/docs/integration-with-existing-apps
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Follow the guide on [setting up your development environment](/docs/set-up-your-environment) and using [React Native without a framework](/docs/getting-started-without-a-framework) to configure your development environment for building React Native apps for Android. This guide also assumes you're familiar with the basics of Android development such as creating Activities and editing the `AndroidManifest.xml` file.

## 1. Set up directory structure[​](#1-set-up-directory-structure "Direct link to 1. Set up directory structure")

To ensure a smooth experience, create a new folder for your integrated React Native project, then **move your existing Android project** to the `/android` subfolder.

## 2. Install NPM dependencies[​](#2-install-npm-dependencies "Direct link to 2. Install NPM dependencies")

Go to the root directory and run the following command:

shell

```
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.87-stable/template/package.json
```

This will copy the `package.json` [file from the Community template](https://github.com/react-native-community/template/blob/0.87-stable/template/package.json) to your project.

Next, install the NPM packages by running:

* npm
* Yarn

```
npm install
```

```
yarn install
```

Installation process has created a new `node_modules` folder. This folder stores all the JavaScript dependencies required to build your project.

Add `node_modules/` to your `.gitignore` file (here the [Community default one](https://github.com/react-native-community/template/blob/0.87-stable/template/_gitignore)).

## 3. Adding React Native to your app[​](#3-adding-react-native-to-your-app "Direct link to 3. Adding React Native to your app")

### Configuring Gradle[​](#configuring-gradle "Direct link to Configuring Gradle")

React Native uses the React Native Gradle Plugin to configure your dependencies and project setup.

First, let's edit your `settings.gradle` file by adding those lines (as suggested from the [Community template](https://github.com/react-native-community/template/blob/0.87-stable/template/android/settings.gradle)):

Groovy

```
// Configures the React Native Gradle Settings plugin used for autolinking

pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }

plugins { id("com.facebook.react.settings") }

extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }

// If using .gradle.kts files:

// extensions.configure<com.facebook.react.ReactSettingsExtension> { autolinkLibrariesFromCommand() }

includeBuild("../node_modules/@react-native/gradle-plugin")



// Include your existing Gradle modules here.

// include(":app")
```

Then you need to open your top level `build.gradle` and include this line (as suggested from the [Community template](https://github.com/react-native-community/template/blob/0.87-stable/template/android/build.gradle)):

Diff

```
buildscript {

    repositories {

        google()

        mavenCentral()

    }

    dependencies {

        classpath("com.android.tools.build:gradle:7.3.1")

+       classpath("com.facebook.react:react-native-gradle-plugin")

    }

}
```

This makes sure the React Native Gradle Plugin (RNGP) is available inside your project. Finally, add those lines inside your Applications's `build.gradle` file (it's a different `build.gradle` file usually inside your `app` folder - you can use the [Community template file as reference](https://github.com/react-native-community/template/blob/0.87-stable/template/android/build.gradle)):

Diff

```
apply plugin: "com.android.application"

+apply plugin: "com.facebook.react"



repositories {

    mavenCentral()

}



dependencies {

    // Other dependencies here

+   // Note: we intentionally don't specify the version number here as RNGP will take care of it.

+   // If you don't use the RNGP, you'll have to specify version manually.

+   implementation("com.facebook.react:react-android")

+   implementation("com.facebook.react:hermes-android")

}



+react {

+   // Needed to enable Autolinking - https://github.com/react-native-community/cli/blob/master/docs/autolinking.md

+   autolinkLibrariesWithApp()

+}
```

Finally, open your application `gradle.properties` files and add the following line (here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.87-stable/template/android/gradle.properties)):

Diff

```
+reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64

+newArchEnabled=true

+hermesEnabled=true
```

### Configuring your manifest[​](#configuring-your-manifest "Direct link to Configuring your manifest")

First, make sure you have the Internet permission in your `AndroidManifest.xml`:

Diff

```
<manifest xmlns:android="http://schemas.android.com/apk/res/android">



+   <uses-permission android:name="android.permission.INTERNET" />



    <application

      android:name=".MainApplication">

    </application>

</manifest>
```

Then you need to enable [cleartext traffic](https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted) in your **debug** `AndroidManifest.xml`:

Diff

```
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools">



    <application

+       android:usesCleartextTraffic="true"

+       tools:targetApi="28"

    />

</manifest>
```

As usual, here the AndroidManifest.xml file from the Community template to use as a reference: [main](https://github.com/react-native-community/template/blob/0.87-stable/template/android/app/src/main/AndroidManifest.xml) and [debug](https://github.com/react-native-community/template/blob/0.87-stable/template/android/app/src/debug/AndroidManifest.xml).

Our index.js should look as follows (here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.87-stable/template/index.js)):

JavaScript

```
import {AppRegistry} from 'react-native';

import App from './App';



AppRegistry.registerComponent('HelloWorld', () => App);
```

### Create a `App.tsx` file[​](#create-a-apptsx-file "Direct link to create-a-apptsx-file")

Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX](https://en.wikipedia.org/wiki/JSX_\(JavaScript\)) expressions. It contains the root React Native component that we will integrate into our Android application ([link](https://github.com/react-native-community/template/blob/0.87-stable/template/App.tsx)):

React TSX

```
import {type JSX} from 'react';

import {

  SafeAreaView,

  ScrollView,

  StatusBar,

  StyleSheet,

  Text,

  useColorScheme,

  View,

} from 'react-native';

import {

  Colors,

  DebugInstructions,

  Header,

  ReloadInstructions,

} from 'react-native/Libraries/NewAppScreen';



function App(): JSX.Element {

  const isDarkMode = useColorScheme() === 'dark';



  const backgroundStyle = {

    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,

  };



  return (

    <SafeAreaView style={backgroundStyle}>

      <StatusBar

        barStyle={isDarkMode ? 'light-content' : 'dark-content'}

        backgroundColor={backgroundStyle.backgroundColor}

      />

      <ScrollView

        contentInsetAdjustmentBehavior="automatic"

        style={backgroundStyle}>

        <Header />

        <View

          style={{

            backgroundColor: isDarkMode

              ? Colors.black

              : Colors.white,

            padding: 24,

          }}>

          <Text style={styles.title}>Step One</Text>

          <Text>

            Edit <Text style={styles.bold}>App.tsx</Text> to

            change this screen and see your edits.

          </Text>

          <Text style={styles.title}>See your changes</Text>

          <ReloadInstructions />

          <Text style={styles.title}>Debug</Text>

          <DebugInstructions />

        </View>

      </ScrollView>

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  title: {

    fontSize: 24,

    fontWeight: '600',

  },

  bold: {

    fontWeight: '700',

  },

});



export default App;
```

Here is the [Community template file as reference](https://github.com/react-native-community/template/blob/0.87-stable/template/App.tsx).

```
package <your-package-here>;



import android.app.Application;

+import com.facebook.react.PackageList;

+import com.facebook.react.ReactApplication;

+import com.facebook.react.ReactHost;

+import com.facebook.react.ReactNativeHost;

+import com.facebook.react.ReactPackage;

+import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;

+import com.facebook.react.defaults.DefaultReactHost;

+import com.facebook.react.defaults.DefaultReactNativeHost;

+import com.facebook.soloader.SoLoader;

+import com.facebook.react.soloader.OpenSourceMergedSoMapping

+import java.util.List;



-class MainApplication extends Application {

+class MainApplication extends Application implements ReactApplication {

+ @Override

+ public ReactNativeHost getReactNativeHost() {

+   return new DefaultReactNativeHost(this) {

+     @Override

+     protected List<ReactPackage> getPackages() { return new PackageList(this).getPackages(); }

+     @Override

+     protected String getJSMainModuleName() { return "index"; }

+     @Override

+     public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; }

+     @Override

+     protected boolean isNewArchEnabled() { return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; }

+     @Override

+     protected Boolean isHermesEnabled() { return BuildConfig.IS_HERMES_ENABLED; }

+   };

+ }



+ @Override

+ public ReactHost getReactHost() {

+   return DefaultReactHost.getDefaultReactHost(getApplicationContext(), getReactNativeHost());

+ }



  @Override

  public void onCreate() {

    super.onCreate();

+   SoLoader.init(this, OpenSourceMergedSoMapping);

+   if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

+     DefaultNewArchitectureEntryPoint.load();

+   }

  }

}
```

Diff

```
// package <your-package-here>



import android.app.Application

+import com.facebook.react.PackageList

+import com.facebook.react.ReactApplication

+import com.facebook.react.ReactHost

+import com.facebook.react.ReactNativeHost

+import com.facebook.react.ReactPackage

+import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load

+import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost

+import com.facebook.react.defaults.DefaultReactNativeHost

+import com.facebook.soloader.SoLoader

+import com.facebook.react.soloader.OpenSourceMergedSoMapping



-class MainApplication : Application() {

+class MainApplication : Application(), ReactApplication {



+ override val reactNativeHost: ReactNativeHost =

+      object : DefaultReactNativeHost(this) {

+        override fun getPackages(): List<ReactPackage> = PackageList(this).packages

+        override fun getJSMainModuleName(): String = "index"

+        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG

+        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED

+        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED

+      }



+ override val reactHost: ReactHost

+   get() = getDefaultReactHost(applicationContext, reactNativeHost)



  override fun onCreate() {

    super.onCreate()

+   SoLoader.init(this, OpenSourceMergedSoMapping)

+   if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {

+     load()

+   }

  }

}
```

As usual, here the [`MainApplication.kt` Community template file as reference](https://github.com/react-native-community/template/blob/0.87-stable/template/android/app/src/main/java/com/helloworld/MainApplication.kt).

#### Creating a `ReactActivity`[​](#creating-a-reactactivity "Direct link to creating-a-reactactivity")

Finally, we need to create a new `Activity` that will extend `ReactActivity` and host the React Native code. This activity will be responsible for starting the React Native runtime and rendering the React component.

* Java
* Kotlin

Java

```
// package <your-package-here>;



import com.facebook.react.ReactActivity;

import com.facebook.react.ReactActivityDelegate;

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;

import com.facebook.react.defaults.DefaultReactActivityDelegate;



public class MyReactActivity extends ReactActivity {



    @Override

    protected String getMainComponentName() {

        return "HelloWorld";

    }



    @Override

    protected ReactActivityDelegate createReactActivityDelegate() {

        return new DefaultReactActivityDelegate(this, getMainComponentName(), DefaultNewArchitectureEntryPoint.getFabricEnabled());

    }

}
```

Kotlin

```
// package <your-package-here>



import com.facebook.react.ReactActivity

import com.facebook.react.ReactActivityDelegate

import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled

import com.facebook.react.defaults.DefaultReactActivityDelegate



class MyReactActivity : ReactActivity() {



    override fun getMainComponentName(): String = "HelloWorld"



    override fun createReactActivityDelegate(): ReactActivityDelegate =

        DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)

}
```

As usual, here the [`MainActivity.kt` Community template file as reference](https://github.com/react-native-community/template/blob/0.87-stable/template/android/app/src/main/java/com/helloworld/MainActivity.kt).

Whenever you create a new Activity, you need to add it to your `AndroidManifest.xml` file. You also need set the theme of `MyReactActivity` to `Theme.AppCompat.Light.NoActionBar` (or to any non-ActionBar theme) as otherwise your application will render an ActionBar on top of your React Native screen:

Diff

```
<manifest xmlns:android="http://schemas.android.com/apk/res/android">



    <uses-permission android:name="android.permission.INTERNET" />



    <application

      android:name=".MainApplication">



+     <activity

+       android:name=".MyReactActivity"

+       android:label="@string/app_name"

+       android:theme="@style/Theme.AppCompat.Light.NoActionBar">

+     </activity>

    </application>

</manifest>
```

Now your activity is ready to run some JavaScript code.

## 6. Test your integration[​](#6-test-your-integration "Direct link to 6. Test your integration")

You have completed all the basic steps to integrate React Native with your application. Now we will start the [Metro bundler](https://metrobundler.dev/) to build your TypeScript application code into a bundle. Metro's HTTP server shares the bundle from `localhost` on your developer environment to a simulator or device. This allows for [hot reloading](https://reactnative.dev/blog/2016/03/24/introducing-hot-reloading).

First, you need to create a `metro.config.js` file in the root of your project as follows:

JavaScript

```
const {getDefaultConfig} = require('@react-native/metro-config');

module.exports = getDefaultConfig(__dirname);
```

You can checkout the [`metro.config.js` file](https://github.com/react-native-community/template/blob/0.87-stable/template/metro.config.js) from the Community template file as reference.

Once you have the configuration file in place, you can run the bundler. Run the following command in the root directory of your project:

* npm
* Yarn

```
npm start
```

```
yarn start
```

Now build and run your Android app as normal.

Once you reach your React-powered Activity inside the app, it should load the JavaScript code from the development server and display:

### Creating a release build in Android Studio[​](#creating-a-release-build-in-android-studio "Direct link to Creating a release build in Android Studio")

You can use Android Studio to create your release builds too! It’s as quick as creating release builds of your previously-existing native Android app.

The React Native Gradle Plugin will take care of bundling the JS code inside your APK/App Bundle.

If you're not using Android Studio, you can create a release build with:

```
cd android

# For a Release APK

./gradlew :app:assembleRelease

# For a Release AAB

./gradlew :app:bundleRelease
```

### Now what?[​](#now-what "Direct link to Now what?")

At this point you can continue developing your app as usual. Refer to our [debugging](/docs/debugging) and [deployment](/docs/running-on-device) docs to learn more about working with React Native.

Follow the guide on [setting up your development environment](/docs/set-up-your-environment) and using [React Native without a framework](/docs/getting-started-without-a-framework) to configure your development environment for building React Native apps for iOS. This guide also assumes you're familiar with the basics of iOS development such as creating a `UIViewController` and editing the `Podfile` file.

### 1. Set up directory structure[​](#1-set-up-directory-structure "Direct link to 1. Set up directory structure")

To ensure a smooth experience, create a new folder for your integrated React Native project, then **move your existing iOS project** to the `/ios` subfolder.

## 2. Install NPM dependencies[​](#2-install-npm-dependencies "Direct link to 2. Install NPM dependencies")

Go to the root directory and run the following command:

shell

```
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.87-stable/template/package.json
```

This will copy the `package.json` [file from the Community template](https://github.com/react-native-community/template/blob/0.87-stable/template/package.json) to your project.

Next, install the NPM packages by running:

* npm
* Yarn

```
npm install
```

```
yarn install
```

Installation process has created a new `node_modules` folder. This folder stores all the JavaScript dependencies required to build your project.

Add `node_modules/` to your `.gitignore` file (here the [Community default one](https://github.com/react-native-community/template/blob/0.87-stable/template/_gitignore)).

### 3. Install Development tools[​](#3-install-development-tools "Direct link to 3. Install Development tools")

### Command Line Tools for Xcode[​](#command-line-tools-for-xcode "Direct link to Command Line Tools for Xcode")

Install the Command Line Tools. Choose **Settings... (or Preferences...)** in the Xcode menu. Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown.

### CocoaPods[​](#cocoapods "Direct link to CocoaPods")

[CocoaPods](https://cocoapods.org) is a package management tool for iOS and macOS development. We use it to add the actual React Native framework code locally into your current project.

We recommend installing CocoaPods using [Homebrew](https://brew.sh/):

```
brew install cocoapods
```

```
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.87-stable/template/Gemfile
```

This will download the Gemfile from the template.

note

If you created your project with Xcode 16, you need to update the Gemfile as it follows:

Diff

```
-gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1'

+gem 'cocoapods', '1.16.2'

gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0'

-gem 'xcodeproj', '< 1.26.0'

+gem 'xcodeproj', '1.27.0'
```

Xcode 16 generates a project in a slightly different ways from previous versions of Xcode, and you need the latest CocoaPods and Xcodeproj gems to make it work properly.

Similarly, for the **Podfile**, go to the `ios` folder of your project and run

shell

```
curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.87-stable/template/ios/Podfile
```

Please use the Community Template as a reference point for the [Gemfile](https://github.com/react-native-community/template/blob/0.87-stable/template/Gemfile) and for the [Podfile](https://github.com/react-native-community/template/blob/0.87-stable/template/ios/Podfile).

note

Remember to change [this line](https://github.com/react-native-community/template/blob/0.87-stable/template/ios/Podfile#L17).

Now, we need to run a couple of extra commands to install the Ruby gems and the Pods. Navigate to the `ios` folder and run the following commands:

```
bundle install

bundle exec pod install
```

Our `index.js` should look as follows (here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.87-stable/template/index.js)):

JavaScript

```
import {AppRegistry} from 'react-native';

import App from './App';



AppRegistry.registerComponent('HelloWorld', () => App);
```

### Create a `App.tsx` file[​](#create-a-apptsx-file "Direct link to create-a-apptsx-file")

Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX](https://en.wikipedia.org/wiki/JSX_\(JavaScript\)) expressions. It contains the root React Native component that we will integrate into our iOS application ([link](https://github.com/react-native-community/template/blob/0.87-stable/template/App.tsx)):

React TSX

```
import {type JSX} from 'react';

import {

  SafeAreaView,

  ScrollView,

  StatusBar,

  StyleSheet,

  Text,

  useColorScheme,

  View,

} from 'react-native';



import {

  Colors,

  DebugInstructions,

  Header,

  ReloadInstructions,

} from 'react-native/Libraries/NewAppScreen';



function App(): JSX.Element {

  const isDarkMode = useColorScheme() === 'dark';



  const backgroundStyle = {

    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,

  };



  return (

    <SafeAreaView style={backgroundStyle}>

      <StatusBar

        barStyle={isDarkMode ? 'light-content' : 'dark-content'}

        backgroundColor={backgroundStyle.backgroundColor}

      />

      <ScrollView

        contentInsetAdjustmentBehavior="automatic"

        style={backgroundStyle}>

        <Header />

        <View

          style={{

            backgroundColor: isDarkMode

              ? Colors.black

              : Colors.white,

            padding: 24,

          }}>

          <Text style={styles.title}>Step One</Text>

          <Text>

            Edit <Text style={styles.bold}>App.tsx</Text> to

            change this screen and see your edits.

          </Text>

          <Text style={styles.title}>See your changes</Text>

          <ReloadInstructions />

          <Text style={styles.title}>Debug</Text>

          <DebugInstructions />

        </View>

      </ScrollView>

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  title: {

    fontSize: 24,

    fontWeight: '600',

  },

  bold: {

    fontWeight: '700',

  },

});



export default App;
```

Here is the [Community template file as reference](https://github.com/react-native-community/template/blob/0.87-stable/template/App.tsx).

## 5. Integrating with your iOS code[​](#5-integrating-with-your-ios-code "Direct link to 5. Integrating with your iOS code")

We now need to add some native code in order to start the React Native runtime and tell it to render our React components.

### Requirements[​](#requirements "Direct link to Requirements")

React Native initialization is now unbound to any specific part of an iOS app.

React Native can be initialized using a class called `RCTReactNativeFactory`, that takes care of handling the React Native lifecycle for you.

Once the class is initialized, you can either start a React Native view providing a `UIWindow` object, or you can ask for the factory to generate a `UIView` that you can load in any `UIViewController.`

In the following example, we will create a ViewController that can load a React Native view as it's `view`.

```
#import "ReactViewController.h"

+#import <React/RCTBundleURLProvider.h>

+#import <RCTReactNativeFactory.h>

+#import <RCTDefaultReactNativeFactoryDelegate.h>

+#import <RCTAppDependencyProvider.h>





@interface ReactViewController ()



@end



+@interface ReactNativeFactoryDelegate: RCTDefaultReactNativeFactoryDelegate

+@end



-@implementation ReactViewController

+@implementation ReactViewController {

+  RCTReactNativeFactory *_factory;

+  id<RCTReactNativeFactoryDelegate> _factoryDelegate;

+}



 - (void)viewDidLoad {

     [super viewDidLoad];

     // Do any additional setup after loading the view.

+    _factoryDelegate = [ReactNativeFactoryDelegate new];

+    _factoryDelegate.dependencyProvider = [RCTAppDependencyProvider new];

+    _factory = [[RCTReactNativeFactory alloc] initWithDelegate:_factoryDelegate];

+    self.view = [_factory.rootViewFactory viewWithModuleName:@"HelloWorld"];

 }



@end



+@implementation ReactNativeFactoryDelegate

+

+- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge

+{

+  return [self bundleURL];

+}

+

+- (NSURL *)bundleURL

+{

+#if DEBUG

+  return [RCTBundleURLProvider.sharedSettings jsBundleURLForBundleRoot:@"index"];

+#else

+  return [NSBundle.mainBundle URLForResource:@"main" withExtension:@"jsbundle"];

+#endif

+}



@end
```

Now open the `ReactViewController.swift` file and apply the following changes

ReactViewController.swift

```
import UIKit

+import React

+import React_RCTAppDelegate

+import ReactAppDependencyProvider



class ReactViewController: UIViewController {

+  var reactNativeFactory: RCTReactNativeFactory?

+  var reactNativeFactoryDelegate: RCTReactNativeFactoryDelegate?



  override func viewDidLoad() {

    super.viewDidLoad()

+    reactNativeFactoryDelegate = ReactNativeDelegate()

+    reactNativeFactoryDelegate!.dependencyProvider = RCTAppDependencyProvider()

+    reactNativeFactory = RCTReactNativeFactory(delegate: reactNativeFactoryDelegate!)

+    view = reactNativeFactory!.rootViewFactory.view(withModuleName: "HelloWorld")



  }

}



+class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate {

+    override func sourceURL(for bridge: RCTBridge) -> URL? {

+      self.bundleURL()

+    }

+

+    override func bundleURL() -> URL? {

+      #if DEBUG

+      RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")

+      #else

+      Bundle.main.url(forResource: "main", withExtension: "jsbundle")

+      #endif

+    }

+

+}
```

#### Presenting a React Native view in a rootViewController[​](#presenting-a-react-native-view-in-a-rootviewcontroller "Direct link to Presenting a React Native view in a rootViewController")

Finally, we can present our React Native view. To do so, we need a new View Controller that can host a view in which we can load the JS content. We already have the initial `ViewController`, and we can make it present the `ReactViewController`. There are several ways to do so, depending on your app. For this example, we assume that you have a button that presents React Native modally.

* ObjectiveC
* Swift

ViewController.m

```
#import "ViewController.h"

+#import "ReactViewController.h"



@interface ViewController ()



@end



- @implementation ViewController

+@implementation ViewController {

+  ReactViewController *reactViewController;

+}



 - (void)viewDidLoad {

   [super viewDidLoad];

   // Do any additional setup after loading the view.

   self.view.backgroundColor = UIColor.systemBackgroundColor;

+  UIButton *button = [UIButton new];

+  [button setTitle:@"Open React Native" forState:UIControlStateNormal];

+  [button setTitleColor:UIColor.systemBlueColor forState:UIControlStateNormal];

+  [button setTitleColor:UIColor.blueColor forState:UIControlStateHighlighted];

+  [button addTarget:self action:@selector(presentReactNative) forControlEvents:UIControlEventTouchUpInside];

+  [self.view addSubview:button];



+  button.translatesAutoresizingMaskIntoConstraints = NO;

+  [NSLayoutConstraint activateConstraints:@[

+    [button.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],

+    [button.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],

+    [button.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor],

+    [button.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],

+  ]];

 }



+- (void)presentReactNative

+{

+  if (reactViewController == NULL) {

+    reactViewController = [ReactViewController new];

+  }

+  [self presentViewController:reactViewController animated:YES];

+}



@end
```

ViewController.swift

```
import UIKit



class ViewController: UIViewController {



+  var reactViewController: ReactViewController?



  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view.

    self.view.backgroundColor = .systemBackground



+    let button = UIButton()

+    button.setTitle("Open React Native", for: .normal)

+    button.setTitleColor(.systemBlue, for: .normal)

+    button.setTitleColor(.blue, for: .highlighted)

+    button.addAction(UIAction { [weak self] _ in

+      guard let self else { return }

+      if reactViewController == nil {

+       reactViewController = ReactViewController()

+      }

+      present(reactViewController!, animated: true)

+    }, for: .touchUpInside)

+    self.view.addSubview(button)

+

+    button.translatesAutoresizingMaskIntoConstraints = false

+    NSLayoutConstraint.activate([

+      button.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),

+      button.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),

+      button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),

+      button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),

+    ])

  }

}
```

Make sure to disable the Sandbox scripting. To achieve this, in Xcode, click on your app, then on build settings. Filter for script and set the `User Script Sandboxing` to `NO`. This step is needed to properly switch between the Debug and Release version of the [Hermes engine](https://github.com/facebook/hermes/blob/main/README.md) that we ship with React Native.

Finally, make sure to add the `UIViewControllerBasedStatusBarAppearance` key into your `Info.plist` file, with value of `NO`.

## 6. Test your integration[​](#6-test-your-integration "Direct link to 6. Test your integration")

You have completed all the basic steps to integrate React Native with your application. Now we will start the [Metro bundler](https://metrobundler.dev/) to build your TypeScript application code into a bundle. Metro's HTTP server shares the bundle from `localhost` on your developer environment to a simulator or device. This allows for [hot reloading](https://reactnative.dev/blog/2016/03/24/introducing-hot-reloading).

First, you need to create a `metro.config.js` file in the root of your project as follows:

JavaScript

```
const {getDefaultConfig} = require('@react-native/metro-config');

module.exports = getDefaultConfig(__dirname);
```

You can checkout the [`metro.config.js` file](https://github.com/react-native-community/template/blob/0.87-stable/template/metro.config.js) from the Community template file as reference.

Then, you need to create a `.watchmanconfig` file in the root of your project. The file must contain an empty json object:

```
echo {} > .watchmanconfig
```

Once you have the configuration file in place, you can run the bundler. Run the following command in the root directory of your project:

* npm
* Yarn

```
npm start
```

```
yarn start
```

```
set -e



WITH_ENVIRONMENT="$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh"

REACT_NATIVE_XCODE="$REACT_NATIVE_PATH/scripts/react-native-xcode.sh"



/bin/sh -c "$WITH_ENVIRONMENT $REACT_NATIVE_XCODE"
```

6. Drag and drop the script before the one called `[CP] Embed Pods Frameworks`.

Now, if you build your app for Release, it will work as expected.

## 7. Passing initial props to the React Native view[​](#7-passing-initial-props-to-the-react-native-view "Direct link to 7. Passing initial props to the React Native view")

In some case, you'd like to pass some information from the Native app to JavaScript. For example, you might want to pass the user id of the currently logged user to React Native, together with a token that can be used to retrieve information from a database.

This is possible by using the `initialProperties` parameter of the `view(withModuleName:initialProperty)` overload of the `RCTReactNativeFactory` class. The following steps shows you how to do it.

### Update the App.tsx file to read the initial properties.[​](#update-the-apptsx-file-to-read-the-initial-properties "Direct link to Update the App.tsx file to read the initial properties.")

Open the `App.tsx` file and add the following code:

App.tsx

```
import {

  Colors,

  DebugInstructions,

  Header,

  ReloadInstructions,

} from 'react-native/Libraries/NewAppScreen';



-function App(): React.JSX.Element {

+function App(props): React.JSX.Element {

  const isDarkMode = useColorScheme() === 'dark';



  const backgroundStyle = {

    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,

  };



  return (

    <SafeAreaView style={backgroundStyle}>

      <StatusBar

        barStyle={isDarkMode ? 'light-content' : 'dark-content'}

        backgroundColor={backgroundStyle.backgroundColor}

      />

      <ScrollView

        contentInsetAdjustmentBehavior="automatic"

        style={backgroundStyle}>

        <Header />

-       <View

-         style={{

-           backgroundColor: isDarkMode

-             ? Colors.black

-             : Colors.white,

-           padding: 24,

-         }}>

-         <Text style={styles.title}>Step One</Text>

-         <Text>

-           Edit <Text style={styles.bold}>App.tsx</Text> to

-           change this screen and see your edits.

-         </Text>

-         <Text style={styles.title}>See your changes</Text>

-         <ReloadInstructions />

-         <Text style={styles.title}>Debug</Text>

-         <DebugInstructions />

+         <Text style={styles.title}>UserID: {props.userID}</Text>

+         <Text style={styles.title}>Token: {props.token}</Text>

        </View>

      </ScrollView>

    </SafeAreaView>

  );

}



const styles = StyleSheet.create({

  title: {

    fontSize: 24,

    fontWeight: '600',

+   marginLeft: 20,

  },

  bold: {

    fontWeight: '700',

  },

});



export default App;
```

These changes will tell React Native that your App component is now accepting some properties. The `RCTreactNativeFactory` will take care of passing them to the component when it's rendered.

### Update the Native code to pass the initial properties to JavaScript.[​](#update-the-native-code-to-pass-the-initial-properties-to-javascript "Direct link to Update the Native code to pass the initial properties to JavaScript.")

* ObjectiveC
* Swift

Modify the `ReactViewController.mm` to pass the initial properties to JavaScript.

ReactViewController.mm

```
 - (void)viewDidLoad {

   [super viewDidLoad];

   // Do any additional setup after loading the view.



   _factoryDelegate = [ReactNativeFactoryDelegate new];

   _factoryDelegate.dependencyProvider = [RCTAppDependencyProvider new];

   _factory = [[RCTReactNativeFactory alloc] initWithDelegate:_factoryDelegate];

-  self.view = [_factory.rootViewFactory viewWithModuleName:@"HelloWorld"];

+  self.view = [_factory.rootViewFactory viewWithModuleName:@"HelloWorld" initialProperties:@{

+    @"userID": @"12345678",

+    @"token": @"secretToken"

+  }];

}
```

Modify the `ReactViewController.swift` to pass the initial properties to the React Native view.

ReactViewController.swift

```
  override func viewDidLoad() {

    super.viewDidLoad()

    reactNativeFactoryDelegate = ReactNativeDelegate()

    reactNativeFactoryDelegate!.dependencyProvider = RCTAppDependencyProvider()

    reactNativeFactory = RCTReactNativeFactory(delegate: reactNativeFactoryDelegate!)

-   view = reactNativeFactory!.rootViewFactory.view(withModuleName: "HelloWorld")

+   view = reactNativeFactory!.rootViewFactory.view(withModuleName: "HelloWorld" initialProperties: [

+     "userID": "12345678",

+     "token": "secretToken"

+])



  }

}
```

3. Run your app once again. You should see the following screen after you present the `ReactViewController`:

## Now what?[​](#now-what "Direct link to Now what?")

At this point you can continue developing your app as usual. Refer to our [debugging](/docs/debugging) and [deployment](/docs/running-on-device) docs to learn more about working with React Native.

----
url: https://reactnative.dev/docs/next/debugging
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/debugging)** (0.87).

Version: Next

[React Native DevTools](/docs/next/react-native-devtools) is our built-in debugger for React Native. It allows you to inspect and understand how your JavaScript code is running, similar to a web browser.

To open DevTools, either:

* Select "Open DevTools" in the Dev Menu.
* Press `j` from the CLI.

On first launch, DevTools will open to a welcome panel, along with an open console drawer where you can view logs and interact with the JavaScript runtime. From the top of the window, you can navigate to other panels, including the integrated React Components Inspector and Profiler.

Learn more in our [React Native DevTools guide](/docs/next/react-native-devtools).

```
import {LogBox} from 'react-native';
```

#### Ignore all logs[​](#ignore-all-logs "Direct link to Ignore all logs")

LogBox notifications can be disabled using `LogBox.ignoreAllLogs()`. This can be useful in situations such as giving product demos.

JavaScript

```
LogBox.ignoreAllLogs();
```

#### Ignore specific logs[​](#ignore-specific-logs "Direct link to Ignore specific logs")

Notifications can be disabled on a per-log basis via `LogBox.ignoreLogs()`. This can be useful for noisy warnings or those that cannot be fixed, e.g. in a third-party dependency.

JavaScript

```
LogBox.ignoreLogs([

  // Exact message

  'Warning: componentWillReceiveProps has been renamed',



  // Substring or regex match

  /GraphQL error: .*/,

]);
```

----
url: https://reactnative.dev/docs/appendix
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

| Flow                                     | TypeScript                      | Flow Nullable Support      | TypeScript Nullable Support     | Android (Java)                       | iOS (ObjC)                                                     |
| ---------------------------------------- | ------------------------------- | -------------------------- | ------------------------------- | ------------------------------------ | -------------------------------------------------------------- |
| `string`                                 | `string`                        | `?string`                  | `string \| null`                | `string`                             | `NSString`                                                     |
| `boolean`                                | `boolean`                       | `?boolean`                 | `boolean \| null`               | `Boolean`                            | `NSNumber`                                                     |
| Object Literal `{\| foo: string, ...\|}` | `{ foo: string, ...} as const`  | `?{\| foo: string, ...\|}` | `?{ foo: string, ...} as const` | -                                    | -                                                              |
| Object \[[1](#notes)]                    | Object \[[1](#notes)]           | `?Object`                  | `Object \| null`                | `ReadableMap`                        | `@` (untyped dictionary)                                       |
| `Array<T>`                               | `Array<T>`                      | `?Array<T>`                | `Array<T> \| null`              | `ReadableArray`                      | `NSArray` (or `RCTConvertVecToArray` when used inside objects) |
| `Function`                               | `Function`                      | `?Function`                | `Function \| null`              | -                                    | -                                                              |
| `Promise<T>`                             | `Promise<T>`                    | `?Promise<T>`              | `Promise<T> \| null`            | `com.facebook.react.bridge.Promise`  | `RCTPromiseResolve` and `RCTPromiseRejectBlock`                |
| Type Unions `'SUCCESS'\|'FAIL'`          | Type Unions `'SUCCESS'\|'FAIL'` | Only as callbacks          |                                 | -                                    | -                                                              |
| Callbacks `() =>`                        | Callbacks `() =>`               | Yes                        |                                 | `com.facebook.react.bridge.Callback` | `RCTResponseSenderBlock`                                       |
| `number`                                 | `number`                        | No                         |                                 | `double`                             | `NSNumber`                                                     |

----
url: https://reactnative.dev/docs/shadow-props
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

* TypeScript
* JavaScript

***

# Reference

There are 3 sets of shadow APIs in React Native:

* `boxShadow`: A View style prop and a spec-compliant implementation of the [web style prop of the same name](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow).
* `dropShadow`: A specific filter function available as part of the [`filter`](/docs/view-style-props#filter) View style prop.

See [View Style Props](/docs/view-style-props#boxshadow) for documentation.

### `dropShadow`Android[​](#dropshadow-android "Direct link to dropshadow-android")

See [View Style Props](/docs/view-style-props#filter) for documentation.

### `shadowColor`[​](#shadowcolor "Direct link to shadowcolor")

Sets the drop shadow color.

This property will only work on Android API 28 and above. For similar functionality on lower Android APIs, use the [`elevation` property](/docs/view-style-props#elevation-android).

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `shadowOffset`iOS[​](#shadowoffset-ios "Direct link to shadowoffset-ios")

Sets the drop shadow offset.

| Type                                     |
| ---------------------------------------- |
| object: `{width: number,height: number}` |

***

### `shadowOpacity`iOS[​](#shadowopacity-ios "Direct link to shadowopacity-ios")

Sets the drop shadow opacity (multiplied by the color's alpha component).

| Type   |
| ------ |
| number |

***

### `shadowRadius`iOS[​](#shadowradius-ios "Direct link to shadowradius-ios")

Sets the drop shadow blur radius.

| Type   |
| ------ |
| number |

* [Props](#props)

  * [`boxShadow`](#boxshadow)
  * [`dropShadow`](#dropshadow-android)

    [Android](#dropshadow-android)
  * [`shadowColor`](#shadowcolor)
  * [`shadowOffset`](#shadowoffset-ios)

    [iOS](#shadowoffset-ios)
  * [`shadowOpacity`](#shadowopacity-ios)

    [iOS](#shadowopacity-ios)
  * [`shadowRadius`](#shadowradius-ios)

    [iOS](#shadowradius-ios)

----
url: https://reactnative.dev/docs/legacy/direct-manipulation
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
const viewRef = useRef<View>();

const setOpacityTo = useCallback(value => {

  // Redacted: animation related code

  viewRef.current.setNativeProps({

    opacity: 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:

React TSX

```
<TouchableOpacity onPress={handlePress}>

  <View>

    <Text>Press me!</Text>

  </View>

</TouchableOpacity>
```

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:

React TSX

```
const [buttonOpacity, setButtonOpacity] = useState(1);

return (

  <TouchableOpacity

    onPressIn={() => setButtonOpacity(0.5)}

    onPressOut={() => setButtonOpacity(1)}>

    <View style={{opacity: buttonOpacity}}>

      <Text>Press me!</Text>

    </View>

  </TouchableOpacity>

);
```

You may have noticed that we passed all of the props down to the child view using `{...props}`. The reason for this is that `TouchableOpacity` is actually a composite component, and so in addition to depending on `setNativeProps` on its child, it also requires that the child perform touch handling. To do this, it passes on [various props](/docs/view#onmoveshouldsetresponder) that call back to the `TouchableOpacity` component. `TouchableHighlight`, in contrast, is backed by a native view and only requires that we implement `setNativeProps`.

## setNativeProps to edit TextInput value[​](#setnativeprops-to-edit-textinput-value "Direct link to setNativeProps to edit TextInput value")

Another very common use case of `setNativeProps` is to edit the value of the TextInput. The `controlled` prop of TextInput can sometimes drop characters when the `bufferDelay` is low and the user types very quickly. Some developers prefer to skip this prop entirely and instead use `setNativeProps` to directly manipulate the TextInput value when necessary. For example, the following code demonstrates editing the input when you tap a button:

* TypeScript
* JavaScript

You can use the [`clear`](/docs/textinput#clear) method to clear the `TextInput` which clears the current input text using the same approach.

Note that these measurements are not available until after the rendering has been completed in native. If you need the measurements as soon as possible and you don't need `pageX` and `pageY`, consider using the [`onLayout`](/docs/view#onlayout) property instead.

Also the width and height returned by `measure()` are the width and height of the component in the viewport. If you need the actual size of the component, consider using the [`onLayout`](/docs/view#onlayout) property instead.

----
url: https://reactnative.dev/docs/text
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

A React component for displaying text.

`Text` supports nesting, styling, and touch handling.

In the following example, the nested title and body text will inherit the `fontFamily` from `styles.baseText`, but the title provides its own additional styles. The title and body will stack on top of each other on account of the literal newlines:

## Nested text[​](#nested-text "Direct link to Nested text")

Both Android and iOS allow you to display formatted text by annotating ranges of a string with specific formatting like bold or colored text (`NSAttributedString` on iOS, `SpannableString` on Android). In practice, this is very tedious. For React Native, we decided to use the web paradigm for this, where you can nest text to achieve the same effect.

Behind the scenes, React Native converts this to a flat `NSAttributedString` or `SpannableString` that contains the following information:

```
"I am bold and red"

0-9: bold

9-17: bold, red
```

## Containers[​](#containers "Direct link to Containers")

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.

React TSX

```
<Text>

  <Text>First part and </Text>

  <Text>second part</Text>

</Text>

// Text container: the text will be inline, if the space allows it

// |First part and second part|



// otherwise, the text will flow as if it was one

// |First part |

// |and second |

// |part       |



<View>

  <Text>First part and </Text>

  <Text>second part</Text>

</View>

// View container: each text is its own block

// |First part and|

// |second part   |



// otherwise, the text will flow in its own block

// |First part |

// |and        |

// |second part|
```

## Limited Style Inheritance[​](#limited-style-inheritance "Direct link to Limited Style Inheritance")

On the web, the usual way to set a font family and size for the entire document is to take advantage of inherited CSS properties like so:

CSS

```
html {

  font-family:

    'lucida grande', tahoma, verdana, arial, sans-serif;

  font-size: 11px;

  color: #141823;

}
```

All elements in the document will inherit this font unless they or one of their parents specifies a new rule.

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>`.

React TSX

```
// BAD: will raise exception, can't have a text node as child of a <View>

<View>

  Some text

</View>



// GOOD

<View>

  <Text>

    Some text

  </Text>

</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.

React TSX

```
<View>

  <MyAppText>

    Text styled with the default font for the entire application

  </MyAppText>

  <MyAppHeaderText>Text styled as a header</MyAppHeaderText>

</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:

React TSX

```
const MyAppHeaderText = ({children}) => {

  return (

    <MyAppText>

      <Text style={{fontSize: 20}}>{children}</Text>

    </MyAppText>

  );

};
```

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.

React TSX

```
<Text style={{fontWeight: 'bold'}}>

  I am bold

  <Text style={{color: 'red'}}>and red</Text>

</Text>
```

We believe that this more constrained way to style text will yield better apps:

* (Developer) React components are designed with strong isolation in mind: You should be able to drop a component anywhere in your application, trusting that as long as the props are the same, it will look and behave the same way. Text properties that could inherit from outside of the props would break this isolation.

* (Implementor) The implementation of React Native is also simplified. We do not need to have a `fontFamily` field on every single element, and we do not need to potentially traverse the tree up to the root every time we display a text node. The style inheritance is only encoded inside of the native Text component and doesn't leak to other components or the system itself.

***

# Reference

## Props[​](#props "Direct link to Props")

### `accessibilityHint`[​](#accessibilityhint "Direct link to accessibilityhint")

An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not clear from the accessibility label.

| Type   |
| ------ |
| string |

***

### `accessibilityLanguage`iOS[​](#accessibilitylanguage-ios "Direct link to accessibilitylanguage-ios")

A value indicating which language should be used by the screen reader when the user interacts with the element. It should follow the [BCP 47 specification](https://www.rfc-editor.org/info/bcp47).

See the [iOS `accessibilityLanguage` doc](https://developer.apple.com/documentation/objectivec/nsobject/1615192-accessibilitylanguage) for more information.

| Type   |
| ------ |
| string |

***

### `accessibilityLabel`[​](#accessibilitylabel "Direct link to accessibilitylabel")

Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the `Text` nodes separated by space.

| Type   |
| ------ |
| string |

***

### `accessibilityRole`[​](#accessibilityrole "Direct link to accessibilityrole")

Tells the screen reader to treat the currently focused on element as having a specific role.

On iOS, these roles map to corresponding Accessibility Traits. Image button has the same functionality as if the trait was set to both 'image' and 'button'. See the [Accessibility guide](/docs/accessibility#accessibilityrole) for more information.

On Android, these roles have similar functionality on TalkBack as adding Accessibility Traits does on Voiceover in iOS

| Type                                                       |
| ---------------------------------------------------------- |
| [AccessibilityRole](/docs/accessibility#accessibilityrole) |

***

### `accessibilityState`[​](#accessibilitystate "Direct link to accessibilitystate")

Tells the screen reader to treat the currently focused on element as being in a specific state.

You can provide one state, no state, or multiple states. The states must be passed in through an object, e.g. `{selected: true, disabled: true}`.

| Type                                                         |
| ------------------------------------------------------------ |
| [AccessibilityState](/docs/accessibility#accessibilitystate) |

***

### `accessibilityActions`[​](#accessibilityactions "Direct link to accessibilityactions")

Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. The `accessibilityActions` property should contain a list of action objects. Each action object should contain the field name and label.

See the [Accessibility guide](/docs/accessibility#accessibility-actions) for more information.

| Type  | Required |
| ----- | -------- |
| array | No       |

***

### `onAccessibilityAction`[​](#onaccessibilityaction "Direct link to onaccessibilityaction")

Invoked when the user performs the accessibility actions. The only argument to this function is an event containing the name of the action to perform.

See the [Accessibility guide](/docs/accessibility#accessibility-actions) for more information.

| Type     | Required |
| -------- | -------- |
| function | No       |

***

### `accessible`[​](#accessible "Direct link to accessible")

When set to `true`, indicates that the view is an accessibility element.

See the [Accessibility guide](/docs/accessibility#accessible) for more information.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

***

### `adjustsFontSizeToFit`[​](#adjustsfontsizetofit "Direct link to adjustsfontsizetofit")

Specifies whether fonts should be scaled down automatically to fit given style constraints.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `allowFontScaling`[​](#allowfontscaling "Direct link to allowfontscaling")

Specifies whether fonts should scale to respect Text Size accessibility settings.

| Type    | Default |
| ------- | ------- |
| boolean | `true`  |

***

### `android_hyphenationFrequency`Android[​](#android_hyphenationfrequency-android "Direct link to android_hyphenationfrequency-android")

Sets the frequency of automatic hyphenation to use when determining word breaks on Android API Level 23+.

| Type                                | Default  |
| ----------------------------------- | -------- |
| enum(`'none'`, `'normal'`,`'full'`) | `'none'` |

***

### `aria-busy`[​](#aria-busy "Direct link to aria-busy")

Indicates an element is being modified and that assistive technologies may want to wait until the changes are complete before informing the user about the update.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-checked`[​](#aria-checked "Direct link to aria-checked")

Indicates the state of a checkable element. This field can either take a boolean or the "mixed" string to represent mixed checkboxes.

| Type             | Default |
| ---------------- | ------- |
| boolean, 'mixed' | false   |

***

### `aria-disabled`[​](#aria-disabled "Direct link to aria-disabled")

Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-expanded`[​](#aria-expanded "Direct link to aria-expanded")

Indicates whether an expandable element is currently expanded or collapsed.

| Type    | Default |
| ------- | ------- |
| boolean | false   |

***

### `aria-label`[​](#aria-label "Direct link to aria-label")

Defines a string value that labels an interactive element.

| Type   |
| ------ |
| string |

***

### `aria-selected`[​](#aria-selected "Direct link to aria-selected")

Indicates whether a selectable element is currently selected or not.

| Type    |
| ------- |
| boolean |

### `dataDetectorType`Android[​](#datadetectortype-android "Direct link to datadetectortype-android")

Determines the types of data converted to clickable URLs in the text element. By default, no data types are detected.

You can provide only one type.

| Type                                                          | Default  |
| ------------------------------------------------------------- | -------- |
| enum(`'phoneNumber'`, `'link'`, `'email'`, `'none'`, `'all'`) | `'none'` |

***

### `disabled`Android[​](#disabled-android "Direct link to disabled-android")

Specifies the disabled state of the text view for testing purposes.

| Type | Default |
| ---- | ------- |
| bool | `false` |

***

### `dynamicTypeRamp`iOS[​](#dynamictyperamp-ios "Direct link to dynamictyperamp-ios")

The [Dynamic Type](https://developer.apple.com/documentation/uikit/uifont/scaling_fonts_automatically) ramp to apply to this element on iOS.

| Type                                                                                                                                                     | Default  |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| enum(`'caption2'`, `'caption1'`, `'footnote'`, `'subheadline'`, `'callout'`, `'body'`, `'headline'`, `'title3'`, `'title2'`, `'title1'`, `'largeTitle'`) | `'body'` |

***

| Type                                           | Default |
| ---------------------------------------------- | ------- |
| enum(`'head'`, `'middle'`, `'tail'`, `'clip'`) | `tail`  |

***

### `id`[​](#id "Direct link to id")

Used to locate this view from native code. Has precedence over `nativeID` prop.

| Type   |
| ------ |
| string |

***

### `maxFontSizeMultiplier`[​](#maxfontsizemultiplier "Direct link to maxfontsizemultiplier")

Specifies the largest possible scale a font can reach when `allowFontScaling` is enabled. Possible values:

* `null/undefined`: inherit from the parent node or the global default (0)
* `0`: no max, ignore parent/global default
* `>= 1`: sets the `maxFontSizeMultiplier` of this node to this value

| Type   | Default     |
| ------ | ----------- |
| number | `undefined` |

***

### `minimumFontScale`[​](#minimumfontscale "Direct link to minimumfontscale")

Specifies the smallest possible scale a font can reach when `adjustsFontSizeToFit` is enabled. (values 0.01-1.0).

| Type   |
| ------ |
| number |

***

### `nativeID`[​](#nativeid "Direct link to nativeid")

Used to locate this view from native code.

| Type   |
| ------ |
| string |

***

### `numberOfLines`[​](#numberoflines "Direct link to numberoflines")

Used to truncate the text with an ellipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number. Setting this property to `0` will result in unsetting this value, which means that no lines restriction will be applied.

This prop is commonly used with `ellipsizeMode`.

| Type   | Default |
| ------ | ------- |
| number | `0`     |

***

### `onLayout`[​](#onlayout "Direct link to onlayout")

Invoked on mount and on layout changes.

| Type                                   |
| -------------------------------------- |
| `({nativeEvent: LayoutEvent}) => void` |

***

### `onLongPress`[​](#onlongpress "Direct link to onlongpress")

This function is called on long press.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onMoveShouldSetResponder`[​](#onmoveshouldsetresponder "Direct link to onmoveshouldsetresponder")

Does this view want to "claim" touch responsiveness? This is called for every touch move on the `View` when it is not the responder.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onPress`[​](#onpress "Direct link to onpress")

Function called on user press, triggered after `onPressOut`.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onPressIn`[​](#onpressin "Direct link to onpressin")

Called immediately when a touch is engaged, before `onPressOut` and `onPress`.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onPressOut`[​](#onpressout "Direct link to onpressout")

Called when a touch is released.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderGrant`[​](#onrespondergrant "Direct link to onrespondergrant")

The View is now responding to touch events. This is the time to highlight and show the user what is happening.

On Android, return true from this callback to prevent any other native components from becoming responder until this responder terminates.

| Type                                            |
| ----------------------------------------------- |
| `({nativeEvent: PressEvent}) => void ｜ boolean` |

***

### `onResponderMove`[​](#onrespondermove "Direct link to onrespondermove")

The user is moving their finger.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderRelease`[​](#onresponderrelease "Direct link to onresponderrelease")

Fired at the end of the touch.

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderTerminate`[​](#onresponderterminate "Direct link to onresponderterminate")

The responder has been taken from the `View`. Might be taken by other views after a call to `onResponderTerminationRequest`, or might be taken by the OS without asking (e.g., happens with control center/ notification center on iOS)

| Type                                  |
| ------------------------------------- |
| `({nativeEvent: PressEvent}) => void` |

***

### `onResponderTerminationRequest`[​](#onresponderterminationrequest "Direct link to onresponderterminationrequest")

Some other `View` wants to become a responder and is asking this `View` to release its responder. Returning `true` allows its release.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onStartShouldSetResponderCapture`[​](#onstartshouldsetrespondercapture "Direct link to onstartshouldsetrespondercapture")

If a parent `View` wants to prevent a child `View` from becoming a responder on a touch start, it should have this handler which returns `true`.

| Type                                     |
| ---------------------------------------- |
| `({nativeEvent: PressEvent}) => boolean` |

***

### `onTextLayout`[​](#ontextlayout "Direct link to ontextlayout")

Invoked on Text layout change.

| Type                                                       |
| ---------------------------------------------------------- |
| ([`TextLayoutEvent`](/docs/text#textlayoutevent)) => mixed |

***

### `pressRetentionOffset`[​](#pressretentionoffset "Direct link to pressretentionoffset")

When the scroll view is disabled, this defines how far your touch may move off of the button, before deactivating the button. Once deactivated, try moving it back and you'll see that the button is once again reactivated! Move it back and forth several times while the scroll view is disabled. Ensure you pass in a constant to reduce memory allocations.

| Type                       |
| -------------------------- |
| [Rect](/docs/rect), number |

***

### `ref`[​](#ref "Direct link to ref")

A ref setter that will be assigned an [element node](/docs/element-nodes) when mounted.

Note that `Text` components don't provide text nodes, the same way that paragraph elements (`<p>`) on Web are element nodes instead of text nodes. Text nodes can be found as their child nodes instead.

***

### `role`[​](#role "Direct link to role")

`role` communicates the purpose of a component to the user of an assistive technology. Has precedence over the [`accessibilityRole`](/docs/text#accessibilityrole) prop.

| Type                             |
| -------------------------------- |
| [Role](/docs/accessibility#role) |

***

### `selectable`[​](#selectable "Direct link to selectable")

Lets the user select text, to use the native copy and paste functionality.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `selectionColor`Android[​](#selectioncolor-android "Direct link to selectioncolor-android")

The highlight color of the text.

| Type                  |
| --------------------- |
| [color](/docs/colors) |

***

### `style`[​](#style "Direct link to style")

| Type                                                                             |
| -------------------------------------------------------------------------------- |
| [Text Style](/docs/text-style-props), [View Style Props](/docs/view-style-props) |

***

### `suppressHighlighting`iOS[​](#suppresshighlighting-ios "Direct link to suppresshighlighting-ios")

When `true`, no visual change is made when text is pressed down. By default, a gray oval highlights the text on press down.

| Type    | Default |
| ------- | ------- |
| boolean | `false` |

***

### `testID`[​](#testid "Direct link to testid")

Used to locate this view in end-to-end tests.

| Type   |
| ------ |
| string |

***

### `textBreakStrategy`Android[​](#textbreakstrategy-android "Direct link to textbreakstrategy-android")

Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced`.

| Type                                            | Default       |
| ----------------------------------------------- | ------------- |
| enum(`'simple'`, `'highQuality'`, `'balanced'`) | `highQuality` |

***

### `lineBreakStrategyIOS`iOS[​](#linebreakstrategyios-ios "Direct link to linebreakstrategyios-ios")

Set line break strategy on iOS 14+. Possible values are `none`, `standard`, `hangul-word` and `push-out`.

| Type                                                        | Default  |
| ----------------------------------------------------------- | -------- |
| enum(`'none'`, `'standard'`, `'hangul-word'`, `'push-out'`) | `'none'` |

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### TextLayout[​](#textlayout "Direct link to TextLayout")

`TextLayout` object is a part of [`TextLayoutEvent`](/docs/text#textlayoutevent) callback and contains the measurement data for `Text` line.

#### Example[​](#example "Direct link to Example")

JavaScript

```
{

    capHeight: 10.496,

    ascender: 14.624,

    descender: 4,

    width: 28.224,

    height: 18.624,

    xHeight: 6.048,

    x: 0,

    y: 0

}
```

#### Properties[​](#properties "Direct link to Properties")

| Name      | Type   | Optional | Description                                                         |
| --------- | ------ | -------- | ------------------------------------------------------------------- |
| ascender  | number | No       | The line ascender height after the text layout changes.             |
| capHeight | number | No       | Height of capital letter above the baseline.                        |
| descender | number | No       | The line descender height after the text layout changes.            |
| height    | number | No       | Height of the line after the text layout changes.                   |
| width     | number | No       | Width of the line after the text layout changes.                    |
| x         | number | No       | Line X coordinate inside the Text component.                        |
| xHeight   | number | No       | Distance between the baseline and median of the line (corpus size). |
| y         | number | No       | Line Y coordinate inside the Text component.                        |

### TextLayoutEvent[​](#textlayoutevent "Direct link to TextLayoutEvent")

`TextLayoutEvent` object is returned in the callback as a result of a component layout change. It contains a key called `lines` with a value which is an array containing [`TextLayout`](/docs/text#textlayout) object corresponded to every rendered text line.

#### Example[​](#example-1 "Direct link to Example")

JavaScript

```
{

  lines: [

    TextLayout,

    TextLayout,

    // ...

  ];

  target: 1127;

}
```

#### Properties[​](#properties-1 "Direct link to Properties")

| Name   | Type                                          | Optional | Description                                           |
| ------ | --------------------------------------------- | -------- | ----------------------------------------------------- |
| lines  | array of [TextLayout](/docs/text#textlayout)s | No       | Provides the TextLayout data for every rendered line. |
| target | number                                        | No       | The node id of the element.                           |

* [Nested text](#nested-text)

* [Containers](#containers)

* [Limited Style Inheritance](#limited-style-inheritance)

* [Props](#props)

  * [`accessibilityHint`](#accessibilityhint)
  * [`accessibilityLanguage`](#accessibilitylanguage-ios)

    [iOS](#accessibilitylanguage-ios)

    [Android](#android_hyphenationfrequency-android)

    [Android](#datadetectortype-android)
  * [`disabled`](#disabled-android)

    [Android](#disabled-android)
  * [`dynamicTypeRamp`](#dynamictyperamp-ios)

    [iOS](#dynamictyperamp-ios)

    [Android](#selectioncolor-android)
  * [`style`](#style)
  * [`suppressHighlighting`](#suppresshighlighting-ios)

    [iOS](#suppresshighlighting-ios)
  * [`testID`](#testid)
  * [`textBreakStrategy`](#textbreakstrategy-android)

    [Android](#textbreakstrategy-android)
  * [`lineBreakStrategyIOS`](#linebreakstrategyios-ios)

    [iOS](#linebreakstrategyios-ios)

* [Type Definitions](#type-definitions)

  * [TextLayout](#textlayout)
  * [TextLayoutEvent](#textlayoutevent)

----
url: https://reactnative.dev/docs/targetevent
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

`TargetEvent` object is returned in the callback as a result of focus change, for example `onFocus` or `onBlur` in the [TextInput](/docs/textinput) component.

## Example[​](#example "Direct link to Example")

```
{

    target: 1127

}
```

## Keys and values[​](#keys-and-values "Direct link to Keys and values")

### `target`[​](#target "Direct link to target")

The node id of the element receiving the TargetEvent.

| Type                        | Optional |
| --------------------------- | -------- |
| number, `null`, `undefined` | No       |

## Used by[​](#used-by "Direct link to Used by")

* [`TextInput`](/docs/textinput)
* [`TouchableWithoutFeedback`](/docs/touchablewithoutfeedback)

- [Example](#example)
- [Keys and values](#keys-and-values)
  * [`target`](#target)
- [Used by](#used-by)

----
url: https://reactnative.dev/docs/components-and-apis
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

React Native provides a number of built-in [Core Components](/docs/intro-react-native-components) ready for you to use in your app. You can find them all in the left sidebar (or menu above, if you are on a narrow screen). If you're not sure where to get started, take a look at the following categories:

* [Basic Components](/docs/components-and-apis#basic-components)
* [User Interface](/docs/components-and-apis#user-interface)
* [List Views](/docs/components-and-apis#list-views)
* [Android-specific](/docs/components-and-apis#android-components-and-apis)
* [iOS-specific](/docs/components-and-apis#ios-components-and-apis)
* [Others](/docs/components-and-apis#others)

You're not limited to the components and APIs bundled with React Native. React Native has a community of thousands of developers. If you're looking for a library that does something specific, please refer to [this guide about finding libraries](/docs/libraries#finding-libraries).

Unlike the more generic [`ScrollView`](/docs/scrollview), the following list view components only render elements that are currently showing on the screen. This makes them a performant choice for displaying long lists of data.

----
url: https://reactnative.dev/docs/global-setInterval
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval) for more information.

The global `setInterval` function, as defined in Web specifications.

----
url: https://reactnative.dev/docs/global-PerformanceObserver
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

The global [`PerformanceObserver`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver) class, as defined in Web specifications.

## Example[​](#example "Direct link to Example")

TypeScript

```
const observer = new PerformanceObserver(

  (list, observer, options) => {

    for (const entry of list.getEntries()) {

      console.log(

        'Received entry with type',

        entry.entryType,

        'and name',

        entry.name,

        'that started at',

        entry.startTime,

        'and took',

        entry.duration,

        'ms',

      );

    }

  },

);



observer.observe({entryTypes: ['mark', 'measure']});
```

***

----
url: https://reactnative.dev/docs/more-resources
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

There’s always more to learn: developer workflows, shipping to app stores, internationalization, security and more.

## Where to go from here[​](#where-to-go-from-here "Direct link to Where to go from here")

* [Set up your environment](/docs/environment-setup)
* [Set up your development workflow](/docs/running-on-device)
* [Design and layout your app](/docs/flexbox)
* [Debug your app](/docs/debugging)
* [Make your app cross platform](/docs/platform-specific-code)

Interested in making your own Native Component or Module? Making modules for your own use case and sharing them with others on NPM and GitHub helps grow the React Native ecosystem and community! Read the guides to making your own Native Modules ([Android](/docs/legacy/native-modules-android), [iOS](/docs/legacy/native-modules-ios)) and Native Components ([Android](/docs/legacy/native-components-android), [iOS](/docs/legacy/native-components-ios)).

* [Where to go from here](#where-to-go-from-here)
* [Dive deep](#dive-deep)
* [IDEs](#ides)
* [Platforms to try](#platforms-to-try)
* [Example Apps](#example-apps)
* [Find, make, and share your own Native Components and TurboModules](#find-make-and-share-your-own-native-components-and-turbomodules)

----
url: https://reactnative.dev/docs/alert
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

Launches an alert dialog with the specified title and message.

Optionally provide a list of buttons. Tapping any button will fire the respective onPress callback and dismiss the alert. By default, the only button will be an 'OK' button.

This is an API that works both on Android and iOS and can show static alerts. Alert that prompts the user to enter some information is available on iOS only.

## Example[​](#example "Direct link to Example")

## iOS[​](#ios "Direct link to iOS")

On iOS you can specify any number of buttons. Each button can optionally specify a style or be emphasized, available options are represented by the [AlertButtonStyle](#alertbuttonstyle-ios) enum and the `isPreferred` field on [AlertButton](/docs/alert#alertbutton).

## Android[​](#android "Direct link to Android")

On Android at most three buttons can be specified. Android has a concept of a neutral, negative and a positive button:

* If you specify one button, it will be the 'positive' one (such as 'OK')
* Two buttons mean 'negative', 'positive' (such as 'Cancel', 'OK')
* Three buttons mean 'neutral', 'negative', 'positive' (such as 'Later', 'Cancel', 'OK')

Alerts on Android can be dismissed by tapping outside of the alert box. It is disabled by default and can be enabled by providing an optional [AlertOptions](/docs/alert#alertoptions) parameter with the cancelable property set to `true` i.e.\
`{cancelable: true}`.

The cancel event can be handled by providing an `onDismiss` callback property inside the `options` parameter.

### ExampleAndroid[​](#example-android "Direct link to example-android")

***

# Reference

## Methods[​](#methods "Direct link to Methods")

### `alert()`[​](#alert "Direct link to alert")

React TSX

```
static alert (

  title: string,

  message?: string,

  buttons?: AlertButton[],

  options?: AlertOptions,

);
```

**Parameters:**

| Name          | Type                                      | Description                                                             |
| ------------- | ----------------------------------------- | ----------------------------------------------------------------------- |
| titleRequired | string                                    | The dialog's title. Passing `null` or empty string will hide the title. |
| message       | string                                    | An optional message that appears below the dialog's title.              |
| buttons       | [AlertButton](/docs/alert#alertbutton)\[] | An optional array containing buttons configuration.                     |
| options       | [AlertOptions](/docs/alert#alertoptions)  | An optional Alert configuration.                                        |

***

### `prompt()`iOS[​](#prompt-ios "Direct link to prompt-ios")

React TSX

```
static prompt: (

  title: string,

  message?: string,

  callbackOrButtons?: ((text: string) => void) | AlertButton[],

  type?: AlertType,

  defaultValue?: string,

  keyboardType?: string,

);
```

Create and display a prompt to enter some text in form of Alert.

**Parameters:**

| Name              | Type                                                 | Description                                                                                                                                                                                     |
| ----------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| titleRequired     | string                                               | The dialog's title.                                                                                                                                                                             |
| message           | string                                               | An optional message that appears above the text input.                                                                                                                                          |
| callbackOrButtons | function***[AlertButton](/docs/alert#alertbutton)\[] | If passed a function, it will be called with the prompt's value `(text: string) => void`, when the user taps 'OK'.***If passed an array, buttons will be configured based on the array content. |
| type              | [AlertType](/docs/alert#alerttype-ios)               | This configures the text input.                                                                                                                                                                 |
| defaultValue      | string                                               | The default text in text input.                                                                                                                                                                 |
| keyboardType      | string                                               | The keyboard type of first text field (if exists). One of TextInput [keyboardTypes](/docs/textinput#keyboardtype).                                                                              |
| options           | [AlertOptions](/docs/alert#alertoptions)             | An optional Alert configuration.                                                                                                                                                                |

***

## Type Definitions[​](#type-definitions "Direct link to Type Definitions")

### AlertButtonStyleiOS[​](#alertbuttonstyle-ios "Direct link to alertbuttonstyle-ios")

An iOS Alert button style.

| Type |
| ---- |
| enum |

**Constants:**

| Value           | Description               |
| --------------- | ------------------------- |
| `'default'`     | Default button style.     |
| `'cancel'`      | Cancel button style.      |
| `'destructive'` | Destructive button style. |

***

### AlertTypeiOS[​](#alerttype-ios "Direct link to alerttype-ios")

An iOS Alert type.

| Type |
| ---- |
| enum |

**Constants:**

| Value              | Description                  |
| ------------------ | ---------------------------- |
| `'default'`        | Default alert with no inputs |
| `'plain-text'`     | Plain text input alert       |
| `'secure-text'`    | Secure text input alert      |
| `'login-password'` | Login and password alert     |

***

### AlertButton[​](#alertbutton "Direct link to AlertButton")

An object describing the configuration of a button in the alert.

| Type             |
| ---------------- |
| array of objects |

**Objects properties:**

| Name           | Type                                                 | Description                                                                    |
| -------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------ |
| text           | string                                               | Button label.                                                                  |
| onPress        | function                                             | Callback function when button is pressed.                                      |
| styleiOS       | [AlertButtonStyle](/docs/alert#alertbuttonstyle-ios) | Button style, on Android this property will be ignored.                        |
| isPreferrediOS | boolean                                              | Whether button should be emphasized, on Android this property will be ignored. |

***

### AlertOptions[​](#alertoptions "Direct link to AlertOptions")

| Type   |
| ------ |
| object |

**Properties:**

| Name                  | Type     | Description                                                                                                               |
| --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
| cancelableAndroid     | boolean  | Defines if alert can be dismissed by tapping outside of the alert box.                                                    |
| userInterfaceStyleiOS | string   | The interface style used for the alert, can be set to `light` or `dark`, otherwise the default system style will be used. |
| onDismissAndroid      | function | Callback function fired when alert has been dismissed.                                                                    |

* [Example](#example)

* [iOS](#ios)

* [Android](#android)
  * [Example](#example-android)

    [Android](#example-android)

* [Methods](#methods)

  * [`alert()`](#alert)
  * [`prompt()`](#prompt-ios)

    [iOS](#prompt-ios)

* [Type Definitions](#type-definitions)

  * [AlertButtonStyle](#alertbuttonstyle-ios)

    [iOS](#alertbuttonstyle-ios)
  * [AlertType](#alerttype-ios)

    [iOS](#alerttype-ios)
  * [AlertButton](#alertbutton)
  * [AlertOptions](#alertoptions)

----
url: https://reactnative.dev/docs/next/getting-started-without-a-framework
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/getting-started-without-a-framework)** (0.87).

Version: Next

To do so, you'll first need to [set up your environment](/docs/next/set-up-your-environment). Once you're set up, continue with the steps below to create an application and start developing.

### Step 1: Creating a new application[​](#step-1-creating-a-new-application "Direct link to Step 1: Creating a new application")

warning

If you previously installed a global `react-native-cli` package, please remove it as it may cause unexpected issues:

```
npm uninstall -g react-native-cli @react-native-community/cli
```

You can use [React Native Community CLI](https://github.com/react-native-community/cli) to generate a new project. Let's create a new React Native project called "AwesomeProject":

```
npx @react-native-community/cli@latest init AwesomeProject
```

This is not necessary if you are integrating React Native into an existing application, or if you've installed [Expo](https://docs.expo.dev/bare/installing-expo-modules/) in your project, or if you're adding Android support to an existing React Native project (see [Integration with Existing Apps](/docs/next/integration-with-existing-apps)). You can also use a third-party CLI to set up your React Native app, such as [Ignite CLI](https://github.com/infinitered/ignite).

```
npx @react-native-community/cli@X.XX.X init AwesomeProject --version X.XX.X
```

You can also start a project with a custom React Native template with the `--template` argument, read more [here](https://github.com/react-native-community/cli/blob/main/docs/init.md#initializing-project-with-custom-template).

### Step 2: Start Metro[​](#step-2-start-metro "Direct link to Step 2: Start Metro")

[**Metro**](https://metrobundler.dev/) is the JavaScript build tool for React Native. To start the Metro development server, run the following from your project folder:

* npm
* Yarn

```
npm start
```

```
yarn start
```

note

If you're familiar with web development, Metro is similar to bundlers such as Vite and webpack, but is designed end-to-end for React Native. For instance, Metro uses [Babel](https://babel.dev/) to transform syntax such as JSX into executable JavaScript.

### Step 3: Start your application[​](#step-3-start-your-application "Direct link to Step 3: Start your application")

Let Metro Bundler run in its own terminal. Open a new terminal inside your React Native project folder. Run the following:

* npm
* Yarn

```
npm run android
```

```
yarn android
```

If everything is set up correctly, you should see your new app running in your Android emulator shortly.

This is one way to run your app - you can also run it directly from within Android Studio.

tip

If you can't get this to work, see the [Troubleshooting](/docs/next/troubleshooting) page.

* If you want to add this new React Native code to an existing application, check out the [Integration guide](/docs/next/integration-with-existing-apps).
* If you're curious to learn more about React Native, check out the [Introduction to React Native](/docs/next/getting-started).

----
url: https://reactnative.dev/docs/next/intro-react-native-components
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/intro-react-native-components)** (0.87).

Version: Next

React Native also lets you build your own Native Components for [Android](/docs/next/legacy/native-components-android) and [iOS](/docs/next/legacy/native-components-ios) to suit your app’s unique needs. We also have a thriving ecosystem of these **community-contributed components.** Check out [Native Directory](https://reactnative.directory) to find what the community has been creating.

## Core Components[​](#core-components "Direct link to Core Components")

React Native has many Core Components for everything from controls to activity indicators. You can find them all [documented in the API section](/docs/next/components-and-apis). You will mostly work with the following Core Components:

| React Native UI Component | Android View   | iOS View         | Web Analog              | Description                                                                                           |
| ------------------------- | -------------- | ---------------- | ----------------------- | ----------------------------------------------------------------------------------------------------- |
| `<View>`                  | `<ViewGroup>`  | `<UIView>`       | A non-scrolling `<div>` | A container that supports layout with flexbox, style, some touch handling, and accessibility controls |
| `<Text>`                  | `<TextView>`   | `<UITextView>`   | `<p>`                   | Displays, styles, and nests strings of text and even handles touch events                             |
| `<Image>`                 | `<ImageView>`  | `<UIImageView>`  | `<img>`                 | Displays different types of images                                                                    |
| `<ScrollView>`            | `<ScrollView>` | `<UIScrollView>` | `<div>`                 | A generic scrolling container that can contain multiple components and views                          |
| `<TextInput>`             | `<EditText>`   | `<UITextField>`  | `<input type="text">`   | Allows the user to enter text                                                                         |

In the next section, you will start combining these Core Components to learn about how React works. Have a play with them here now!

***

Because React Native uses the same API structure as React components, you’ll need to understand React component APIs to get started. The [next section](/docs/next/intro-react) makes for a quick introduction or refresher on the topic. However, if you’re already familiar with React, feel free to [skip ahead](/docs/next/handling-text-input).

* [Views and mobile development](#views-and-mobile-development)
* [Native Components](#native-components)
* [Core Components](#core-components)

----
url: https://reactnative.dev/docs/next/navigation
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/navigation)** (0.87).

Version: Next

Mobile apps are rarely made up of a single screen. Managing the presentation of, and transition between, multiple screens is typically handled by what is known as a navigator.

This guide covers the various navigation components available in React Native. If you are getting started with navigation, you will probably want to use [React Navigation](/docs/next/navigation#react-navigation). React Navigation provides a straightforward navigation solution, with the ability to present common stack navigation and tabbed navigation patterns on both Android and iOS.

If you're integrating React Native into an app that already manages navigation natively, or looking for an alternative to React Navigation, the following library provides native navigation on both platforms: [react-native-navigation](https://github.com/wix/react-native-navigation).

## React Navigation[​](#react-navigation "Direct link to React Navigation")

The community solution to navigation is a standalone library that allows developers to set up the screens of an app with a few lines of code.

### Starter template[​](#starter-template "Direct link to Starter template")

If you're starting a new project, you can use the React Navigation template to quickly set up a new project with [Expo](https://expo.dev/):

```
npx create-expo-app@latest --template react-navigation/template
```

See the project's `README.md` for more information on how to get started.

### Installation and setup[​](#installation-and-setup "Direct link to Installation and setup")

First, you need to install them in your project:

```
npm install @react-navigation/native @react-navigation/native-stack
```

Next, install the required peer dependencies. You need to run different commands depending on whether your project is an Expo managed project or a bare React Native project.

* If you have an Expo managed project, install the dependencies with `expo`:

  ```
  npx expo install react-native-screens react-native-safe-area-context
  ```

* If you have a bare React Native project, install the dependencies with `npm`:

  ```
  npm install react-native-screens react-native-safe-area-context
  ```

  For iOS with bare React Native project, make sure you have [CocoaPods](https://cocoapods.org/) installed. Then install the pods to complete the installation:

  ```
  cd ios

  pod install

  cd ..
  ```

Once you've installed and configured the dependencies, you can move on to setting up your project to use React Navigation.

When using React Navigation, you configure [navigators](https://reactnavigation.org/docs/glossary-of-terms#navigator) in your app. Navigators handle the transition between screens in your app and provide UI such as header, tab bar etc.

Now you are ready to build and run your app on the device/simulator.

### Usage[​](#usage "Direct link to Usage")

Now you can create an app with a home screen and a profile screen:

App.tsx

```
import {createStaticNavigation} from '@react-navigation/native';

import {createNativeStackNavigator} from '@react-navigation/native-stack';



const RootStack = createNativeStackNavigator({

  screens: {

    Home: {

      screen: HomeScreen,

      options: {title: 'Welcome'},

    },

    Profile: {

      screen: ProfileScreen,

    },

  },

});



const Navigation = createStaticNavigation(RootStack);



export default function App() {

  return <Navigation />;

}
```

In this example, `RootStack` is a navigator with 2 screens (`Home` and `Profile`), defined in the `screens` property in `createNativeStackNavigator`. Similarly, you can define as many screens as you like.

You can specify options such as the screen title for each screen in the `options` property of each screen. Each screen definition also needs a `screen` property that is a React component or another navigator.

Inside each screen component, you can use the `useNavigation` hook to get the `navigation` object, which has various methods to link to other screens. For example, you can use `navigation.navigate` to go to the `Profile` screen:

HomeScreen.tsx

```
import {useNavigation} from '@react-navigation/native';



export default function HomeScreen() {

  const navigation = useNavigation();



  return (

    <Button

      title="Go to Jane's profile"

      onPress={() =>

        navigation.navigate('Profile', {name: 'Jane'})

      }

    />

  );

}
```

ProfileScreen.tsx

```
export default function ProfileScreen({route}) {

  return <Text>This is {route.params.name}'s profile</Text>;

}
```

----
url: https://reactnative.dev/docs/the-new-architecture/advanced-topics-components
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This document contains a set of advanced topics to implement more complex functionalities of Native Components. It is recommended to first read the [Codegen](/docs/the-new-architecture/what-is-codegen) section and the guides on [Native Components](/docs/fabric-native-components-introduction).

This guide will cover the following topics:

* [Direct Manipulation](/docs/the-new-architecture/direct-manipulation-new-architecture)
* [Measuring the Layout](/docs/the-new-architecture/layout-measurements)
* [Invoking native functions on your native component](/docs/next/the-new-architecture/fabric-component-native-commands)

----
url: https://reactnative.dev/docs/strict-typescript-api
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

```
  {

    "extends": "@react-native/typescript-config",

    "compilerOptions": {

      ...

+     "customConditions": ["react-native", "react-native-legacy-deep-imports"]

    }

  }
```

Issues / Feedback?

The 0.87 rollout of the Strict API by default is an ecosystem-wide change, and one we need to make in order to have stable API guarantees for React Native in future.

Design choices about which APIs are exported at root, and intentional updates to type names/shapes have been worked on with the community and partners since the original 0.80 preview.

We believe we've ironed out all rough edges, but there may still be edge cases. If you're choosing to opt out of the Strict API in 0.87 or later, we'd love to know why: [**discussion thread**](https://github.com/react-native-community/discussions-and-proposals/discussions/1015).

***

## Migration guide[​](#migration-guide "Direct link to Migration guide")

tip

Use the [**/migrate-to-strict-api**](https://www.skills.sh/react-native-community/skills/migrate-to-strict-api) skill to migrate your codebase via an agent.

```
npx skills add react-native-community/skills --skill migrate-to-strict-api
```

```
{

  "compilerOptions": {

    "paths": {

      "some-library/jest/mock": ["./untyped-module.d.ts"]

    }

  }

}
```

untyped-module.d.ts

```
declare const anyExport: unknown;

export default anyExport;
```

```
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';

import type {

  Int32,

  WithDefault,

} from 'react-native/Libraries/Types/CodegenTypes';



interface NativeProps extends ViewProps {

  enabled?: WithDefault<boolean, true>;

  size?: Int32;

}



export default codegenNativeComponent<NativeProps>(

  'RNCustomComponent',

);
```

```
import {CodegenTypes, codegenNativeComponent} from 'react-native';



interface NativeProps extends ViewProps {

  enabled?: CodegenTypes.WithDefault<boolean, true>;

  size?: CodegenTypes.Int32;

}



export default codegenNativeComponent<NativeProps>(

  'RNCustomComponent',

);
```

### Refs now use `*Instance` typesSince 0.87[​](#refs-now-use-instance-types-since-087 "Direct link to refs-now-use-instance-types-since-087")

Each built-in component now has a dedicated `*Instance` type for use with refs — for example, `ViewInstance`, `TextInputInstance`, `ScrollViewInstance`. These are the **recommended way to type refs** under the Strict TypeScript API.

Previously, `useRef<View>` worked because `View` and other components were typed as a class. Under the Strict API, built-in components are typed as functions, so `View` refers to the function itself — **component type names no longer work as ref types**.

* Before
* After

```
import {useRef} from 'react';

import {View, TextInput} from 'react-native';



function MyComponent() {

  const viewRef = useRef<View>(null);

  const inputRef = useRef<TextInput>(null);



  return (

    <>

      <View ref={viewRef} />

      <TextInput ref={inputRef} />

    </>

  );

}
```

```
import {useRef} from 'react';

import type {

  TextInput,

  TextInputInstance,

  View,

  ViewInstance,

} from 'react-native';



function MyComponent() {

  const viewRef = useRef<ViewInstance>(null);

  const inputRef = useRef<TextInputInstance>(null);



  return (

    <>

      <View ref={viewRef} />

      <TextInput ref={inputRef} />

    </>

  );

}
```

`*Instance` types also work transparently with `Animated` variants — no separate type is needed:

```
const viewRef = useRef<ViewInstance>(null);



<View ref={viewRef} />

<Animated.View ref={viewRef} />
```

This also replaces the removed `Animated.LegacyRef` type. Code using `ref={ref as React.Ref<Animated.LegacyRef<View>>}` can be simplified to `ref={ref}` with a `ViewInstance`-typed ref.

**Available instance types**

| Component                 | Instance type                     |
| ------------------------- | --------------------------------- |
| `ActivityIndicator`       | `ActivityIndicatorInstance`       |
| `Button`                  | `ButtonInstance`                  |
| `DrawerLayoutAndroid`     | `DrawerLayoutAndroidInstance`     |
| `FlatList`                | `FlatListInstance`                |
| `Image`                   | `ImageInstance`                   |
| `ImageBackground`         | `ImageBackgroundInstance`         |
| `KeyboardAvoidingView`    | `KeyboardAvoidingViewInstance`    |
| `Modal`                   | `ModalInstance`                   |
| `Pressable`               | `PressableInstance`               |
| `ProgressBarAndroid`      | `ProgressBarAndroidInstance`      |
| `RefreshControl`          | `RefreshControlInstance`          |
| `SafeAreaView`            | `SafeAreaViewInstance`            |
| `ScrollView`              | `ScrollViewInstance`              |
| `SectionList`             | `SectionListInstance`             |
| `StatusBar`               | `StatusBarInstance`               |
| `Switch`                  | `SwitchInstance`                  |
| `Text`                    | `TextInstance`                    |
| `TextInput`               | `TextInputInstance`               |
| `TouchableHighlight`      | `TouchableHighlightInstance`      |
| `TouchableNativeFeedback` | `TouchableNativeFeedbackInstance` |
| `TouchableOpacity`        | `TouchableOpacityInstance`        |
| `View`                    | `ViewInstance`                    |
| `VirtualizedList`         | `VirtualizedListInstance`         |
| `VirtualizedSectionList`  | `VirtualizedSectionListInstance`  |

Components without ref support (`InputAccessoryView`, `TouchableWithoutFeedback`, `experimental_LayoutConformance`) do not have instance types.

**Migration**

| Before                                                  | After                        |
| ------------------------------------------------------- | ---------------------------- |
| `useRef<View>(null)`                                    | `useRef<ViewInstance>(null)` |
| `useRef<React.ComponentRef<typeof View>>(null)`         | `useRef<ViewInstance>(null)` |
| `useRef<HostInstance>(null)` (for a specific component) | `useRef<ViewInstance>(null)` |
| `Ref<Animated.LegacyRef<View>>`                         | `Ref<ViewInstance>`          |

note

`React.ComponentRef<typeof View>` remains valid and produces the same type as `ViewInstance`. The `*Instance` types are convenient aliases — both approaches work.

### Removal of `*Static` types[​](#removal-of-static-types "Direct link to removal-of-static-types")

#### Migration[​](#migration-1 "Direct link to Migration")

* Before
* After

```
import {Linking, LinkingStatic} from 'react-native';



function foo(linking: LinkingStatic) {}

foo(Linking);
```

```
import {Linking} from 'react-native';



function foo(linking: Linking) {}

foo(Linking);
```

```
// @ts-expect-error - React Native internal, untyped under the Strict API

import NativeAppState from 'react-native/Libraries/AppState/NativeAppState';
```

Separately, if your Jest setup imports `react-native/Libraries/Core/InitializeCore`, update it — see [`InitializeCore` is now `react-native/setup-env`](#initializecore-is-now-react-nativesetup-env-since-087).

## Other breaking changes[​](#other-breaking-changes "Direct link to Other breaking changes")

### `InitializeCore` is now `react-native/setup-env`Since 0.87[​](#initializecore-is-now-react-nativesetup-env-since-087 "Direct link to initializecore-is-now-react-nativesetup-env-since-087")

Unlike other deep imports, this module is a side-effect entry point with no root `react-native` equivalent. `InitializeCore` is deprecated since 0.87.

```
- import 'react-native/Libraries/Core/InitializeCore';

+ import 'react-native/setup-env';
```

For the full list of aliases, see [`DeprecatedPropertiesAlias.d.ts`](https://github.com/react/react-native/blob/0.87-stable/packages/react-native/types/public/DeprecatedPropertiesAlias.d.ts).

****

    [Since 0.87](#refs-now-use-instance-types-since-087)
  * [Removal of `*Static` types](#removal-of-static-types)
  * [Updating test mocks](#updating-test-mocks)

* [Other breaking changes](#other-breaking-changes)

  * [`InitializeCore` is now `react-native/setup-env`](#initializecore-is-now-react-nativesetup-env-since-087)

    [Since 0.87](#initializecore-is-now-react-nativesetup-env-since-087)
  * [Changes to Animated types](#changes-to-animated-types)
  * [Unified types for optional props](#unified-types-for-optional-props)
  * [Removal of some deprecated types](#removal-of-some-deprecated-types)
  * [Removal of leftover component props](#removal-of-leftover-component-props)
  * [Removal of internal-only helper types](#removal-of-internal-only-helper-types)

* [FAQs](#faqs)

----
url: https://reactnative.dev/docs/next/global-Headers
----

[Skip to main content](#__docusaurus_skipToContent_fallback)

This is unreleased documentation for React Native **Next** version.

For up-to-date documentation, see the **[latest version](/docs/global-Headers)** (0.87).

Version: Next

warning

🚧 This page is work in progress, so please refer to the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Headers) for more information.

The global `Headers` class, as defined in Web specifications.