diff --git a/docs/_fabric-native-components.jsx b/docs/_fabric-native-components.jsx index fc6a3171a4f..69bc6f31268 100644 --- a/docs/_fabric-native-components.jsx +++ b/docs/_fabric-native-components.jsx @@ -1,4 +1,3 @@ -import React from 'react'; import IOSContent from './fabric-native-components-ios.md'; import AndroidContent from './fabric-native-components-android.md'; diff --git a/docs/_integration-with-existing-apps-ios.md b/docs/_integration-with-existing-apps-ios.md index 4b95571538b..1670717d84f 100644 --- a/docs/_integration-with-existing-apps-ios.md +++ b/docs/_integration-with-existing-apps-ios.md @@ -159,7 +159,7 @@ AppRegistry.registerComponent('HelloWorld', () => App); Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX]() expressions. It contains the root React Native component that we will integrate into our iOS application (link): ```tsx -import React from 'react'; +import {type JSX} from 'react'; import { SafeAreaView, ScrollView, @@ -177,7 +177,7 @@ import { ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; -function App(): React.JSX.Element { +function App(): JSX.Element { const isDarkMode = useColorScheme() === 'dark'; const backgroundStyle = { diff --git a/docs/_integration-with-existing-apps-kotlin.md b/docs/_integration-with-existing-apps-kotlin.md index 23414c63a3b..6ce02c4133b 100644 --- a/docs/_integration-with-existing-apps-kotlin.md +++ b/docs/_integration-with-existing-apps-kotlin.md @@ -192,7 +192,7 @@ AppRegistry.registerComponent('HelloWorld', () => App); Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX]() expressions. It contains the root React Native component that we will integrate into our Android application (link): ```tsx -import React from 'react'; +import {type JSX} from 'react'; import { SafeAreaView, ScrollView, @@ -202,7 +202,6 @@ import { useColorScheme, View, } from 'react-native'; - import { Colors, DebugInstructions, @@ -210,7 +209,7 @@ import { ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; -function App(): React.JSX.Element { +function App(): JSX.Element { const isDarkMode = useColorScheme() === 'dark'; const backgroundStyle = { diff --git a/docs/_turbo-native-modules-components.jsx b/docs/_turbo-native-modules-components.jsx index 1bb5a1b5edb..9b17f011728 100644 --- a/docs/_turbo-native-modules-components.jsx +++ b/docs/_turbo-native-modules-components.jsx @@ -1,4 +1,3 @@ -import React from 'react'; import IOSContent from './turbo-native-modules-ios.md'; import AndroidContent from './turbo-native-modules-android.md'; diff --git a/docs/accessibilityinfo.md b/docs/accessibilityinfo.md index af69fbcfec3..4cebdadb1b3 100644 --- a/docs/accessibilityinfo.md +++ b/docs/accessibilityinfo.md @@ -8,7 +8,7 @@ Sometimes it's useful to know whether or not the device has a screen reader that ## Example ```SnackPlayer name=AccessibilityInfo%20Example&supportedPlatforms=android,ios -import React, {useState, useEffect} from 'react'; +import {useState, useEffect} from 'react'; import {AccessibilityInfo, Text, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/actionsheetios.md b/docs/actionsheetios.md index 30d1d6afea5..d4294c35d18 100644 --- a/docs/actionsheetios.md +++ b/docs/actionsheetios.md @@ -8,7 +8,7 @@ Displays native to iOS [Action Sheet](https://developer.apple.com/design/human-i ## Example ```SnackPlayer name=ActionSheetIOS%20Example&supportedPlatforms=ios -import React, {useState} from 'react'; +import {useState} from 'react'; import {ActionSheetIOS, Button, StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/activityindicator.md b/docs/activityindicator.md index c9d03b73021..9b1445cbf5e 100644 --- a/docs/activityindicator.md +++ b/docs/activityindicator.md @@ -8,7 +8,6 @@ Displays a circular loading indicator. ## Example ```SnackPlayer name=ActivityIndicator%20Example -import React from 'react'; import {ActivityIndicator, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/alert.md b/docs/alert.md index c80b62fb7a6..78b1c412e66 100644 --- a/docs/alert.md +++ b/docs/alert.md @@ -12,7 +12,6 @@ This is an API that works both on Android and iOS and can show static alerts. Al ## Example ```SnackPlayer name=Alert%20Example&supportedPlatforms=ios,android -import React from 'react'; import {StyleSheet, Button, Alert} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -81,7 +80,6 @@ The cancel event can be handled by providing an `onDismiss` callback property in ### Example
Android
```SnackPlayer name=Alert%20Android%20Dissmissable%20Example&supportedPlatforms=android -import React from 'react'; import {StyleSheet, Button, Alert} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/animated.md b/docs/animated.md index d4ba867028b..fce79ffaf57 100644 --- a/docs/animated.md +++ b/docs/animated.md @@ -16,7 +16,6 @@ Don't modify the animated value directly. You can use the [`useRef` Hook](https: The following example contains a `View` which will fade in and fade out based on the animated value `fadeAnim` ```SnackPlayer name=Animated%20Example -import React from 'react'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; import { Animated, diff --git a/docs/animatedvaluexy.md b/docs/animatedvaluexy.md index 6cb44808ccf..e5ddd564489 100644 --- a/docs/animatedvaluexy.md +++ b/docs/animatedvaluexy.md @@ -8,7 +8,7 @@ title: Animated.ValueXY ## Example ```SnackPlayer name=Animated.ValueXY%20Example -import React, {useRef} from 'react'; +import {useRef} from 'react'; import {Animated, PanResponder, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/animations.md b/docs/animations.md index ccdaa5a32bb..321c8a0b2e1 100644 --- a/docs/animations.md +++ b/docs/animations.md @@ -21,7 +21,7 @@ For example, a container view that fades in when it is mounted may look like thi ```SnackPlayer ext=js -import React, {useEffect, useRef} from 'react'; +import {useEffect, useRef} from 'react'; import {Animated, Text, View} from 'react-native'; const FadeInView = props => { @@ -74,12 +74,12 @@ export default () => { ```SnackPlayer ext=tsx -import React, {useEffect, useRef, type PropsWithChildren} from 'react'; +import {useEffect, useRef, type PropsWithChildren, type FC} from 'react'; import {Animated, Text, View, type ViewStyle} from 'react-native'; type FadeInViewProps = PropsWithChildren<{style: ViewStyle}>; -const FadeInView: React.FC = props => { +const FadeInView: FC = props => { const fadeAnim = useRef(new Animated.Value(0)).current; // Initial value for opacity: 0 useEffect(() => { @@ -309,7 +309,6 @@ The following example implements a horizontal scrolling carousel where the scrol #### ScrollView with Animated Event Example ```SnackPlayer name=Animated&supportedPlatforms=ios,android -import React from 'react'; import { ScrollView, Text, @@ -452,7 +451,7 @@ onPanResponderMove={Animated.event( #### PanResponder with Animated Event Example ```SnackPlayer name=Animated -import React, {useRef} from 'react'; +import {useRef} from 'react'; import {Animated, View, StyleSheet, PanResponder, Text} from 'react-native'; const App = () => { @@ -593,7 +592,7 @@ UIManager.setLayoutAnimationEnabledExperimental(true); ``` ```SnackPlayer name=LayoutAnimations -import React, {useState} from 'react'; +import {useState} from 'react'; import { NativeModules, LayoutAnimation, diff --git a/docs/appstate.md b/docs/appstate.md index b776907d3e1..fb4188f6cf1 100644 --- a/docs/appstate.md +++ b/docs/appstate.md @@ -28,7 +28,7 @@ If you are using the legacy architecture, `currentState` will be `null` at launc ::: ```SnackPlayer name=AppState%20Example -import React, {useRef, useState, useEffect} from 'react'; +import {useRef, useState, useEffect} from 'react'; import {AppState, StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/backhandler.md b/docs/backhandler.md index c3c7c937541..1d096c71a13 100644 --- a/docs/backhandler.md +++ b/docs/backhandler.md @@ -52,7 +52,7 @@ subscription.remove(); The following example implements a scenario where you confirm if the user wants to exit the app: ```SnackPlayer name=BackHandler&supportedPlatforms=android -import React, {useEffect} from 'react'; +import {useEffect} from 'react'; import {Text, StyleSheet, BackHandler, Alert} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/button.md b/docs/button.md index 9fc529fc863..23501057f52 100644 --- a/docs/button.md +++ b/docs/button.md @@ -19,7 +19,6 @@ If this button doesn't look right for your app, you can build your own button us ## Example ```SnackPlayer name=Button%20Example&ext=js -import React from 'react'; import {StyleSheet, Button, View, Text, Alert, Platform} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/communication-android.md b/docs/communication-android.md index f78dc84cf65..35aab358818 100644 --- a/docs/communication-android.md +++ b/docs/communication-android.md @@ -67,7 +67,6 @@ class MainActivity : ReactActivity() { ```tsx -import React from 'react'; import {View, Image} from 'react-native'; export default class ImageBrowserApp extends React.Component { diff --git a/docs/communication-ios.md b/docs/communication-ios.md index f82cae7e620..89a64ff9b4c 100644 --- a/docs/communication-ios.md +++ b/docs/communication-ios.md @@ -33,7 +33,6 @@ RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge ``` ```tsx -import React from 'react'; import {View, Image} from 'react-native'; export default class ImageBrowserApp extends React.Component { diff --git a/docs/dimensions.md b/docs/dimensions.md index 9ebb8561739..c9c6b70c613 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -27,7 +27,7 @@ If you are targeting foldable devices or devices which can change the screen siz ## Example ```SnackPlayer name=Dimensions%20Example -import React, {useState, useEffect} from 'react'; +import {useState, useEffect} from 'react'; import {StyleSheet, Text, Dimensions} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/document-nodes.md b/docs/document-nodes.md index 978ef87a1f8..5f8a6e073a6 100644 --- a/docs/document-nodes.md +++ b/docs/document-nodes.md @@ -6,7 +6,7 @@ title: Document nodes 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). ```SnackPlayer ext=js&name=Document%20instance%20example -import * as React from 'react'; +import {useEffect, useRef} from 'react'; import {Text, TextInput, View} from 'react-native'; function MyComponent(props) { @@ -19,9 +19,9 @@ function MyComponent(props) { } export default function AccessingDocument() { - const ref = React.useRef(null); + const ref = useRef(null); - React.useEffect(() => { + useEffect(() => { // Get the main text input in the screen and focus it after initial load. const element = ref.current; const doc = element.ownerDocument; diff --git a/docs/drawerlayoutandroid.md b/docs/drawerlayoutandroid.md index 3714318df5c..079f50b60a6 100644 --- a/docs/drawerlayoutandroid.md +++ b/docs/drawerlayoutandroid.md @@ -13,7 +13,7 @@ React component that wraps the platform `DrawerLayout` (Android only). The Drawe ```SnackPlayer name=DrawerLayoutAndroid%20Component%20Example&supportedPlatforms=android&ext=js -import React, {useRef, useState} from 'react'; +import {useRef, useState} from 'react'; import {Button, DrawerLayoutAndroid, Text, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -86,7 +86,7 @@ export default App; ```SnackPlayer name=DrawerLayoutAndroid%20Component%20Example&supportedPlatforms=android&ext=tsx -import React, {useRef, useState} from 'react'; +import {useRef, useState} from 'react'; import { Button, DrawerLayoutAndroid, diff --git a/docs/easing.md b/docs/easing.md index bb31dd0e4fa..f20e2644f4d 100644 --- a/docs/easing.md +++ b/docs/easing.md @@ -49,7 +49,7 @@ The following helpers are used to modify other easing functions. ```SnackPlayer name=Easing%20Demo&ext=js -import React, {useRef} from 'react'; +import {useRef} from 'react'; import { Animated, Easing, @@ -209,7 +209,7 @@ export default App; ```SnackPlayer name=Easing%20Demo&ext=tsx -import React, {useRef} from 'react'; +import {useRef} from 'react'; import { Animated, Easing, diff --git a/docs/element-nodes.md b/docs/element-nodes.md index 654c870b37f..53c05835199 100644 --- a/docs/element-nodes.md +++ b/docs/element-nodes.md @@ -8,14 +8,14 @@ Element nodes represent native components in the native view tree (similar to [E They are provided by all native components, and by many built-in components, via refs: ```SnackPlayer ext=js&name=Element%20instances%20example -import * as React from 'react'; -import { View, SafeAreaView, StyleSheet, Text } from 'react-native'; +import {useEffect, useRef, useState} from 'react'; +import {View, SafeAreaView, StyleSheet, Text} from 'react-native'; const ViewWithRefs = () => { - const ref = React.useRef(null); - const [viewInfo, setViewInfo] = React.useState(''); + const ref = useRef(null); + const [viewInfo, setViewInfo] = useState(''); - React.useEffect(() => { + useEffect(() => { // `element` is an object implementing the interface described here. const element = ref.current; const rect = JSON.stringify(element.getBoundingClientRect()); diff --git a/docs/fabric-native-components.md b/docs/fabric-native-components.md index 2a509a7174e..6efdd572e92 100644 --- a/docs/fabric-native-components.md +++ b/docs/fabric-native-components.md @@ -172,7 +172,6 @@ This guide shows you how to create a Native Component that only works with the N Finally, you can use the new component in your app. Update your generated `App.tsx` to: ```javascript title="Demo/App.tsx" -import React from 'react'; import {Alert, StyleSheet, View} from 'react-native'; import WebView from './specs/WebViewNativeComponent'; diff --git a/docs/flatlist.md b/docs/flatlist.md index 56505e27ca8..7bc9884fa34 100644 --- a/docs/flatlist.md +++ b/docs/flatlist.md @@ -26,7 +26,6 @@ If you need section support, use [``](sectionlist.md). ```SnackPlayer name=Simple%20FlatList%20Example&ext=js -import React from 'react'; import {View, FlatList, StyleSheet, Text, StatusBar} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -86,7 +85,6 @@ export default App; ```SnackPlayer name=Simple%20FlatList%20Example&ext=tsx -import React from 'react'; import {View, FlatList, StyleSheet, Text, StatusBar} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -158,7 +156,7 @@ More complex, selectable example below. ```SnackPlayer name=flatlist-selectable&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import { FlatList, StatusBar, @@ -242,7 +240,7 @@ export default App; ```SnackPlayer name=flatlist-selectable&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import { FlatList, StatusBar, diff --git a/docs/flexbox.md b/docs/flexbox.md index 039a7bdf60b..c98c516714d 100644 --- a/docs/flexbox.md +++ b/docs/flexbox.md @@ -21,7 +21,6 @@ The defaults are different, with `flexDirection` defaulting to `column` instead 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. ```SnackPlayer name=Flex%20Example -import React from 'react'; import {StyleSheet, View} from 'react-native'; const Flex = () => { @@ -69,7 +68,7 @@ You can learn more [here](https://www.yogalayout.dev/docs/styling/flex-direction ```SnackPlayer name=Flex%20Direction&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'; const FlexDirectionBasics = () => { @@ -168,7 +167,7 @@ export default FlexDirectionBasics; ```SnackPlayer name=Flex%20Direction&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'; import type {PropsWithChildren} from 'react'; @@ -286,7 +285,7 @@ Layout [`direction`](layout-props#direction) specifies the direction in which ch ```SnackPlayer name=Flex%20Direction&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; const DirectionLayout = () => { @@ -385,7 +384,7 @@ export default DirectionLayout; ```SnackPlayer name=Flex%20Direction&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import type {PropsWithChildren} from 'react'; @@ -513,7 +512,7 @@ You can learn more [here](https://www.yogalayout.dev/docs/styling/justify-conten ```SnackPlayer name=Justify%20Content&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; const JustifyContentBasics = () => { @@ -619,7 +618,7 @@ export default JustifyContentBasics; ```SnackPlayer name=Justify%20Content&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import type {PropsWithChildren} from 'react'; @@ -756,7 +755,7 @@ You can learn more [here](https://www.yogalayout.dev/docs/styling/align-items-se ```SnackPlayer name=Align%20Items&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; const AlignItemsLayout = () => { @@ -865,7 +864,7 @@ export default AlignItemsLayout; ```SnackPlayer name=Align%20Items&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import type {PropsWithChildren} from 'react'; @@ -989,7 +988,7 @@ export default AlignItemsLayout; ```SnackPlayer name=Align%20Self&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; const AlignSelfLayout = () => { @@ -1099,7 +1098,7 @@ export default AlignSelfLayout; ```SnackPlayer name=Align%20Self&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import type {PropsWithChildren} from 'react'; import type {FlexAlignType} from 'react-native'; @@ -1241,7 +1240,7 @@ You can learn more [here](https://www.yogalayout.dev/docs/styling/align-content) ```SnackPlayer name=Align%20Content&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; const AlignContentLayout = () => { @@ -1353,7 +1352,7 @@ export default AlignContentLayout; ```SnackPlayer name=Align%20Content&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import type {PropsWithChildren} from 'react'; @@ -1482,7 +1481,7 @@ When wrapping lines, `alignContent` can be used to specify how the lines are pla ```SnackPlayer name=Flex%20Wrap&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; const FlexWrapLayout = () => { @@ -1585,7 +1584,7 @@ export default FlexWrapLayout; ```SnackPlayer name=Flex%20Wrap&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import type {PropsWithChildren} from 'react'; @@ -1713,7 +1712,7 @@ You can learn more [here](https://www.yogalayout.dev/docs/styling/flex-basis-gro ```SnackPlayer name=Flex%20Basis%2C%20Grow%2C%20and%20Shrink&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, Text, TextInput, StyleSheet} from 'react-native'; const App = () => { @@ -1887,7 +1886,7 @@ export default App; ```SnackPlayer name=Flex%20Basis%2C%20Grow%2C%20and%20Shrink&ext=tsx -import React, {useState} from 'react'; +import {useState, type Dispatch, type SetStateAction} from 'react'; import {View, Text, TextInput, StyleSheet} from 'react-native'; import type {ViewStyle} from 'react-native'; @@ -1962,7 +1961,7 @@ const App = () => { type BoxInfoProps = ViewStyle & { color: string; - setStyle: React.Dispatch>; + setStyle: Dispatch>; }; const BoxInfo = ({ @@ -2086,7 +2085,7 @@ You can use `flexWrap` and `alignContent` along with `gap` to add consistent spa ```SnackPlayer name=Row%20Gap%20and%20Column%20Gap&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, Text, StyleSheet, TextInput} from 'react-native'; const RowGapAndColumnGap = () => { @@ -2188,7 +2187,7 @@ export default RowGapAndColumnGap; ```SnackPlayer name=Row%20Gap%20and%20Column%20Gap&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, Text, StyleSheet, TextInput} from 'react-native'; import type {PropsWithChildren} from 'react'; @@ -2313,7 +2312,7 @@ Both `width` and `height` can take the following values: ```SnackPlayer name=Width%20and%20Height&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -2439,7 +2438,7 @@ export default WidthHeightBasics; ```SnackPlayer name=Width%20and%20Height&ext=tsx -import React, {useState, PropsWithChildren} from 'react'; +import {useState, PropsWithChildren} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -2589,7 +2588,7 @@ The `position` type of an element defines how it is positioned relative to eithe ```SnackPlayer name=Position&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; const PositionLayout = () => { @@ -2719,7 +2718,7 @@ export default PositionLayout; ```SnackPlayer name=Position&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, TouchableOpacity, Text, StyleSheet} from 'react-native'; import type {PropsWithChildren} from 'react'; diff --git a/docs/handling-text-input.md b/docs/handling-text-input.md index 6db00cae840..c6f249bb31f 100644 --- a/docs/handling-text-input.md +++ b/docs/handling-text-input.md @@ -8,7 +8,7 @@ title: Handling Text Input 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 "🍕 🍕 🍕". ```SnackPlayer name=Handling%20Text%20Input -import React, {useState} from 'react'; +import {useState} from 'react'; import {Text, TextInput, View} from 'react-native'; const PizzaTranslator = () => { diff --git a/docs/handling-touches.md b/docs/handling-touches.md index 612287f6e10..b9604b393c0 100644 --- a/docs/handling-touches.md +++ b/docs/handling-touches.md @@ -25,7 +25,6 @@ This will render a blue label on iOS, and a blue rounded rectangle with light te 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. ```SnackPlayer name=Button%20Basics -import React from 'react'; import {Alert, Button, StyleSheet, View} from 'react-native'; const ButtonBasics = () => { @@ -86,7 +85,6 @@ In some cases, you may want to detect when a user presses and holds a view for a Let's see all of these in action: ```SnackPlayer name=Touchables -import React from 'react'; import { Alert, Platform, diff --git a/docs/height-and-width.md b/docs/height-and-width.md index 485667831cd..b768626716e 100644 --- a/docs/height-and-width.md +++ b/docs/height-and-width.md @@ -10,7 +10,6 @@ A component's height and width determine its size on the screen. The general way to set the dimensions of a component is by adding a fixed `width` and `height` to style. All dimensions in React Native are unitless, and represent density-independent pixels. ```SnackPlayer name=Height%20and%20Width -import React from 'react'; import {View} from 'react-native'; const FixedDimensionsBasics = () => { @@ -59,7 +58,6 @@ A component can only expand to fill available space if its parent has dimensions ::: ```SnackPlayer name=Flex%20Dimensions -import React from 'react'; import {View} from 'react-native'; const FlexDimensionsBasics = () => { @@ -85,7 +83,6 @@ After you can control a component's size, the next step is to [learn how to lay 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. ```SnackPlayer name=Percentage%20Dimensions -import React from 'react'; import {View} from 'react-native'; const PercentageDimensionsBasics = () => { diff --git a/docs/i18nmanager.md b/docs/i18nmanager.md index 80ccd2ccd72..106b03fc111 100644 --- a/docs/i18nmanager.md +++ b/docs/i18nmanager.md @@ -14,7 +14,6 @@ The `I18nManager` module provides utilities for managing Right-to-Left (RTL) lay If you absolutely position elements to align with other flexbox elements, they may not align in RTL languages. Using `isRTL` can be used to adjust alignment or animations. ```SnackPlayer name=I18nManager%20Change%20Absolute%20Positions%20And%20Animations -import React from 'react'; import {I18nManager, Text, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -43,7 +42,7 @@ export default App; ### During Development ```SnackPlayer name=I18nManager%20During%20Development -import React, {useState} from 'react'; +import {useState} from 'react'; import {Alert, I18nManager, StyleSheet, Switch, Text, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/image-style-props.md b/docs/image-style-props.md index efa0dc725e1..cbf19f996f9 100644 --- a/docs/image-style-props.md +++ b/docs/image-style-props.md @@ -8,7 +8,6 @@ title: Image Style Props ### Image Resize Mode ```SnackPlayer name=Image%20Resize%20Modes%20Example -import React from 'react'; import {View, Image, Text, StyleSheet, ScrollView} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -82,7 +81,6 @@ export default DisplayAnImageWithStyle; ### Image Border ```SnackPlayer name=Style%20BorderWidth%20and%20BorderColor%20Example -import React from 'react'; import {Image, StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -118,7 +116,6 @@ export default DisplayAnImageWithStyle; ### Image Border Radius ```SnackPlayer name=Style%20Border%20Radius%20Example -import React from 'react'; import {View, Image, StyleSheet, Text, ScrollView} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -184,7 +181,6 @@ export default DisplayAnImageWithStyle; ### Image Tint ```SnackPlayer name=Style%20tintColor%20Function%20Component -import React from 'react'; import {Image, StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/image.md b/docs/image.md index 5f6a2a5b1ad..3f83be8c19c 100644 --- a/docs/image.md +++ b/docs/image.md @@ -14,7 +14,6 @@ For network and data images, you will need to manually specify the dimensions of ## Examples ```SnackPlayer name=Image%20Example -import React from 'react'; import {Image, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -61,7 +60,6 @@ export default DisplayAnImage; You can also add `style` to an image: ```SnackPlayer name=Styled%20Image%20Example -import React from 'react'; import {Image, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/imagebackground.md b/docs/imagebackground.md index 6670fd3b632..d3d40b2a844 100644 --- a/docs/imagebackground.md +++ b/docs/imagebackground.md @@ -12,7 +12,6 @@ Note that you must specify some width and height style attributes. ## Example ```SnackPlayer name=ImageBackground -import React from 'react'; import {ImageBackground, StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/improvingux.md b/docs/improvingux.md index 462f5f0ce1c..4b8e807c6c4 100644 --- a/docs/improvingux.md +++ b/docs/improvingux.md @@ -21,7 +21,7 @@ Check out [`TextInput` docs](textinput.md) for more configuration options. ```SnackPlayer name=TextInput%20form%20example&ext=js -import React, {useState, useRef} from 'react'; +import {useState, useRef} from 'react'; import { Alert, Text, @@ -115,7 +115,7 @@ export default App; ```SnackPlayer name=TextInput%20form%20example&ext=tsx -import React, {useState, useRef} from 'react'; +import {useState, useRef} from 'react'; import { Alert, Text, @@ -216,7 +216,7 @@ Software keyboard takes almost half of the screen. If you have interactive eleme ```SnackPlayer name=KeyboardAvoidingView%20example&ext=js -import React, {useState, useRef} from 'react'; +import {useState, useRef} from 'react'; import { Alert, Text, @@ -313,7 +313,7 @@ export default App; ```SnackPlayer name=KeyboardAvoidingView%20example&ext=tsx -import React, {useState, useRef} from 'react'; +import {useState, useRef} from 'react'; import { Alert, Text, @@ -414,7 +414,6 @@ export default App; 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](touchablewithoutfeedback.md#hitslop) to increase interactive area without affecting the layout. Here's a demo: ```SnackPlayer name=HitSlop%20example -import React from 'react'; import { Text, StatusBar, @@ -493,7 +492,6 @@ export default App; 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](touchablenativefeedback.md). 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. ```SnackPlayer name=Android%20Ripple%20example&supportedPlatforms=android -import React from 'react'; import { TouchableNativeFeedback, TouchableOpacity, diff --git a/docs/inputaccessoryview.md b/docs/inputaccessoryview.md index a4f56532fa4..30c86719e14 100644 --- a/docs/inputaccessoryview.md +++ b/docs/inputaccessoryview.md @@ -8,7 +8,7 @@ A component which enables customization of the keyboard input accessory view on 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: ```SnackPlayer name=InputAccessoryView&supportedPlatforms=ios -import React, {useState} from 'react'; +import {useState} from 'react'; import { Button, InputAccessoryView, diff --git a/docs/interactionmanager.md b/docs/interactionmanager.md index 8eac16a4b70..75328f17894 100644 --- a/docs/interactionmanager.md +++ b/docs/interactionmanager.md @@ -51,7 +51,7 @@ By default, queued tasks are executed together in a loop in one `setImmediate` b ```SnackPlayer name=InteractionManager%20Function%20Component%20Basic%20Example&supportedPlatforms=ios,android&ext=js -import React, {useEffect} from 'react'; +import {useEffect} from 'react'; import { Alert, Animated, @@ -133,7 +133,7 @@ export default App; ```SnackPlayer name=InteractionManager%20Function%20Component%20Basic%20Example&supportedPlatforms=ios,android&ext=tsx -import React, {useEffect} from 'react'; +import {useEffect} from 'react'; import { Alert, Animated, @@ -224,7 +224,7 @@ export default App; ```SnackPlayer name=InteractionManager%20Function%20Component%20Advanced%20Example&supportedPlatforms=ios,android&ext=js -import React, {useEffect} from 'react'; +import {useEffect} from 'react'; import { Alert, Animated, @@ -300,7 +300,7 @@ export default App; ```SnackPlayer name=InteractionManager%20Function%20Component%20Advanced%20Example&supportedPlatforms=ios,android&ext=tsx -import React, {useEffect} from 'react'; +import {useEffect} from 'react'; import { Alert, Animated, diff --git a/docs/intro-react-native-components.md b/docs/intro-react-native-components.md index eb585964154..2f3a1449d28 100644 --- a/docs/intro-react-native-components.md +++ b/docs/intro-react-native-components.md @@ -43,7 +43,6 @@ React Native has many Core Components for everything from controls to activity i In the next section, you will start combining these Core Components to learn about how React works. Have a play with them here now! ```SnackPlayer name=Hello%20World -import React from 'react'; import {View, Text, Image, ScrollView, TextInput} from 'react-native'; const App = () => { diff --git a/docs/introduction.md b/docs/introduction.md index ba782cd838c..2752b80327b 100644 --- a/docs/introduction.md +++ b/docs/introduction.md @@ -30,7 +30,6 @@ While we do our best to assume no prior knowledge of React, Android, or iOS deve This introduction lets you get started immediately in your browser with interactive examples like this one: ```SnackPlayer name=Hello%20World -import React from 'react'; import {Text, View} from 'react-native'; const YourApp = () => { diff --git a/docs/javascript-environment.md b/docs/javascript-environment.md index ab041dd34cd..d66b5a996de 100644 --- a/docs/javascript-environment.md +++ b/docs/javascript-environment.md @@ -41,7 +41,7 @@ A full list of React Native's enabled transformations can be found in [@react-na - + diff --git a/docs/keyboard.md b/docs/keyboard.md index 8560ce4999d..c4951b2058c 100644 --- a/docs/keyboard.md +++ b/docs/keyboard.md @@ -10,7 +10,7 @@ title: Keyboard 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. ```SnackPlayer name=Keyboard%20Example&supportedPlatforms=ios,android -import React, {useState, useEffect} from 'react'; +import {useState, useEffect} from 'react'; import {Keyboard, Text, TextInput, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/keyboardavoidingview.md b/docs/keyboardavoidingview.md index 55cce32cf54..cc650dd0f57 100644 --- a/docs/keyboardavoidingview.md +++ b/docs/keyboardavoidingview.md @@ -8,7 +8,6 @@ This component will automatically adjust its height, position, or bottom padding ## Example ```SnackPlayer name=KeyboardAvoidingView&supportedPlatforms=android,ios -import React from 'react'; import { View, KeyboardAvoidingView, diff --git a/docs/layout-props.md b/docs/layout-props.md index b3673e0c849..36797b8dc86 100644 --- a/docs/layout-props.md +++ b/docs/layout-props.md @@ -17,7 +17,7 @@ The following example shows how different properties can affect or shape a React ```SnackPlayer name=LayoutProps%20Example&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import {Button, ScrollView, StyleSheet, Text, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -190,7 +190,7 @@ export default App; ```SnackPlayer name=LayoutProps%20Example&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import { Button, ScrollView, diff --git a/docs/layoutanimation.md b/docs/layoutanimation.md index 911a247c8c7..b69454098f6 100644 --- a/docs/layoutanimation.md +++ b/docs/layoutanimation.md @@ -20,7 +20,7 @@ if (Platform.OS === 'android') { ## Example ```SnackPlayer name=LayoutAnimation%20Example&supportedPlatforms=android,ios -import React, {useState} from 'react'; +import {useState} from 'react'; import { LayoutAnimation, Platform, @@ -134,7 +134,7 @@ Helper that creates an object (with `create`, `update`, and `delete` fields) to **Example:** ```SnackPlayer name=LayoutAnimation&supportedPlatforms=android,ios -import React, {useState} from 'react'; +import {useState} from 'react'; import { View, Platform, @@ -263,7 +263,7 @@ Calls `configureNext()` with `Presets.spring`. **Example:** ```SnackPlayer name=LayoutAnimation&supportedPlatforms=android,ios -import React, {useState} from 'react'; +import {useState} from 'react'; import { View, Platform, diff --git a/docs/legacy/direct-manipulation.md b/docs/legacy/direct-manipulation.md index b3e7e063414..bc7953e544b 100644 --- a/docs/legacy/direct-manipulation.md +++ b/docs/legacy/direct-manipulation.md @@ -67,7 +67,6 @@ Composite components are not backed by a native view, so you cannot call `setNat ```SnackPlayer name=setNativeProps%20with%20Composite%20Components&ext=js -import React from 'react'; import {Text, TouchableOpacity, View} from 'react-native'; const MyButton = props => ( @@ -89,7 +88,6 @@ export default App; ```SnackPlayer name=setNativeProps%20with%20Composite%20Components&ext=tsx -import React from 'react'; import {Text, TouchableOpacity, View} from 'react-native'; const MyButton = (props: {label: string}) => ( @@ -120,10 +118,10 @@ Since the `setNativeProps` method exists on any ref to a `View` component, it is ```SnackPlayer name=Forwarding%20setNativeProps&ext=js -import React from 'react'; +import {forwardRef} from 'react'; import {Text, TouchableOpacity, View} from 'react-native'; -const MyButton = React.forwardRef((props, ref) => ( +const MyButton = forwardRef((props, ref) => ( {props.label} @@ -142,10 +140,10 @@ export default App; ```SnackPlayer name=Forwarding%20setNativeProps&ext=tsx -import React from 'react'; +import {forwardRef} from 'react'; import {Text, TouchableOpacity, View} from 'react-native'; -const MyButton = React.forwardRef((props, ref) => ( +const MyButton = forwardRef((props, ref) => ( {props.label} @@ -175,7 +173,6 @@ Another very common use case of `setNativeProps` is to edit the value of the Tex ```SnackPlayer name=Clear%20text&ext=js -import React from 'react'; import {useCallback, useRef} from 'react'; import { StyleSheet, @@ -223,7 +220,6 @@ export default App; ```SnackPlayer name=Clear%20text&ext=tsx -import React from 'react'; import {useCallback, useRef} from 'react'; import { StyleSheet, @@ -320,7 +316,7 @@ This method can also be called with a `relativeToNativeNode` handler (instead of ```SnackPlayer name=measureLayout%20example&supportedPlatforms=android,ios&ext=js -import React, {useEffect, useRef, useState} from 'react'; +import {useEffect, useRef, useState} from 'react'; import {Text, View, StyleSheet} from 'react-native'; const App = () => { @@ -373,7 +369,7 @@ export default App; ```SnackPlayer name=measureLayout%20example&ext=tsx -import React, {useEffect, useRef, useState} from 'react'; +import {useEffect, useRef, useState} from 'react'; import {Text, View, StyleSheet} from 'react-native'; type Measurements = { diff --git a/docs/legacy/native-components-android.md b/docs/legacy/native-components-android.md index 9443d854c53..d1b853213e0 100644 --- a/docs/legacy/native-components-android.md +++ b/docs/legacy/native-components-android.md @@ -831,7 +831,7 @@ export const MyViewManager = II. Then implement custom View calling the `create` method: ```tsx title="MyView.tsx" -import React, {useEffect, useRef} from 'react'; +import {useEffect, useRef} from 'react'; import { PixelRatio, UIManager, diff --git a/docs/legacy/native-modules-android.md b/docs/legacy/native-modules-android.md index 82fe222f628..cec5857a441 100644 --- a/docs/legacy/native-modules-android.md +++ b/docs/legacy/native-modules-android.md @@ -315,7 +315,6 @@ At this point, you have set up the basic scaffolding for your native module in A Find a place in your application where you would like to add a call to the native module’s `createCalendarEvent()` method. Below is an example of a component, `NewModuleButton` you can add in your app. You can invoke the native module inside `NewModuleButton`'s `onPress()` function. ```tsx -import React from 'react'; import {NativeModules, Button} from 'react-native'; const NewModuleButton = () => { diff --git a/docs/legacy/native-modules-ios.md b/docs/legacy/native-modules-ios.md index 6c33c64ec75..d3239e16a90 100644 --- a/docs/legacy/native-modules-ios.md +++ b/docs/legacy/native-modules-ios.md @@ -141,7 +141,6 @@ At this point you have set up the basic scaffolding for your native module in iO Find a place in your application where you would like to add a call to the native module’s `createCalendarEvent()` method. Below is an example of a component, `NewModuleButton` you can add in your app. You can invoke the native module inside `NewModuleButton`'s `onPress()` function. ```tsx -import React from 'react'; import {Button} from 'react-native'; const NewModuleButton = () => { diff --git a/docs/linking.md b/docs/linking.md index ff9c1e1121e..308d1660d61 100644 --- a/docs/linking.md +++ b/docs/linking.md @@ -137,7 +137,7 @@ You can handle these events with `Linking.getInitialURL()` - it returns a Promis ```SnackPlayer name=Linking%20Example&supportedPlatforms=ios,android&ext=js -import React, {useCallback} from 'react'; +import {useCallback} from 'react'; import {Alert, Button, Linking, StyleSheet, View} from 'react-native'; const supportedURL = 'https://google.com'; @@ -185,7 +185,7 @@ export default App; ```SnackPlayer name=Linking%20Example&supportedPlatforms=ios,android&ext=tsx -import React, {useCallback} from 'react'; +import {useCallback} from 'react'; import {Alert, Button, Linking, StyleSheet, View} from 'react-native'; const supportedURL = 'https://google.com'; @@ -243,7 +243,7 @@ export default App; ```SnackPlayer name=Linking%20Example&supportedPlatforms=ios,android&ext=js -import React, {useCallback} from 'react'; +import {useCallback} from 'react'; import {Button, Linking, StyleSheet, View} from 'react-native'; const OpenSettingsButton = ({children}) => { @@ -278,7 +278,7 @@ export default App; ```SnackPlayer name=Linking%20Example&supportedPlatforms=ios,android&ext=tsx -import React, {useCallback} from 'react'; +import {useCallback} from 'react'; import {Button, Linking, StyleSheet, View} from 'react-native'; type OpenSettingsButtonProps = { @@ -322,7 +322,7 @@ export default App; ```SnackPlayer name=Linking%20Example&supportedPlatforms=ios,android&ext=js -import React, {useState, useEffect} from 'react'; +import {useState, useEffect} from 'react'; import {Linking, StyleSheet, Text, View} from 'react-native'; const useInitialURL = () => { @@ -376,7 +376,7 @@ export default App; ```SnackPlayer name=Linking%20Example&supportedPlatforms=ios,android&ext=tsx -import React, {useState, useEffect} from 'react'; +import {useState, useEffect} from 'react'; import {Linking, StyleSheet, Text, View} from 'react-native'; const useInitialURL = () => { @@ -435,7 +435,7 @@ export default App; ```SnackPlayer name=Linking%20Example&supportedPlatforms=android&ext=js -import React, {useCallback} from 'react'; +import {useCallback} from 'react'; import {Alert, Button, Linking, StyleSheet, View} from 'react-native'; const SendIntentButton = ({action, extras, children}) => { @@ -485,7 +485,7 @@ export default App; ```SnackPlayer name=Linking%20Example&ext=tsx -import React, {useCallback} from 'react'; +import {useCallback} from 'react'; import {Alert, Button, Linking, StyleSheet, View} from 'react-native'; type SendIntentButtonProps = { diff --git a/docs/modal.md b/docs/modal.md index 45be2531592..4ad9af1381f 100644 --- a/docs/modal.md +++ b/docs/modal.md @@ -8,7 +8,7 @@ The Modal component is a basic way to present content above an enclosing view. ## Example ```SnackPlayer name=Modal&supportedPlatforms=android,ios -import React, {useState} from 'react'; +import {useState} from 'react'; import {Alert, Modal, StyleSheet, Text, Pressable, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/navigation.md b/docs/navigation.md index 363b48b1261..4d9586bf801 100644 --- a/docs/navigation.md +++ b/docs/navigation.md @@ -64,7 +64,6 @@ Now you are ready to build and run your app on the device/simulator. Now you can create an app with a home screen and a profile screen: ```tsx -import * as React from 'react'; import {createStaticNavigation} from '@react-navigation/native'; import {createNativeStackNavigator} from '@react-navigation/native-stack'; diff --git a/docs/network.md b/docs/network.md index ac014628da1..005db77962b 100644 --- a/docs/network.md +++ b/docs/network.md @@ -78,7 +78,7 @@ Don't forget to catch any errors that may be thrown by `fetch`, otherwise they w ```SnackPlayer name=Fetch%20Example&ext=js -import React, {useEffect, useState} from 'react'; +import {useEffect, useState} from 'react'; import {ActivityIndicator, FlatList, Text, View} from 'react-native'; const App = () => { @@ -127,7 +127,7 @@ export default App; ```SnackPlayer name=Fetch%20Example&ext=tsx -import React, {useEffect, useState} from 'react'; +import {useEffect, useState} from 'react'; import {ActivityIndicator, FlatList, Text, View} from 'react-native'; type Movie = { diff --git a/docs/optimizing-flatlist-configuration.md b/docs/optimizing-flatlist-configuration.md index a81ec0c6cf6..9ce09c365df 100644 --- a/docs/optimizing-flatlist-configuration.md +++ b/docs/optimizing-flatlist-configuration.md @@ -98,7 +98,7 @@ The heavier your components are, the slower they render. Avoid heavy images (use `React.memo()` creates a memoized component that will be re-rendered only when the props passed to the component change. We can use this function to optimize the components in the FlatList. ```tsx -import React, {memo} from 'react'; +import {memo} from 'react'; import {View, Text} from 'react-native'; const MyListItem = memo( diff --git a/docs/panresponder.md b/docs/panresponder.md index fa6d8b8ee4e..c7197248416 100644 --- a/docs/panresponder.md +++ b/docs/panresponder.md @@ -34,7 +34,7 @@ A `gestureState` object has the following: ```tsx const ExampleComponent = () => { - const panResponder = React.useRef( + const panResponder = useRef( PanResponder.create({ // Ask to be the responder: onStartShouldSetPanResponder: (evt, gestureState) => true, @@ -81,7 +81,7 @@ const ExampleComponent = () => { `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 ```SnackPlayer name=PanResponder -import React, {useRef} from 'react'; +import {useRef} from 'react'; import {Animated, View, StyleSheet, PanResponder, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/permissionsandroid.md b/docs/permissionsandroid.md index ec1f486ba37..4e93941ad1f 100644 --- a/docs/permissionsandroid.md +++ b/docs/permissionsandroid.md @@ -17,7 +17,6 @@ If a user has previously turned off a permission that you prompt for, the OS wil ### Example ```SnackPlayer name=PermissionsAndroid%20Example&supportedPlatforms=android -import React from 'react'; import { Button, PermissionsAndroid, diff --git a/docs/pixelratio.md b/docs/pixelratio.md index 64e4eded49f..f298a8e73ab 100644 --- a/docs/pixelratio.md +++ b/docs/pixelratio.md @@ -30,7 +30,6 @@ In React Native, everything in JavaScript and within the layout engine works wit ## Example ```SnackPlayer name=PixelRatio%20Example -import React from 'react'; import { Image, PixelRatio, diff --git a/docs/platform.md b/docs/platform.md index 79f435ccd56..b8642658a84 100644 --- a/docs/platform.md +++ b/docs/platform.md @@ -6,7 +6,6 @@ title: Platform ## Example ```SnackPlayer name=Platform%20API%20Example&supportedPlatforms=ios,android -import React from 'react'; import {Platform, StyleSheet, Text, ScrollView} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/platformcolor.md b/docs/platformcolor.md index 17371f76c26..040c6d2c18a 100644 --- a/docs/platformcolor.md +++ b/docs/platformcolor.md @@ -46,7 +46,6 @@ If you’re familiar with design systems, another way of thinking about this is ## Example ```SnackPlayer name=PlatformColor%20Example&supportedPlatforms=android,ios -import React from 'react'; import {Platform, PlatformColor, StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/pressable.md b/docs/pressable.md index 70480cfd719..5c1a0933fc0 100644 --- a/docs/pressable.md +++ b/docs/pressable.md @@ -47,7 +47,7 @@ The touch area never extends past the parent view bounds and the Z-index of sibl ## Example ```SnackPlayer name=Pressable -import React, {useState} from 'react'; +import {useState} from 'react'; import {Pressable, StyleSheet, Text, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/progressbarandroid.md b/docs/progressbarandroid.md index 4f165d86c46..f8810dc541a 100644 --- a/docs/progressbarandroid.md +++ b/docs/progressbarandroid.md @@ -12,7 +12,6 @@ Android-only React component used to indicate that the app is loading or there i ### Example ```SnackPlayer name=ProgressBarAndroid&supportedPlatforms=android -import React from 'react'; import {View, StyleSheet, ProgressBarAndroid, Text} from 'react-native'; const App = () => { diff --git a/docs/props.md b/docs/props.md index 490eb214632..8b24d6dd9f1 100644 --- a/docs/props.md +++ b/docs/props.md @@ -10,7 +10,6 @@ Most components can be customized when they are created, with different paramete 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. ```SnackPlayer name=Props -import React from 'react'; import {Image} from 'react-native'; const Bananas = () => { @@ -33,7 +32,6 @@ Your own components can also use `props`. This lets you make a single component ```SnackPlayer name=Props&ext=js -import React from 'react'; import {Text, View} from 'react-native'; const Greeting = props => { @@ -61,7 +59,6 @@ export default LotsOfGreetings; ```SnackPlayer name=Props&ext=tsx -import React from 'react'; import {Text, View} from 'react-native'; type GreetingProps = { diff --git a/docs/refreshcontrol.md b/docs/refreshcontrol.md index 7f7faab6744..87fac2e1690 100644 --- a/docs/refreshcontrol.md +++ b/docs/refreshcontrol.md @@ -8,14 +8,14 @@ This component is used inside a ScrollView or ListView to add pull to refresh fu ## Example ```SnackPlayer name=RefreshControl&supportedPlatforms=ios,android -import React from 'react'; +import {useCallback, useState} from 'react'; import {RefreshControl, ScrollView, StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; const App = () => { - const [refreshing, setRefreshing] = React.useState(false); + const [refreshing, setRefreshing] = useState(false); - const onRefresh = React.useCallback(() => { + const onRefresh = useCallback(() => { setRefreshing(true); setTimeout(() => { setRefreshing(false); diff --git a/docs/safeareaview.md b/docs/safeareaview.md index fd0d2d479c3..b8373e905a2 100644 --- a/docs/safeareaview.md +++ b/docs/safeareaview.md @@ -16,7 +16,6 @@ The purpose of `SafeAreaView` is to render content within the safe area boundari 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. ```SnackPlayer name=SafeAreaView&supportedPlatforms=ios -import React from 'react'; import {StyleSheet, Text, SafeAreaView} from 'react-native'; const App = () => { diff --git a/docs/scrollview.md b/docs/scrollview.md index f24d99073cc..aec1d79a36b 100644 --- a/docs/scrollview.md +++ b/docs/scrollview.md @@ -22,7 +22,6 @@ This is where `FlatList` comes into play. `FlatList` renders items lazily, when ## Example ```SnackPlayer name=ScrollView%20Example -import React from 'react'; import {StyleSheet, Text, ScrollView, StatusBar} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/sectionlist.md b/docs/sectionlist.md index d0e9519a301..ead40b211b9 100644 --- a/docs/sectionlist.md +++ b/docs/sectionlist.md @@ -21,7 +21,6 @@ If you don't need section support and want a simpler interface, use [` ## Example ```SnackPlayer name=SectionList%20Example -import React from 'react'; import {StyleSheet, Text, View, SectionList, StatusBar} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/settings.md b/docs/settings.md index 01c0533d813..0a5dc85032f 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -8,7 +8,7 @@ title: Settings ## Example ```SnackPlayer name=Settings%20Example&supportedPlatforms=ios -import React, {useState} from 'react'; +import {useState} from 'react'; import {Button, Settings, StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/shadow-props.md b/docs/shadow-props.md index d5e8a037059..7dcaa331e79 100644 --- a/docs/shadow-props.md +++ b/docs/shadow-props.md @@ -9,7 +9,7 @@ import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import con ```SnackPlayer name=Shadow%20Props&supportedPlatforms=ios&ext=js&dependencies=@react-native-community/slider -import React, {useState} from 'react'; +import {useState} from 'react'; import {Text, View, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; import Slider from '@react-native-community/slider'; @@ -110,7 +110,7 @@ export default App; ```SnackPlayer name=Shadow%20Props&supportedPlatforms=ios&ext=tsx&dependencies=@react-native-community/slider -import React, {useState} from 'react'; +import {useState} from 'react'; import {Text, View, StyleSheet} from 'react-native'; import Slider, {SliderProps} from '@react-native-community/slider'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/share.md b/docs/share.md index 1fc5823361f..46d0f858435 100644 --- a/docs/share.md +++ b/docs/share.md @@ -11,7 +11,6 @@ import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import con ```SnackPlayer name=Example&supportedPlatforms=ios,android&ext=js -import React from 'react'; import {Alert, Share, Button} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -51,7 +50,6 @@ export default ShareExample; ```SnackPlayer name=Example&supportedPlatforms=ios,android&ext=tsx -import React from 'react'; import {Alert, Share, Button} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/state.md b/docs/state.md index bc162f44b40..b8a1959af5f 100644 --- a/docs/state.md +++ b/docs/state.md @@ -15,7 +15,7 @@ For example, let's say we want to make text that blinks all the time. The text i ```SnackPlayer name=State&ext=js -import React, {useState, useEffect} from 'react'; +import {useState, useEffect} from 'react'; import {Text, View} from 'react-native'; const Blink = props => { @@ -54,7 +54,7 @@ export default BlinkApp; ```SnackPlayer name=State&ext=tsx -import React, {useState, useEffect} from 'react'; +import {useState, useEffect} from 'react'; import {Text, View} from 'react-native'; type BlinkProps = { diff --git a/docs/statusbar.md b/docs/statusbar.md index 6345e7bf4ef..b1d5c210ed6 100644 --- a/docs/statusbar.md +++ b/docs/statusbar.md @@ -15,7 +15,7 @@ It is possible to have multiple `StatusBar` components mounted at the same time. ```SnackPlayer name=StatusBar%20Component%20Example&supportedPlatforms=android,ios&ext=js -import React, {useState} from 'react'; +import {useState} from 'react'; import { Button, Platform, @@ -123,7 +123,7 @@ export default App; ```SnackPlayer name=StatusBar%20Component%20Example&supportedPlatforms=android,ios&ext=tsx -import React, {useState} from 'react'; +import {useState} from 'react'; import { Button, Platform, diff --git a/docs/style.md b/docs/style.md index d847c0597cb..4890db4fbfa 100644 --- a/docs/style.md +++ b/docs/style.md @@ -10,7 +10,6 @@ The `style` prop can be a plain old JavaScript object. That's what we usually us 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: ```SnackPlayer name=Style -import React from 'react'; import {StyleSheet, Text, View} from 'react-native'; const LotsOfStyles = () => { diff --git a/docs/stylesheet.md b/docs/stylesheet.md index 78918aeb374..1ac0eab9880 100644 --- a/docs/stylesheet.md +++ b/docs/stylesheet.md @@ -6,7 +6,6 @@ title: StyleSheet A StyleSheet is an abstraction similar to CSS StyleSheets. ```SnackPlayer name=StyleSheet -import React from 'react'; import {StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -62,7 +61,6 @@ 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. ```SnackPlayer name=Compose -import React from 'react'; import {StyleSheet, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -123,7 +121,6 @@ static flatten(style: Array ( diff --git a/docs/switch.md b/docs/switch.md index 4f9055c6256..891847d7fee 100644 --- a/docs/switch.md +++ b/docs/switch.md @@ -10,7 +10,7 @@ This is a controlled component that requires an `onValueChange` callback that up ## Example ```SnackPlayer name=Switch&supportedPlatforms=android,ios -import React, {useState} from 'react'; +import {useState} from 'react'; import {Switch, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/systrace.md b/docs/systrace.md index 53cfd62c7a9..9aa54fe8e18 100644 --- a/docs/systrace.md +++ b/docs/systrace.md @@ -10,7 +10,6 @@ title: Systrace `Systrace` allows you to mark JavaScript (JS) events with a tag and an integer value. Capture the non-Timed JS events in EasyProfiler. ```SnackPlayer name=Systrace%20Example -import React from 'react'; import {Button, Text, View, StyleSheet, Systrace} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/text-nodes.md b/docs/text-nodes.md index 63f195ea4b5..17d372c86e5 100644 --- a/docs/text-nodes.md +++ b/docs/text-nodes.md @@ -6,14 +6,14 @@ title: Text nodes 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. ```SnackPlayer ext=js&name=Text%20instances%20example -import * as React from 'react'; -import { SafeAreaView, StyleSheet, Text } from 'react-native'; +import {useEffect, useRef, useState} from 'react'; +import {SafeAreaView, StyleSheet, Text} from 'react-native'; const TextWithRefs = () => { - const ref = React.useRef(null); - const [viewInfo, setViewInfo] = React.useState(''); + const ref = useRef(null); + const [viewInfo, setViewInfo] = useState(''); - React.useEffect(() => { + useEffect(() => { // `textElement` is an object implementing the interface described here. const textElement = ref.current; const textNode = textElement.childNodes[0]; diff --git a/docs/text-style-props.md b/docs/text-style-props.md index 64ffc4ef816..227fccadbf4 100644 --- a/docs/text-style-props.md +++ b/docs/text-style-props.md @@ -11,7 +11,7 @@ import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import con ```SnackPlayer name=TextStyleProps&supportedPlatforms=ios,android&ext=js&dependencies=@react-native-community/slider -import React, {useState} from 'react'; +import {useState} from 'react'; import { FlatList, Platform, @@ -372,7 +372,7 @@ export default App; ```SnackPlayer name=TextStyleProps&supportedPlatforms=ios,android&ext=tsx&dependencies=@react-native-community/slider -import React, {useState} from 'react'; +import {useState} from 'react'; import { FlatList, Platform, diff --git a/docs/text.md b/docs/text.md index 3112485639c..b637552bfa5 100644 --- a/docs/text.md +++ b/docs/text.md @@ -10,7 +10,7 @@ A React component for displaying text. 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: ```SnackPlayer name=Text%20Function%20Component%20Example -import React, {useState} from 'react'; +import {useState} from 'react'; import {Text, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -59,7 +59,6 @@ export default TextInANest; 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. ```SnackPlayer name=Nested%20Text%20Example -import React from 'react'; import {Text, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/textinput.md b/docs/textinput.md index c1d62e96278..379f4e5da37 100644 --- a/docs/textinput.md +++ b/docs/textinput.md @@ -8,13 +8,13 @@ A foundational component for inputting text into the app via a keyboard. Props p 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: ```SnackPlayer name=TextInput%20Example -import React from 'react'; +import {useState} from 'react'; import {StyleSheet, TextInput} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; const TextInputExample = () => { - const [text, onChangeText] = React.useState('Useless Text'); - const [number, onChangeNumber] = React.useState(''); + const [text, onChangeText] = useState('Useless Text'); + const [number, onChangeNumber] = useState(''); return ( @@ -53,12 +53,12 @@ Two methods exposed via the native element are `.focus()` and `.blur()` that wil Note that some props are only available with `multiline={true/false}`. Additionally, border styles that apply to only one side of the element (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if `multiline=true`. To achieve the same effect, you can wrap your `TextInput` in a `View`: ```SnackPlayer name=Multiline%20TextInput%20Example -import React from 'react'; +import {useState} from 'react'; import {TextInput, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; const MultilineTextInputExample = () => { - const [value, onChangeText] = React.useState('Useless Multiline Placeholder'); + const [value, onChangeText] = useState('Useless Multiline Placeholder'); // If you type something in the text box that is a color, // the background will change to that color. diff --git a/docs/the-new-architecture/custom-cxx-types.md b/docs/the-new-architecture/custom-cxx-types.md index 94db3e21b3f..edc490b8070 100644 --- a/docs/the-new-architecture/custom-cxx-types.md +++ b/docs/the-new-architecture/custom-cxx-types.md @@ -173,8 +173,8 @@ First, we need to update the `App.tsx` file to use the new method from the Turbo ```diff title="App.tsx" // ... -+ const [cubicSource, setCubicSource] = React.useState('') -+ const [cubicRoot, setCubicRoot] = React.useState(0) ++ const [cubicSource, setCubicSource] = useState('') ++ const [cubicRoot, setCubicRoot] = useState(0) return ( @@ -366,9 +366,9 @@ To test the code in the app, we have to modify the `App.tsx` file. 2. Replace the body of the `App()` function with the following code: ```tsx title="App.tsx (App function body replacement)" -const [street, setStreet] = React.useState(''); -const [num, setNum] = React.useState(''); -const [isValidAddress, setIsValidAddress] = React.useState< +const [street, setStreet] = useState(''); +const [num, setNum] = useState(''); +const [isValidAddress, setIsValidAddress] = useState< boolean | null >(null); diff --git a/docs/the-new-architecture/direct-manipulation.md b/docs/the-new-architecture/direct-manipulation.md index 6708a643cba..6035b6a64b7 100644 --- a/docs/the-new-architecture/direct-manipulation.md +++ b/docs/the-new-architecture/direct-manipulation.md @@ -26,7 +26,6 @@ For example, the following code demonstrates editing the input when you tap a bu ```SnackPlayer name=setNativeProps%20on%20TextInput&ext=js -import React from 'react'; import {useCallback, useRef} from 'react'; import { StyleSheet, @@ -74,7 +73,6 @@ export default App; ```SnackPlayer name=Clear%20text&ext=tsx -import React from 'react'; import {useCallback, useRef} from 'react'; import { StyleSheet, diff --git a/docs/the-new-architecture/fabric-component-native-commands.md b/docs/the-new-architecture/fabric-component-native-commands.md index ca87360ba3a..5cb5dbd6710 100644 --- a/docs/the-new-architecture/fabric-component-native-commands.md +++ b/docs/the-new-architecture/fabric-component-native-commands.md @@ -107,7 +107,6 @@ Now you can use the command in the the app. Open the `App.tsx` file and modify it as it follows: ```diff title="App.tsx" -import React from 'react'; -import {Alert, StyleSheet, View} from 'react-native'; -import WebView from '../specs/WebViewNativeComponent'; +import {Alert, StyleSheet, Pressable, Text, View} from 'react-native'; @@ -186,7 +185,6 @@ export default App; Open the `App.tsx` file and modify it as it follows: ```diff title="App.jsx" -import React from 'react'; -import {Alert, StyleSheet, View} from 'react-native'; -import WebView from '../specs/WebViewNativeComponent'; +import {Alert, StyleSheet, Pressable, Text, View} from 'react-native'; diff --git a/docs/the-new-architecture/layout-measurements.md b/docs/the-new-architecture/layout-measurements.md index cc693a99b0c..715cd42aee7 100644 --- a/docs/the-new-architecture/layout-measurements.md +++ b/docs/the-new-architecture/layout-measurements.md @@ -10,7 +10,7 @@ Typical code will look like this: ```tsx function AComponent(children) { - const targetRef = React.useRef(null) + const targetRef = useRef(null) useLayoutEffect(() => { targetRef.current?.measure((x, y, width, height, pageX, pageY) => { diff --git a/docs/the-new-architecture/native-modules-custom-events.md b/docs/the-new-architecture/native-modules-custom-events.md index 0af5bb95957..c44bbf93c16 100644 --- a/docs/the-new-architecture/native-modules-custom-events.md +++ b/docs/the-new-architecture/native-modules-custom-events.md @@ -134,7 +134,6 @@ 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: ```diff title="App.tsx" -import React from 'react'; import { + Alert, + EventSubscription, diff --git a/docs/the-new-architecture/pure-cxx-modules.md b/docs/the-new-architecture/pure-cxx-modules.md index b7c08196290..06a11572201 100644 --- a/docs/the-new-architecture/pure-cxx-modules.md +++ b/docs/the-new-architecture/pure-cxx-modules.md @@ -423,7 +423,7 @@ It's now time to access our C++ Turbo Native Module from JS. To do so, we have t 2. Replace the content of the template with the following code: ```tsx title="App.tsx" -import React from 'react'; +import {type JSX, useState} from 'react'; import { Button, SafeAreaView, @@ -434,9 +434,9 @@ import { } from 'react-native'; import SampleTurboModule from './specs/NativeSampleModule'; -function App(): React.JSX.Element { - const [value, setValue] = React.useState(''); - const [reversedValue, setReversedValue] = React.useState(''); +function App(): JSX.Element { + const [value, setValue] = useState(''); + const [reversedValue, setReversedValue] = useState(''); const onPress = () => { const revString = SampleTurboModule.reverseString(value); diff --git a/docs/toastandroid.md b/docs/toastandroid.md index 0d7a569235d..07f2b7b20cd 100644 --- a/docs/toastandroid.md +++ b/docs/toastandroid.md @@ -17,7 +17,6 @@ Starting with Android 11 (API level 30), setting the gravity has no effect on te ::: ```SnackPlayer name=Toast%20Android%20API%20Example&supportedPlatforms=android -import React from 'react'; import {StyleSheet, ToastAndroid, Button, StatusBar} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/touchablehighlight.md b/docs/touchablehighlight.md index 98ea0823783..b34916e0aa4 100644 --- a/docs/touchablehighlight.md +++ b/docs/touchablehighlight.md @@ -33,7 +33,7 @@ function MyComponent(props: MyComponentProps) { ## Example ```SnackPlayer name=TouchableHighlight%20Example -import React, {useState} from 'react'; +import {useState} from 'react'; import {StyleSheet, Text, TouchableHighlight, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/touchablenativefeedback.md b/docs/touchablenativefeedback.md index a7465b9f2ed..b44f68365e9 100644 --- a/docs/touchablenativefeedback.md +++ b/docs/touchablenativefeedback.md @@ -16,7 +16,7 @@ Background drawable of native feedback touchable can be customized with `backgro ## Example ```SnackPlayer name=TouchableNativeFeedback%20Android%20Component%20Example&supportedPlatforms=android -import React, {useState} from 'react'; +import {useState} from 'react'; import {Text, View, StyleSheet, TouchableNativeFeedback} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/touchableopacity.md b/docs/touchableopacity.md index 72af0bc5f49..b48209f5a44 100644 --- a/docs/touchableopacity.md +++ b/docs/touchableopacity.md @@ -14,7 +14,7 @@ Opacity is controlled by wrapping the children in an `Animated.View`, which is a ## Example ```SnackPlayer name=TouchableOpacity%20Example -import React, {useState} from 'react'; +import {useState} from 'react'; import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/touchablewithoutfeedback.md b/docs/touchablewithoutfeedback.md index c7e875156df..bd2d68fcb42 100644 --- a/docs/touchablewithoutfeedback.md +++ b/docs/touchablewithoutfeedback.md @@ -30,7 +30,7 @@ function MyComponent(props: MyComponentProps) { ## Example ```SnackPlayer name=TouchableWithoutFeedback -import React, {useState} from 'react'; +import {useState} from 'react'; import {StyleSheet, TouchableWithoutFeedback, Text, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/transforms.md b/docs/transforms.md index 92a75671719..13d17d82103 100644 --- a/docs/transforms.md +++ b/docs/transforms.md @@ -8,7 +8,6 @@ Transforms are style properties that will help you modify the appearance and pos ## Example ```SnackPlayer name=Transforms%20Example -import React from 'react'; import {ScrollView, StyleSheet, Text, View} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -279,7 +278,7 @@ The `transformOrigin` property sets the origin for a view's transformations. The # Example ```SnackPlayer name=TransformOrigin%20Example -import React, {useEffect, useRef} from 'react'; +import {useEffect, useRef} from 'react'; import {Animated, View, StyleSheet, Easing} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 811302be504..540f38b984f 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -91,7 +91,6 @@ To revert the `User Search Header Paths` and `Header Search Paths` build setting React Native implements a polyfill for WebSockets. These [polyfills](https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/InitializeCore.js) are initialized as part of the react-native module that you include in your application through `import React from 'react'`. If you load another module that requires WebSockets, such as [Firebase](https://github.com/facebook/react-native/issues/3645), be sure to load/require it after react-native: ``` -import React from 'react'; import Firebase from 'firebase'; ``` diff --git a/docs/turbo-native-modules.md b/docs/turbo-native-modules.md index eeef8624578..4d97e5bbb7a 100644 --- a/docs/turbo-native-modules.md +++ b/docs/turbo-native-modules.md @@ -166,7 +166,7 @@ The `TurboModuleRegistry` supports 2 modes of retrieving a Turbo Native Module: - `getEnforcing(name: string): T` which will throw an exception if the Turbo Native Module is unavailable. This assumes the module is always available. ```tsx title="App.tsx" -import React from 'react'; +import {useEffect, useState, type JSX} from 'react'; import { SafeAreaView, StyleSheet, @@ -179,14 +179,14 @@ import NativeLocalStorage from './specs/NativeLocalStorage'; const EMPTY = ''; -function App(): React.JSX.Element { - const [value, setValue] = React.useState(null); +function App(): JSX.Element { + const [value, setValue] = useState(null); - const [editingValue, setEditingValue] = React.useState< - string | null - >(null); + const [editingValue, setEditingValue] = useState( + null, + ); - React.useEffect(() => { + useEffect(() => { const storedValue = NativeLocalStorage?.getItem('myKey'); setValue(storedValue ?? ''); }, []); diff --git a/docs/tutorial.md b/docs/tutorial.md index d1a92919cd7..80c79e1ed8e 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -14,7 +14,6 @@ Let's do this thing. In accordance with the ancient traditions of our people, we must first build an app that does nothing except say "Hello, world!". Here it is: ```SnackPlayer name=Hello%20World -import React from 'react'; import {Text, View} from 'react-native'; const HelloWorldApp = () => { @@ -67,7 +66,6 @@ Your own components can also use `props`. This lets you make a single component ```SnackPlayer name=Hello%20Props&ext=js -import React from 'react'; import {Text, View, StyleSheet} from 'react-native'; const styles = StyleSheet.create({ @@ -101,7 +99,6 @@ export default LotsOfGreetings; ```SnackPlayer name=Hello%20Props&ext=tsx -import React from 'react'; import {Text, View, StyleSheet} from 'react-native'; const styles = StyleSheet.create({ @@ -157,9 +154,9 @@ In a React component, the props are the variables that we pass from a parent com
```tsx -// ReactJS Counter Example using Hooks! +// React Counter Example using Hooks! -import React, {useState} from 'react'; +import {useState} from 'react'; @@ -190,7 +187,7 @@ const App = () => { ```tsx // React Native Counter Example using Hooks! -import React, {useState} from 'react'; +import {useState} from 'react'; import {View, Text, Button, StyleSheet} from 'react-native'; const App = () => { @@ -224,7 +221,7 @@ As shown above, there is no difference in handling the `state` between [React](h In the following example we will show the same above counter example using classes. ```SnackPlayer name=Hello%20Classes -import React, {Component} from 'react'; +import {Component} from 'react'; import {StyleSheet, TouchableOpacity, Text, View} from 'react-native'; class App extends Component { diff --git a/docs/usecolorscheme.md b/docs/usecolorscheme.md index 42f16f775d7..14b7becabe8 100644 --- a/docs/usecolorscheme.md +++ b/docs/usecolorscheme.md @@ -20,7 +20,6 @@ The `useColorScheme` React hook provides and subscribes to color scheme updates ## Example ```SnackPlayer -import React from 'react'; import {Text, StyleSheet, useColorScheme} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/usewindowdimensions.md b/docs/usewindowdimensions.md index 92bb1931d32..3e8a8077370 100644 --- a/docs/usewindowdimensions.md +++ b/docs/usewindowdimensions.md @@ -16,7 +16,6 @@ const {height, width} = useWindowDimensions(); ## Example ```SnackPlayer name=useWindowDimensions&supportedPlatforms=ios,android -import React from 'react'; import {StyleSheet, Text, useWindowDimensions} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/using-a-listview.md b/docs/using-a-listview.md index cf13fa66a6c..a5a04f40279 100644 --- a/docs/using-a-listview.md +++ b/docs/using-a-listview.md @@ -12,7 +12,6 @@ The `FlatList` component requires two props: `data` and `renderItem`. `data` is 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. ```SnackPlayer name=FlatList%20Basics -import React from 'react'; import {FlatList, StyleSheet, Text, View} from 'react-native'; const styles = StyleSheet.create({ @@ -55,7 +54,6 @@ export default FlatListBasics; 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](sectionlist.md) is the way to go. ```SnackPlayer name=SectionList%20Basics -import React from 'react'; import {SectionList, StyleSheet, Text, View} from 'react-native'; const styles = StyleSheet.create({ diff --git a/docs/using-a-scrollview.md b/docs/using-a-scrollview.md index e4de6207a71..3ffae817bf0 100644 --- a/docs/using-a-scrollview.md +++ b/docs/using-a-scrollview.md @@ -8,7 +8,6 @@ The [ScrollView](scrollview.md) is a generic scrolling container that can contai This example creates a vertical `ScrollView` with both images and text mixed together. ```SnackPlayer name=Using%20ScrollView -import React from 'react'; import {Image, ScrollView, Text} from 'react-native'; const logo = { diff --git a/docs/vibration.md b/docs/vibration.md index 44a0af2db43..bdb564ab331 100644 --- a/docs/vibration.md +++ b/docs/vibration.md @@ -8,7 +8,6 @@ Vibrates the device. ## Example ```SnackPlayer name=Vibration%20Example&supportedPlatforms=ios,android -import React from 'react'; import { Button, Platform, diff --git a/docs/view-style-props.md b/docs/view-style-props.md index 431557883ad..562aa837ad5 100644 --- a/docs/view-style-props.md +++ b/docs/view-style-props.md @@ -9,7 +9,6 @@ import {getCoreBranchNameForCurrentVersion} from '@site/src/getCoreBranchNameFor ### Example ```SnackPlayer name=ViewStyleProps -import React from 'react'; import {View, StyleSheet} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/view.md b/docs/view.md index 3fd3c7fb4bd..405218dcc9b 100644 --- a/docs/view.md +++ b/docs/view.md @@ -12,7 +12,6 @@ The most fundamental component for building a UI, `View` is a container that sup This example creates a `View` that wraps two boxes with color and a text component in a row with padding. ```SnackPlayer name=View%20Example -import React from 'react'; import {View, Text} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/docs/virtualizedlist.md b/docs/virtualizedlist.md index e0a31ffb2e2..7cb55d1b5d7 100644 --- a/docs/virtualizedlist.md +++ b/docs/virtualizedlist.md @@ -15,7 +15,6 @@ Virtualization massively improves memory consumption and performance of large li ```SnackPlayer name=VirtualizedListExample&ext=js -import React from 'react'; import {View, VirtualizedList, StyleSheet, Text, StatusBar} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; @@ -71,7 +70,6 @@ export default App; ```SnackPlayer name=VirtualizedListExample&ext=tsx -import React from 'react'; import {View, VirtualizedList, StyleSheet, Text, StatusBar} from 'react-native'; import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; diff --git a/website/versioned_docs/version-0.80/_fabric-native-components.jsx b/website/versioned_docs/version-0.80/_fabric-native-components.jsx index fc6a3171a4f..69bc6f31268 100644 --- a/website/versioned_docs/version-0.80/_fabric-native-components.jsx +++ b/website/versioned_docs/version-0.80/_fabric-native-components.jsx @@ -1,4 +1,3 @@ -import React from 'react'; import IOSContent from './fabric-native-components-ios.md'; import AndroidContent from './fabric-native-components-android.md'; diff --git a/website/versioned_docs/version-0.80/_integration-with-existing-apps-ios.md b/website/versioned_docs/version-0.80/_integration-with-existing-apps-ios.md index 33d02fe901d..1509c3e72f0 100644 --- a/website/versioned_docs/version-0.80/_integration-with-existing-apps-ios.md +++ b/website/versioned_docs/version-0.80/_integration-with-existing-apps-ios.md @@ -1,650 +1,650 @@ -import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import constants from '@site/core/TabsConstants'; - -## Key Concepts - -The keys to integrating React Native components into your iOS application are to: - -1. Set up the correct directory structure. -2. Install the necessary NPM dependencies. -3. Adding React Native to your Podfile configuration. -4. Writing the TypeScript code for your first React Native screen. -5. Integrate React Native with your iOS code using a `RCTRootView`. -6. Testing your integration by running the bundler and seeing your app in action. - -## Using the Community Template - -While you follow this guide, we suggest you to use the [React Native Community Template](https://github.com/react-native-community/template/) as reference. The template contains a **minimal iOS app** and will help you understanding how to integrate React Native into an existing iOS app. - -## Prerequisites - -Follow the guide on [setting up your development environment](set-up-your-environment) and using [React Native without a framework](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 - -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 - -Go to the root directory and run the following command: - -```shell -curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-stable/template/package.json -``` - -This will copy the `package.json` [file from the Community template](https://github.com/react-native-community/template/blob/0.78-stable/template/package.json) to your project. - -Next, install the NPM packages by running: - - - - -```shell -npm install -``` - - - - -```shell -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.78-stable/template/_gitignore)). - -### 3. Install Development tools - -### 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. - -![Xcode Command Line Tools](/docs/assets/GettingStartedXcodeCommandLineTools.png) - -### 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/): - -```shell -brew install cocoapods -``` - -## 4. Adding React Native to your app - -### Configuring CocoaPods - -To configure CocoaPods, we need two files: - -- A **Gemfile** that defines which Ruby dependencies we need. -- A **Podfile** that defines how to properly install our dependencies. - -For the **Gemfile**, go to the root directory of your project and run this command - -```sh -curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-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 - -```sh -curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-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.78-stable/template/Gemfile) and for the [Podfile](https://github.com/react-native-community/template/blob/0.78-stable/template/ios/Podfile). - -:::note -Remember to change [this line](https://github.com/react-native-community/template/blob/0.78-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: - -```sh -bundle install -bundle exec pod install -``` - -The first command will install the Ruby dependencies and the second command will actually integrate the React Native code in your application so that your iOS files can import the React Native headers. - -## 5. Writing the TypeScript Code - -Now we will actually modify the native iOS application to integrate React Native. - -The first bit of code we will write is the actual React Native code for the new screen that will be integrated into our application. - -### Create a `index.js` file - -First, create an empty `index.js` file in the root of your React Native project. - -`index.js` is the starting point for React Native applications, and it is always required. It can be a small file that `import`s other file that are part of your React Native component or application, or it can contain all the code that is needed for it. - -Our `index.js` should look as follows (here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.78-stable/template/index.js)): - -```js -import {AppRegistry} from 'react-native'; -import App from './App'; - -AppRegistry.registerComponent('HelloWorld', () => App); -``` - -### Create a `App.tsx` file - -Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX]() 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.78-stable/template/App.tsx)): - -```tsx -import React 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(): React.JSX.Element { - const isDarkMode = useColorScheme() === 'dark'; - - const backgroundStyle = { - backgroundColor: isDarkMode ? Colors.darker : Colors.lighter, - }; - - return ( - - - -
- - Step One - - Edit App.tsx to - change this screen and see your edits. - - See your changes - - Debug - - - - - ); -} - -const styles = StyleSheet.create({ - title: { - fontSize: 24, - fontWeight: '600', - }, - bold: { - fontWeight: '700', - }, -}); - -export default App; -``` - -Here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.78-stable/template/App.tsx) - -## 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 - -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`. - -#### Create the ReactViewController - -Create a new file from template (+N) and choose the Cocoa Touch Class template. - -Make sure to select `UIViewController` as the "Subclass of" field. - - - - -Now open the `ReactViewController.m` file and apply the following changes - -```diff title="ReactViewController.m" -#import "ReactViewController.h" -+#import -+#import -+#import -+#import - - -@interface ReactViewController () - -@end - -+@interface ReactNativeFactoryDelegate: RCTDefaultReactNativeFactoryDelegate -+@end - --@implementation ReactViewController -+@implementation ReactViewController { -+ RCTReactNativeFactory *_factory; -+ id _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 - -```diff title="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 - -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. - - - - -```diff title="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 -``` - - - - -```diff title="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. - -![Disable Sandboxing](/docs/assets/disable-sandboxing.png) - -Finally, make sure to add the `UIViewControllerBasedStatusBarAppearance` key into your `Info.plist` file, with value of `NO`. - -![Disable UIViewControllerBasedStatusBarAppearance](/docs/assets/disable-UIViewControllerBasedStatusBarAppearance.png) - -## 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: - -```js -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.78-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: - -```sh -echo {} > .watchmanconfig -``` - -Once you have the configurations file in place, you can run the bundler. Run the following command in the root directory of your project: - - - - -```shell -npm start -``` - - - - -```shell -yarn start -``` - - - - -Now build and run your iOS 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 Xcode - -You can use Xcode to create your release builds too! The only additional step is to add a script that is executed when the app is built to package your JS and images into the iOS application. - -1. In Xcode, select your application -2. Click on `Build Phases` -3. Click on the `+` in the top left corner and select `New Run Script Phase` -4. Click on the `Run Script` line and rename the Script to `Bundle React Native code and images` -5. Paste in the text box the following script - -```sh title="Build React Native code and image" -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 - -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. - -Open the `App.tsx` file and add the following code: - -```diff title="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 ( - - - -
-- -- Step One -- -- Edit App.tsx to -- change this screen and see your edits. -- -- See your changes -- -- Debug -- -+ UserID: {props.userID} -+ Token: {props.token} - - - - ); -} - -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. - - - - -Modify the `ReactViewController.mm` to pass the initial properties to JavaScript. - -```diff title="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. - -```diff title="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? - -At this point you can continue developing your app as usual. Refer to our [debugging](debugging) and [deployment](running-on-device) docs to learn more about working with React Native. +import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import constants from '@site/core/TabsConstants'; + +## Key Concepts + +The keys to integrating React Native components into your iOS application are to: + +1. Set up the correct directory structure. +2. Install the necessary NPM dependencies. +3. Adding React Native to your Podfile configuration. +4. Writing the TypeScript code for your first React Native screen. +5. Integrate React Native with your iOS code using a `RCTRootView`. +6. Testing your integration by running the bundler and seeing your app in action. + +## Using the Community Template + +While you follow this guide, we suggest you to use the [React Native Community Template](https://github.com/react-native-community/template/) as reference. The template contains a **minimal iOS app** and will help you understanding how to integrate React Native into an existing iOS app. + +## Prerequisites + +Follow the guide on [setting up your development environment](set-up-your-environment) and using [React Native without a framework](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 + +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 + +Go to the root directory and run the following command: + +```shell +curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-stable/template/package.json +``` + +This will copy the `package.json` [file from the Community template](https://github.com/react-native-community/template/blob/0.78-stable/template/package.json) to your project. + +Next, install the NPM packages by running: + + + + +```shell +npm install +``` + + + + +```shell +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.78-stable/template/_gitignore)). + +### 3. Install Development tools + +### 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. + +![Xcode Command Line Tools](/docs/assets/GettingStartedXcodeCommandLineTools.png) + +### 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/): + +```shell +brew install cocoapods +``` + +## 4. Adding React Native to your app + +### Configuring CocoaPods + +To configure CocoaPods, we need two files: + +- A **Gemfile** that defines which Ruby dependencies we need. +- A **Podfile** that defines how to properly install our dependencies. + +For the **Gemfile**, go to the root directory of your project and run this command + +```sh +curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-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 + +```sh +curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.78-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.78-stable/template/Gemfile) and for the [Podfile](https://github.com/react-native-community/template/blob/0.78-stable/template/ios/Podfile). + +:::note +Remember to change [this line](https://github.com/react-native-community/template/blob/0.78-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: + +```sh +bundle install +bundle exec pod install +``` + +The first command will install the Ruby dependencies and the second command will actually integrate the React Native code in your application so that your iOS files can import the React Native headers. + +## 5. Writing the TypeScript Code + +Now we will actually modify the native iOS application to integrate React Native. + +The first bit of code we will write is the actual React Native code for the new screen that will be integrated into our application. + +### Create a `index.js` file + +First, create an empty `index.js` file in the root of your React Native project. + +`index.js` is the starting point for React Native applications, and it is always required. It can be a small file that `import`s other file that are part of your React Native component or application, or it can contain all the code that is needed for it. + +Our `index.js` should look as follows (here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.78-stable/template/index.js)): + +```js +import {AppRegistry} from 'react-native'; +import App from './App'; + +AppRegistry.registerComponent('HelloWorld', () => App); +``` + +### Create a `App.tsx` file + +Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX]() 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.78-stable/template/App.tsx)): + +```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 ( + + + +
+ + Step One + + Edit App.tsx to + change this screen and see your edits. + + See your changes + + Debug + + + + + ); +} + +const styles = StyleSheet.create({ + title: { + fontSize: 24, + fontWeight: '600', + }, + bold: { + fontWeight: '700', + }, +}); + +export default App; +``` + +Here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.78-stable/template/App.tsx) + +## 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 + +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`. + +#### Create the ReactViewController + +Create a new file from template (+N) and choose the Cocoa Touch Class template. + +Make sure to select `UIViewController` as the "Subclass of" field. + + + + +Now open the `ReactViewController.m` file and apply the following changes + +```diff title="ReactViewController.m" +#import "ReactViewController.h" ++#import ++#import ++#import ++#import + + +@interface ReactViewController () + +@end + ++@interface ReactNativeFactoryDelegate: RCTDefaultReactNativeFactoryDelegate ++@end + +-@implementation ReactViewController ++@implementation ReactViewController { ++ RCTReactNativeFactory *_factory; ++ id _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 + +```diff title="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 + +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. + + + + +```diff title="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 +``` + + + + +```diff title="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. + +![Disable Sandboxing](/docs/assets/disable-sandboxing.png) + +Finally, make sure to add the `UIViewControllerBasedStatusBarAppearance` key into your `Info.plist` file, with value of `NO`. + +![Disable UIViewControllerBasedStatusBarAppearance](/docs/assets/disable-UIViewControllerBasedStatusBarAppearance.png) + +## 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: + +```js +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.78-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: + +```sh +echo {} > .watchmanconfig +``` + +Once you have the configurations file in place, you can run the bundler. Run the following command in the root directory of your project: + + + + +```shell +npm start +``` + + + + +```shell +yarn start +``` + + + + +Now build and run your iOS 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 Xcode + +You can use Xcode to create your release builds too! The only additional step is to add a script that is executed when the app is built to package your JS and images into the iOS application. + +1. In Xcode, select your application +2. Click on `Build Phases` +3. Click on the `+` in the top left corner and select `New Run Script Phase` +4. Click on the `Run Script` line and rename the Script to `Bundle React Native code and images` +5. Paste in the text box the following script + +```sh title="Build React Native code and image" +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 + +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. + +Open the `App.tsx` file and add the following code: + +```diff title="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 ( + + + +
+- +- Step One +- +- Edit App.tsx to +- change this screen and see your edits. +- +- See your changes +- +- Debug +- ++ UserID: {props.userID} ++ Token: {props.token} + + + + ); +} + +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. + + + + +Modify the `ReactViewController.mm` to pass the initial properties to JavaScript. + +```diff title="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. + +```diff title="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? + +At this point you can continue developing your app as usual. Refer to our [debugging](debugging) and [deployment](running-on-device) docs to learn more about working with React Native. diff --git a/website/versioned_docs/version-0.80/_integration-with-existing-apps-kotlin.md b/website/versioned_docs/version-0.80/_integration-with-existing-apps-kotlin.md index 72f8337f33f..586d6c4054c 100644 --- a/website/versioned_docs/version-0.80/_integration-with-existing-apps-kotlin.md +++ b/website/versioned_docs/version-0.80/_integration-with-existing-apps-kotlin.md @@ -1,506 +1,505 @@ -import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import constants from '@site/core/TabsConstants'; - -## Key Concepts - -The keys to integrating React Native components into your Android application are to: - -1. Set up the correct directory structure. -2. Install the necessary NPM dependencies. -3. Adding React Native to your Gradle configuration. -4. Writing the TypeScript code for your first React Native screen. -5. Integrate React Native with your Android code using a ReactActivity. -6. Testing your integration by running the bundler and seeing your app in action. - -## Using the Community Template - -While you follow this guide, we suggest you to use the [React Native Community Template](https://github.com/react-native-community/template/) as reference. The template contains a **minimal Android app** and will help you understanding how to integrate React Native into an existing Android app. - -## Prerequisites - -Follow the guide on [setting up your development environment](set-up-your-environment) and using [React Native without a framework](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 - -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 - -Go to the root directory and run the following command: - -```shell -curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.75-stable/template/package.json -``` - -This will copy the `package.json` [file from the Community template](https://github.com/react-native-community/template/blob/0.75-stable/template/package.json) to your project. - -Next, install the NPM packages by running: - - - - -```shell -npm install -``` - - - - -```shell -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.75-stable/template/_gitignore)). - -## 3. Adding React Native to your app - -### 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.77-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 { 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.77-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.77-stable/template/android/app/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.77-stable/template/android/gradle.properties)): - -```diff -+reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 -+newArchEnabled=true -+hermesEnabled=true -``` - -### Configuring your manifest - -First, make sure you have the Internet permission in your `AndroidManifest.xml`: - -```diff - - -+ - - - - -``` - -Then you need to enable [cleartext traffic](https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted) in your **debug** `AndroidManifest.xml`: - -```diff - - - - - -``` - -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.77-stable/template/android/app/src/main/AndroidManifest.xml) and [debug](https://github.com/react-native-community/template/blob/0.77-stable/template/android/app/src/debug/AndroidManifest.xml) - -This is needed as your application will communicate with your local bundler, [Metro](https://metrobundler.dev/), via HTTP. - -Make sure you add this only to your **debug** manifest. - -## 4. Writing the TypeScript Code - -Now we will actually modify the native Android application to integrate React Native. - -The first bit of code we will write is the actual React Native code for the new screen that will be integrated into our application. - -### Create a `index.js` file - -First, create an empty `index.js` file in the root of your React Native project. - -`index.js` is the starting point for React Native applications, and it is always required. It can be a small file that `import`s other file that are part of your React Native component or application, or it can contain all the code that is needed for it. - -Our index.js should look as follows (here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.77-stable/template/index.js)): - -```js -import {AppRegistry} from 'react-native'; -import App from './App'; - -AppRegistry.registerComponent('HelloWorld', () => App); -``` - -### Create a `App.tsx` file - -Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX]() 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.77-stable/template/App.tsx)): - -```tsx -import React 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(): React.JSX.Element { - const isDarkMode = useColorScheme() === 'dark'; - - const backgroundStyle = { - backgroundColor: isDarkMode ? Colors.darker : Colors.lighter, - }; - - return ( - - - -
- - Step One - - Edit App.tsx to - change this screen and see your edits. - - See your changes - - Debug - - - - - ); -} - -const styles = StyleSheet.create({ - title: { - fontSize: 24, - fontWeight: '600', - }, - bold: { - fontWeight: '700', - }, -}); - -export default App; -``` - -Here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.77-stable/template/App.tsx) - -## 5. Integrating with your Android 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. - -### Updating your Application class - -First, we need to update your `Application` class to properly initialize React Native as follows: - - - - - -```diff -package ; - -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 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 - -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 = 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.77-stable/template/android/app/src/main/java/com/helloworld/MainApplication.kt) - -#### 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 -// package ; - -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 - -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.77-stable/template/android/app/src/main/java/com/helloworld/MainApplication.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 - - - - - - -+ -+ - - -``` - -Now your activity is ready to run some JavaScript code. - -## 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: - -```js -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.77-stable/template/metro.config.js) from the Community template file as reference. - -Once you have the config file in place, you can run the bundler. Run the following command in the root directory of your project: - - - - -```shell -npm start -``` - - - - -```shell -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 - -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? - -At this point you can continue developing your app as usual. Refer to our [debugging](debugging) and [deployment](running-on-device) docs to learn more about working with React Native. +import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import constants from '@site/core/TabsConstants'; + +## Key Concepts + +The keys to integrating React Native components into your Android application are to: + +1. Set up the correct directory structure. +2. Install the necessary NPM dependencies. +3. Adding React Native to your Gradle configuration. +4. Writing the TypeScript code for your first React Native screen. +5. Integrate React Native with your Android code using a ReactActivity. +6. Testing your integration by running the bundler and seeing your app in action. + +## Using the Community Template + +While you follow this guide, we suggest you to use the [React Native Community Template](https://github.com/react-native-community/template/) as reference. The template contains a **minimal Android app** and will help you understanding how to integrate React Native into an existing Android app. + +## Prerequisites + +Follow the guide on [setting up your development environment](set-up-your-environment) and using [React Native without a framework](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 + +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 + +Go to the root directory and run the following command: + +```shell +curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.75-stable/template/package.json +``` + +This will copy the `package.json` [file from the Community template](https://github.com/react-native-community/template/blob/0.75-stable/template/package.json) to your project. + +Next, install the NPM packages by running: + + + + +```shell +npm install +``` + + + + +```shell +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.75-stable/template/_gitignore)). + +## 3. Adding React Native to your app + +### 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.77-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 { 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.77-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.77-stable/template/android/app/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.77-stable/template/android/gradle.properties)): + +```diff ++reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 ++newArchEnabled=true ++hermesEnabled=true +``` + +### Configuring your manifest + +First, make sure you have the Internet permission in your `AndroidManifest.xml`: + +```diff + + ++ + + + + +``` + +Then you need to enable [cleartext traffic](https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted) in your **debug** `AndroidManifest.xml`: + +```diff + + + + + +``` + +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.77-stable/template/android/app/src/main/AndroidManifest.xml) and [debug](https://github.com/react-native-community/template/blob/0.77-stable/template/android/app/src/debug/AndroidManifest.xml) + +This is needed as your application will communicate with your local bundler, [Metro](https://metrobundler.dev/), via HTTP. + +Make sure you add this only to your **debug** manifest. + +## 4. Writing the TypeScript Code + +Now we will actually modify the native Android application to integrate React Native. + +The first bit of code we will write is the actual React Native code for the new screen that will be integrated into our application. + +### Create a `index.js` file + +First, create an empty `index.js` file in the root of your React Native project. + +`index.js` is the starting point for React Native applications, and it is always required. It can be a small file that `import`s other file that are part of your React Native component or application, or it can contain all the code that is needed for it. + +Our index.js should look as follows (here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.77-stable/template/index.js)): + +```js +import {AppRegistry} from 'react-native'; +import App from './App'; + +AppRegistry.registerComponent('HelloWorld', () => App); +``` + +### Create a `App.tsx` file + +Let's create an `App.tsx` file. This is a [TypeScript](https://www.typescriptlang.org/) file that can have [JSX]() 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.77-stable/template/App.tsx)): + +```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 ( + + + +
+ + Step One + + Edit App.tsx to + change this screen and see your edits. + + See your changes + + Debug + + + + + ); +} + +const styles = StyleSheet.create({ + title: { + fontSize: 24, + fontWeight: '600', + }, + bold: { + fontWeight: '700', + }, +}); + +export default App; +``` + +Here the [Community template file as reference](https://github.com/react-native-community/template/blob/0.77-stable/template/App.tsx) + +## 5. Integrating with your Android 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. + +### Updating your Application class + +First, we need to update your `Application` class to properly initialize React Native as follows: + + + + + +```diff +package ; + +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 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 + +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 = 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.77-stable/template/android/app/src/main/java/com/helloworld/MainApplication.kt) + +#### 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 +// package ; + +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 + +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.77-stable/template/android/app/src/main/java/com/helloworld/MainApplication.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 + + + + + + ++ ++ + + +``` + +Now your activity is ready to run some JavaScript code. + +## 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: + +```js +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.77-stable/template/metro.config.js) from the Community template file as reference. + +Once you have the config file in place, you can run the bundler. Run the following command in the root directory of your project: + + + + +```shell +npm start +``` + + + + +```shell +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 + +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? + +At this point you can continue developing your app as usual. Refer to our [debugging](debugging) and [deployment](running-on-device) docs to learn more about working with React Native. diff --git a/website/versioned_docs/version-0.80/_turbo-native-modules-components.jsx b/website/versioned_docs/version-0.80/_turbo-native-modules-components.jsx index 1bb5a1b5edb..9b17f011728 100644 --- a/website/versioned_docs/version-0.80/_turbo-native-modules-components.jsx +++ b/website/versioned_docs/version-0.80/_turbo-native-modules-components.jsx @@ -1,4 +1,3 @@ -import React from 'react'; import IOSContent from './turbo-native-modules-ios.md'; import AndroidContent from './turbo-native-modules-android.md'; diff --git a/website/versioned_docs/version-0.80/accessibilityinfo.md b/website/versioned_docs/version-0.80/accessibilityinfo.md index fab883898c3..c42fda62a2c 100644 --- a/website/versioned_docs/version-0.80/accessibilityinfo.md +++ b/website/versioned_docs/version-0.80/accessibilityinfo.md @@ -1,290 +1,290 @@ ---- -id: accessibilityinfo -title: AccessibilityInfo ---- - -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 - -```SnackPlayer name=AccessibilityInfo%20Example&supportedPlatforms=android,ios -import React, {useState, useEffect} from 'react'; -import {AccessibilityInfo, Text, StyleSheet} from 'react-native'; -import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; - -const App = () => { - const [reduceMotionEnabled, setReduceMotionEnabled] = useState(false); - const [screenReaderEnabled, setScreenReaderEnabled] = useState(false); - - useEffect(() => { - const reduceMotionChangedSubscription = AccessibilityInfo.addEventListener( - 'reduceMotionChanged', - isReduceMotionEnabled => { - setReduceMotionEnabled(isReduceMotionEnabled); - }, - ); - const screenReaderChangedSubscription = AccessibilityInfo.addEventListener( - 'screenReaderChanged', - isScreenReaderEnabled => { - setScreenReaderEnabled(isScreenReaderEnabled); - }, - ); - - AccessibilityInfo.isReduceMotionEnabled().then(isReduceMotionEnabled => { - setReduceMotionEnabled(isReduceMotionEnabled); - }); - AccessibilityInfo.isScreenReaderEnabled().then(isScreenReaderEnabled => { - setScreenReaderEnabled(isScreenReaderEnabled); - }); - - return () => { - reduceMotionChangedSubscription.remove(); - screenReaderChangedSubscription.remove(); - }; - }, []); - - return ( - - - - The reduce motion is {reduceMotionEnabled ? 'enabled' : 'disabled'}. - - - The screen reader is {screenReaderEnabled ? 'enabled' : 'disabled'}. - - - - ); -}; - -const styles = StyleSheet.create({ - container: { - flex: 1, - alignItems: 'center', - justifyContent: 'center', - }, - status: { - margin: 30, - }, -}); - -export default App; -``` - ---- - -# Reference - -## Methods - -### `addEventListener()` - -```tsx -static addEventListener( - eventName: AccessibilityChangeEventName | AccessibilityAnnouncementEventName, - handler: ( - event: AccessibilityChangeEvent | AccessibilityAnnouncementFinishedEvent, - ) => void, -): EmitterSubscription; -``` - -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()` - -```tsx -static announceForAccessibility(announcement: string); -``` - -Post a string to be announced by the screen reader. - ---- - -### `announceForAccessibilityWithOptions()` - -```tsx -static announceForAccessibilityWithOptions( - announcement: string, - options: {queue?: boolean}, -); -``` - -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. - -**Parameters:** - -| Name | Type | Description | -| ----------------------------------------------------------------- | ------ | -------------------------------------------------------------------------------------------- | -| announcement
Required
| string | The string to be announced | -| options
Required
| object | `queue` - queue the announcement behind existing speech
iOS
| - ---- - -### `getRecommendedTimeoutMillis()`
Android
- -```tsx -static getRecommendedTimeoutMillis(originalTimeout: number): Promise; -``` - -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 | -| -------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------------- | -| originalTimeout
Required
| number | The timeout to return if "Accessibility timeout" is not set. Specify in milliseconds. | - ---- - -### `isAccessibilityServiceEnabled()`
Android
- -```tsx -static isAccessibilityServiceEnabled(): Promise; -``` - -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
- -```tsx -static isBoldTextEnabled(): Promise: -``` - -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
- -```tsx -static isGrayscaleEnabled(): Promise; -``` - -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
- -```tsx -static isInvertColorsEnabled(): Promise; -``` - -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()` - -```tsx -static isReduceMotionEnabled(): Promise; -``` - -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
- -```tsx -static isReduceTransparencyEnabled(): Promise; -``` - -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()` - -```tsx -static isScreenReaderEnabled(): Promise; -``` - -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
- -```tsx -static isHighTextContrastEnabled(): Promise -``` - -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
- -```tsx -static isDarkerSystemColorsEnabled(): Promise -``` - -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
- -```tsx -static prefersCrossFadeTransitions(): Promise; -``` - -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()` - -:::warning[Deprecated] -Prefer using `sendAccessibilityEvent` with eventType `focus` instead. -::: - -```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()` - -```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 | -| -------------------------------------------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| host
Required
| HostInstance | The component ref to send the event to. | -| eventType
Required
| AccessibilityEventTypes | One of `'click'` (Android only), `'focus'`, `'viewHoverEnter'` (Android only), or `'windowStateChange'` (Android only) | +--- +id: accessibilityinfo +title: AccessibilityInfo +--- + +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 + +```SnackPlayer name=AccessibilityInfo%20Example&supportedPlatforms=android,ios +import {useState, useEffect} from 'react'; +import {AccessibilityInfo, Text, StyleSheet} from 'react-native'; +import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; + +const App = () => { + const [reduceMotionEnabled, setReduceMotionEnabled] = useState(false); + const [screenReaderEnabled, setScreenReaderEnabled] = useState(false); + + useEffect(() => { + const reduceMotionChangedSubscription = AccessibilityInfo.addEventListener( + 'reduceMotionChanged', + isReduceMotionEnabled => { + setReduceMotionEnabled(isReduceMotionEnabled); + }, + ); + const screenReaderChangedSubscription = AccessibilityInfo.addEventListener( + 'screenReaderChanged', + isScreenReaderEnabled => { + setScreenReaderEnabled(isScreenReaderEnabled); + }, + ); + + AccessibilityInfo.isReduceMotionEnabled().then(isReduceMotionEnabled => { + setReduceMotionEnabled(isReduceMotionEnabled); + }); + AccessibilityInfo.isScreenReaderEnabled().then(isScreenReaderEnabled => { + setScreenReaderEnabled(isScreenReaderEnabled); + }); + + return () => { + reduceMotionChangedSubscription.remove(); + screenReaderChangedSubscription.remove(); + }; + }, []); + + return ( + + + + The reduce motion is {reduceMotionEnabled ? 'enabled' : 'disabled'}. + + + The screen reader is {screenReaderEnabled ? 'enabled' : 'disabled'}. + + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + }, + status: { + margin: 30, + }, +}); + +export default App; +``` + +--- + +# Reference + +## Methods + +### `addEventListener()` + +```tsx +static addEventListener( + eventName: AccessibilityChangeEventName | AccessibilityAnnouncementEventName, + handler: ( + event: AccessibilityChangeEvent | AccessibilityAnnouncementFinishedEvent, + ) => void, +): EmitterSubscription; +``` + +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()` + +```tsx +static announceForAccessibility(announcement: string); +``` + +Post a string to be announced by the screen reader. + +--- + +### `announceForAccessibilityWithOptions()` + +```tsx +static announceForAccessibilityWithOptions( + announcement: string, + options: {queue?: boolean}, +); +``` + +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. + +**Parameters:** + +| Name | Type | Description | +| ----------------------------------------------------------------- | ------ | -------------------------------------------------------------------------------------------- | +| announcement
Required
| string | The string to be announced | +| options
Required
| object | `queue` - queue the announcement behind existing speech
iOS
| + +--- + +### `getRecommendedTimeoutMillis()`
Android
+ +```tsx +static getRecommendedTimeoutMillis(originalTimeout: number): Promise; +``` + +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 | +| -------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------------- | +| originalTimeout
Required
| number | The timeout to return if "Accessibility timeout" is not set. Specify in milliseconds. | + +--- + +### `isAccessibilityServiceEnabled()`
Android
+ +```tsx +static isAccessibilityServiceEnabled(): Promise; +``` + +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
+ +```tsx +static isBoldTextEnabled(): Promise: +``` + +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
+ +```tsx +static isGrayscaleEnabled(): Promise; +``` + +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
+ +```tsx +static isInvertColorsEnabled(): Promise; +``` + +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()` + +```tsx +static isReduceMotionEnabled(): Promise; +``` + +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
+ +```tsx +static isReduceTransparencyEnabled(): Promise; +``` + +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()` + +```tsx +static isScreenReaderEnabled(): Promise; +``` + +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
+ +```tsx +static isHighTextContrastEnabled(): Promise +``` + +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
+ +```tsx +static isDarkerSystemColorsEnabled(): Promise +``` + +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
+ +```tsx +static prefersCrossFadeTransitions(): Promise; +``` + +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()` + +:::warning[Deprecated] +Prefer using `sendAccessibilityEvent` with eventType `focus` instead. +::: + +```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()` + +```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 | +| -------------------------------------------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| host
Required
| HostInstance | The component ref to send the event to. | +| eventType
Required
| AccessibilityEventTypes | One of `'click'` (Android only), `'focus'`, `'viewHoverEnter'` (Android only), or `'windowStateChange'` (Android only) | diff --git a/website/versioned_docs/version-0.80/actionsheetios.md b/website/versioned_docs/version-0.80/actionsheetios.md index 3640d4de160..ef129850796 100644 --- a/website/versioned_docs/version-0.80/actionsheetios.md +++ b/website/versioned_docs/version-0.80/actionsheetios.md @@ -1,142 +1,142 @@ ---- -id: actionsheetios -title: ActionSheetIOS ---- - -Displays native to iOS [Action Sheet](https://developer.apple.com/design/human-interface-guidelines/action-sheets) component. - -## Example - -```SnackPlayer name=ActionSheetIOS%20Example&supportedPlatforms=ios -import React, {useState} from 'react'; -import {ActionSheetIOS, Button, StyleSheet, Text} from 'react-native'; -import {SafeAreaView, SafeAreaProvider} from 'react-native-safe-area-context'; - -const App = () => { - const [result, setResult] = useState('🔮'); - - const onPress = () => - ActionSheetIOS.showActionSheetWithOptions( - { - options: ['Cancel', 'Generate number', 'Reset'], - destructiveButtonIndex: 2, - cancelButtonIndex: 0, - userInterfaceStyle: 'dark', - }, - buttonIndex => { - if (buttonIndex === 0) { - // cancel action - } else if (buttonIndex === 1) { - setResult(String(Math.floor(Math.random() * 100) + 1)); - } else if (buttonIndex === 2) { - setResult('🔮'); - } - }, - ); - - return ( - - - {result} -