From 4cd3a37a889aee6fcd039755cbbd65218b389639 Mon Sep 17 00:00:00 2001 From: Fabrizio Cucci Date: Thu, 11 Jun 2026 17:11:28 +0100 Subject: [PATCH 1/3] [docs] Cut branch 0.86 --- .../_integration-with-existing-apps-ios.md | 1310 ++-- .../_integration-with-existing-apps-kotlin.md | 1020 +-- .../version-0.86/accessibility.md | 6 +- .../version-0.86/accessibilityinfo.md | 584 +- .../version-0.86/actionsheetios.md | 288 +- .../version-0.86/animatedvaluexy.md | 454 +- .../versioned_docs/version-0.86/animations.md | 1344 ++-- .../versioned_docs/version-0.86/appearance.md | 12 +- .../versioned_docs/version-0.86/appstate.md | 244 +- .../version-0.86/backhandler.md | 272 +- .../versioned_docs/version-0.86/dimensions.md | 308 +- .../version-0.86/document-nodes.md | 150 +- .../version-0.86/drawerlayoutandroid.md | 646 +- website/versioned_docs/version-0.86/easing.md | 1136 ++-- .../version-0.86/element-nodes.md | 270 +- .../versioned_docs/version-0.86/flatlist.md | 1718 ++--- .../versioned_docs/version-0.86/flexbox.md | 5766 ++++++++--------- .../version-0.86/handling-text-input.md | 96 +- .../version-0.86/i18nmanager.md | 336 +- .../version-0.86/improvingux.md | 1188 ++-- .../version-0.86/inputaccessoryview.md | 196 +- .../version-0.86/interactionmanager.md | 844 +-- .../version-0.86/javascript-environment.md | 218 +- .../versioned_docs/version-0.86/keyboard.md | 292 +- .../version-0.86/layout-props.md | 2720 ++++---- .../version-0.86/layoutanimation.md | 716 +- .../legacy/direct-manipulation.md | 880 +-- .../legacy/native-components-android.md | 1746 ++--- .../versioned_docs/version-0.86/linking.md | 1376 ++-- website/versioned_docs/version-0.86/modal.md | 552 +- .../versioned_docs/version-0.86/network.md | 572 +- .../optimizing-flatlist-configuration.md | 308 +- .../version-0.86/panresponder.md | 354 +- .../versioned_docs/version-0.86/pressable.md | 537 +- .../version-0.86/refreshcontrol.md | 334 +- .../versioned_docs/version-0.86/settings.md | 206 +- .../version-0.86/shadow-props.md | 570 +- website/versioned_docs/version-0.86/state.md | 206 +- .../versioned_docs/version-0.86/statusbar.md | 1026 +-- website/versioned_docs/version-0.86/switch.md | 266 +- .../versioned_docs/version-0.86/text-nodes.md | 172 +- .../version-0.86/text-style-props.md | 1896 +++--- website/versioned_docs/version-0.86/text.md | 1560 ++--- .../versioned_docs/version-0.86/textinput.md | 2292 +++---- .../the-new-architecture/pure-cxx-modules.md | 1006 +-- .../version-0.86/touchablehighlight.md | 430 +- .../version-0.86/touchablenativefeedback.md | 438 +- .../version-0.86/touchableopacity.md | 302 +- .../version-0.86/touchablewithoutfeedback.md | 1062 +-- .../versioned_docs/version-0.86/transforms.md | 796 +-- .../version-0.86/turbo-native-modules.md | 520 +- .../versioned_docs/version-0.86/tutorial.md | 534 +- .../version-0.86/usecolorscheme.md | 1 - .../version-0.86-sidebars.json | 53 +- website/versions.json | 1 + 55 files changed, 21082 insertions(+), 21048 deletions(-) diff --git a/website/versioned_docs/version-0.86/_integration-with-existing-apps-ios.md b/website/versioned_docs/version-0.86/_integration-with-existing-apps-ios.md index f28e3c48bf9..1670717d84f 100644 --- a/website/versioned_docs/version-0.86/_integration-with-existing-apps-ios.md +++ b/website/versioned_docs/version-0.86/_integration-with-existing-apps-ios.md @@ -1,655 +1,655 @@ -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import constants from '@site/core/TabsConstants'; -import CodeBlock from '@theme/CodeBlock'; -import RNTemplateRepoLink from '@site/core/RNTemplateRepoLink'; -import {getTemplateBranchNameForCurrentVersion} from '@site/src/getTemplateBranchNameForCurrentVersion'; - -## 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: - - -{`curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/${getTemplateBranchNameForCurrentVersion()}/template/package.json`} - - -This will copy the `package.json` file from the Community template 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). - -### 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 - - -{`curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/${getTemplateBranchNameForCurrentVersion()}/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 - - -{`curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/${getTemplateBranchNameForCurrentVersion()}/template/ios/Podfile`} - - -Please use the Community Template as a reference point for the Gemfile and for the Podfile. - -:::note -Remember to change this line. -::: - -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): - -```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): - -```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 is the Community template file as reference. - -## 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 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 configuration 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'; +import CodeBlock from '@theme/CodeBlock'; +import RNTemplateRepoLink from '@site/core/RNTemplateRepoLink'; +import {getTemplateBranchNameForCurrentVersion} from '@site/src/getTemplateBranchNameForCurrentVersion'; + +## 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: + + +{`curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/${getTemplateBranchNameForCurrentVersion()}/template/package.json`} + + +This will copy the `package.json` file from the Community template 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). + +### 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 + + +{`curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/${getTemplateBranchNameForCurrentVersion()}/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 + + +{`curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/${getTemplateBranchNameForCurrentVersion()}/template/ios/Podfile`} + + +Please use the Community Template as a reference point for the Gemfile and for the Podfile. + +:::note +Remember to change this line. +::: + +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): + +```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): + +```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 is the Community template file as reference. + +## 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 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 configuration 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.86/_integration-with-existing-apps-kotlin.md b/website/versioned_docs/version-0.86/_integration-with-existing-apps-kotlin.md index c5f7d6bc4a6..6ce02c4133b 100644 --- a/website/versioned_docs/version-0.86/_integration-with-existing-apps-kotlin.md +++ b/website/versioned_docs/version-0.86/_integration-with-existing-apps-kotlin.md @@ -1,510 +1,510 @@ -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import constants from '@site/core/TabsConstants'; -import CodeBlock from '@theme/CodeBlock'; -import RNTemplateRepoLink from '@site/core/RNTemplateRepoLink'; -import {getTemplateBranchNameForCurrentVersion} from '@site/src/getTemplateBranchNameForCurrentVersion'; - -## 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: - - -{`curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/${getTemplateBranchNameForCurrentVersion()}/template/package.json`} - - -This will copy the `package.json` file from the Community template 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). - -## 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): - -```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): - -```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): - -```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): - -```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 and debug. - -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): - -```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): - -```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 is the Community template file as reference. - -## 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. - -#### 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. - -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 from the Community template file as reference. - -Once you have the configuration file in place, you can run the bundler. Run the following command in the root directory of your project: - - - - -```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'; +import CodeBlock from '@theme/CodeBlock'; +import RNTemplateRepoLink from '@site/core/RNTemplateRepoLink'; +import {getTemplateBranchNameForCurrentVersion} from '@site/src/getTemplateBranchNameForCurrentVersion'; + +## 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: + + +{`curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/${getTemplateBranchNameForCurrentVersion()}/template/package.json`} + + +This will copy the `package.json` file from the Community template 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). + +## 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): + +```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): + +```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): + +```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): + +```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 and debug. + +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): + +```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): + +```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 is the Community template file as reference. + +## 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. + +#### 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. + +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 from the Community template file as reference. + +Once you have the configuration file in place, you can run the bundler. Run the following command in the root directory of your project: + + + + +```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.86/accessibility.md b/website/versioned_docs/version-0.86/accessibility.md index e9f305964cc..cf113a900d3 100644 --- a/website/versioned_docs/version-0.86/accessibility.md +++ b/website/versioned_docs/version-0.86/accessibility.md @@ -521,13 +521,13 @@ When adding support for standard actions, `name` must be one of the following: - `'magicTap'` - iOS only - While VoiceOver focus is on or inside the component, the user double tapped with two fingers. - `'escape'` - iOS only - While VoiceOver focus is on or inside the component, the user performed a two-finger scrub gesture (left, right, left). - `'activate'` - Activate the component. This should perform the same action with, or without, assistive technology. Engaged when a screen reader user double taps the component. -- `'increment'` - Increment an adjustable component. On iOS, VoiceOver generates this action when the component has a role of `'adjustable'` and the user places focus on it and swipes upward. On Android, TalkBack generates this action when the user places accessibility focus on the component and presses the volume-up button. -- `'decrement'` - Decrement an adjustable component. On iOS, VoiceOver generates this action when the component has a role of `'adjustable'` and the user places focus on it and swipes downward. On Android, TalkBack generates this action when the user places accessibility focus on the component and presses the volume-down button. +- `'increment'` - Increment an adjustable component. On iOS, VoiceOver generates this action when the component has a role of `'adjustable'` and the user places focus on it and swipes upward. On Android, in TalkBack versions 8.1 and below, this action is generated when the user focuses the component and presses the volume-up button. In TalkBack 9.1 and later, this was replaced by the "Adjust Reading Control" gesture (swiping upward on the focused control). +- `'decrement'` - Decrement an adjustable component. On iOS, VoiceOver generates this action when the component has a role of `'adjustable'` and the user places focus on it and swipes downward. On Android, in TalkBack versions 8.2 and below, this action is generated when the user focuses the component and presses the volume-down button. In TalkBack 9.2 and later, this was replaced by the "Adjust Reading Control" gesture (swiping downward on the focused control). - `'longpress'` - Android only - This action is generated when the user places accessibility focus on the component, then double-taps and holds one finger on the screen. This should perform the same action with, or without, assistive technology. - `'expand'` - Android only - This action "expands" the component so that TalkBack will announce an "expanded" hint. - `'collapse'` - Android only - This action "collapses" the component so that TalkBack will announce a "collapsed" hint. -The `label` field is optional for standard actions and is often unused by assistive technologies. For custom actions, it is a localized string containing a description of the action to be presented to the user. +The `label` field is optional for standard actions and is used by assistive technologies to describe the specific result of an action. For example, TalkBack uses this field to override the default "Double tap to activate" announcement with a custom description like "Double tap to open chat." For custom actions, the `label` is a localized string containing a description of the action to be presented to the user. To handle action requests, a component must implement an `onAccessibilityAction` function. The only argument to this function is an event containing the name of the action to perform. The below example from RNTester shows how to create a component that defines and handles several custom actions. diff --git a/website/versioned_docs/version-0.86/accessibilityinfo.md b/website/versioned_docs/version-0.86/accessibilityinfo.md index c88372497d5..4cebdadb1b3 100644 --- a/website/versioned_docs/version-0.86/accessibilityinfo.md +++ b/website/versioned_docs/version-0.86/accessibilityinfo.md @@ -1,292 +1,292 @@ ---- -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) | +--- +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.86/actionsheetios.md b/website/versioned_docs/version-0.86/actionsheetios.md index dc2269301d2..d4294c35d18 100644 --- a/website/versioned_docs/version-0.86/actionsheetios.md +++ b/website/versioned_docs/version-0.86/actionsheetios.md @@ -1,144 +1,144 @@ ---- -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 {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} - - - ); -}; - - -// CSS -.container { - display: flex; - justify-content: center; - align-items: center; -} - -``` - -```tsx -// React Native Counter Example using Hooks! - -import {useState} from 'react'; -import {View, Text, Button, StyleSheet} from 'react-native'; - -const App = () => { - const [count, setCount] = useState(0); - - return ( - - You clicked {count} times - + + ); +}; + + +// CSS +.container { + display: flex; + justify-content: center; + align-items: center; +} + +``` + +```tsx +// React Native Counter Example using Hooks! + +import {useState} from 'react'; +import {View, Text, Button, StyleSheet} from 'react-native'; + +const App = () => { + const [count, setCount] = useState(0); + + return ( + + You clicked {count} times + - - ); -}; - - -// CSS -.container { - display: flex; - justify-content: center; - align-items: center; -} - -``` - -```tsx -// React Native Counter Example using Hooks! - -import {useState} from 'react'; -import {View, Text, Button, StyleSheet} from 'react-native'; - -const App = () => { - const [count, setCount] = useState(0); - - return ( - - You clicked {count} times - + + ); +}; + + +// CSS +.container { + display: flex; + justify-content: center; + align-items: center; +} + +``` + +```tsx +// React Native Counter Example using Hooks! + +import {useState} from 'react'; +import {View, Text, Button, StyleSheet} from 'react-native'; + +const App = () => { + const [count, setCount] = useState(0); + + return ( + + You clicked {count} times +