diff --git a/.circleci/config.yml b/.circleci/config.yml index ae294ea2e20..52c5678d300 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -25,6 +25,7 @@ commands: - run: name: Yarn Install command: yarn install --no-progress --non-interactive --cache-folder ~/.cache/yarn + working_directory: ~/react-native-website - save_cache: paths: - node_modules diff --git a/.gitignore b/.gitignore index 6e85513bdcb..45da9c7e3e9 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ cnwebsite/scripts/sync-api-docs/generatedComponentApiDocs.js cnwebsite/scripts/sync-api-docs/extracted.json sync-api-docs/generatedComponentApiDocs.js sync-api-docs/extracted.json + +scripts/lint-examples/out/ + diff --git a/.prettierrc b/.prettierrc index 43f7d62dd47..11998292dbf 100644 --- a/.prettierrc +++ b/.prettierrc @@ -15,13 +15,13 @@ { "files": "*.md", "options": { - "arrowParens": "always", - "bracketSpacing": true, + "arrowParens": "avoid", + "bracketSpacing": false, "bracketSameLine": true, "printWidth": 66, "proseWrap": "preserve", "singleQuote": true, - "trailingComma": "none", + "trailingComma": "all", "endOfLine": "auto" } }, diff --git a/README.md b/README.md index 9dd7e5d7d4e..043f068b37f 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ If you are looking for the source code of the [React Native Archive website](htt ## 📖 Overview If you would like to **_contribute an edit or addition to the docs,_** read through our [style guide](STYLEGUIDE.md) before you write anything. -Almost all our content is generated from markdown files you can find in the `docs`, `website/architecure` and `website/contibuting` directories. +Almost all our content is generated from markdown files you can find in the `docs`, `website/architecture` and `website/contributing` directories. **_To edit the internals of how the site is built,_** you may want to get familiarized with how the site is built. The React Native website is a static site generated using [Docusaurus](https://docusaurus.io/). The website configuration can be found in the `website` directory. Visit the Docusaurus website to learn more about all the available configuration options. @@ -109,7 +109,7 @@ As mentioned above, the `docs` folder contains the source files for docs from "G The doc files for the "Architecture" and "Contribution" tabs are located inside `website` in the respective directories (unversioned/static docs). In most cases, you will only want to edit the files within those directories. -If you're adding a new doc or you need to alter the order the docs appear in the sidebar, take a look at the `sidebars.json`, `sidebarsArchitecture.json` and `sidebarsContributing.json` files in the `website` directory. The sidebar files contains a list of document ids that should match those defined in the header metadata (aka frontmatter) of the docs markdown files. +If you're adding a new doc or you need to alter the order the docs appear in the sidebar, take a look at the `sidebars.json`, `sidebarsArchitecture.json` and `sidebarsContributing.json` files in the `website` directory. The sidebar files contain a list of document ids that should match those defined in the header metadata (aka frontmatter) of the docs markdown files. ### Versioned docs @@ -117,7 +117,7 @@ Part of the React Native website is versioned to allow users to go back and see > **_Note:_** Do not edit the auto-generated files within `versioned_docs` or `versioned_sidebars` unless you are sure it is necessary. Edits made to older versions will not be propagated to newer versions of the versioned docs. -Docusaurus keeps track of the list of versions for the site in the `website/versions.json` file. The ordering of the versions in this file should be in reverse chronological order. +Docusaurus keeps track of the list of versions for the site in the `website/versions.json` file. The ordering of versions in this file should be in reverse chronological order. #### Cutting a new version diff --git a/docs/_getting-started-linux-android.md b/docs/_getting-started-linux-android.md index 839c6882c65..1c10384763b 100644 --- a/docs/_getting-started-linux-android.md +++ b/docs/_getting-started-linux-android.md @@ -49,21 +49,21 @@ Next, select the "SDK Tools" tab and check the box next to "Show Package Details Finally, click "Apply" to download and install the Android SDK and related build tools. -

3. Configure the ANDROID_SDK_ROOT environment variable

+

3. Configure the ANDROID_HOME environment variable

The React Native tools require some environment variables to be set up in order to build apps with native code. Add the following lines to your `$HOME/.bash_profile` or `$HOME/.bashrc` (if you are using `zsh` then `~/.zprofile` or `~/.zshrc`) config file: ```shell -export ANDROID_SDK_ROOT=$HOME/Library/Android/Sdk -export PATH=$PATH:$ANDROID_SDK_ROOT/emulator -export PATH=$PATH:$ANDROID_SDK_ROOT/platform-tools +export ANDROID_HOME=$HOME/Android/Sdk +export PATH=$PATH:$ANDROID_HOME/emulator +export PATH=$PATH:$ANDROID_HOME/platform-tools ``` > `.bash_profile` is specific to `bash`. If you're using another shell, you will need to edit the appropriate shell-specific config file. -Type `source $HOME/.bash_profile` for `bash` or `source $HOME/.zprofile` to load the config into your current shell. Verify that ANDROID_SDK_ROOT has been set by running `echo $ANDROID_SDK_ROOT` and the appropriate directories have been added to your path by running `echo $PATH`. +Type `source $HOME/.bash_profile` for `bash` or `source $HOME/.zprofile` to load the config into your current shell. Verify that ANDROID_HOME has been set by running `echo $ANDROID_HOME` and the appropriate directories have been added to your path by running `echo $PATH`. > Please make sure you use the correct Android SDK path. You can find the actual location of the SDK in the Android Studio "Preferences" dialog, under **Appearance & Behavior** → **System Settings** → **Android SDK**. @@ -97,11 +97,7 @@ If you want to start a new project with a specific React Native version, you can npx react-native init AwesomeProject --version X.XX.X ``` -You can also start a project with a custom React Native template, like TypeScript, with `--template` argument: - -```shell -npx react-native init AwesomeTSProject --template react-native-template-typescript -``` +You can also start a project with a custom React Native template with the `--template` argument.

Preparing the Android device

diff --git a/docs/_getting-started-macos-android.md b/docs/_getting-started-macos-android.md index eada9f7e420..9e1d1e3022a 100644 --- a/docs/_getting-started-macos-android.md +++ b/docs/_getting-started-macos-android.md @@ -69,19 +69,19 @@ Next, select the "SDK Tools" tab and check the box next to "Show Package Details Finally, click "Apply" to download and install the Android SDK and related build tools. -

3. Configure the ANDROID_SDK_ROOT environment variable

+

3. Configure the ANDROID_HOME environment variable

The React Native tools require some environment variables to be set up in order to build apps with native code. Add the following lines to your `~/.zprofile` or `~/.zshrc` (if you are using `bash`, then `~/.bash_profile` or `~/.bashrc`) config file: ```shell -export ANDROID_SDK_ROOT=$HOME/Library/Android/sdk -export PATH=$PATH:$ANDROID_SDK_ROOT/emulator -export PATH=$PATH:$ANDROID_SDK_ROOT/platform-tools +export ANDROID_HOME=$HOME/Library/Android/sdk +export PATH=$PATH:$ANDROID_HOME/emulator +export PATH=$PATH:$ANDROID_HOME/platform-tools ``` -Run `source ~/.zprofile` (or `source ~/.bash_profile` for `bash`) to load the config into your current shell. Verify that ANDROID_SDK_ROOT has been set by running `echo $ANDROID_SDK_ROOT` and the appropriate directories have been added to your path by running `echo $PATH`. +Run `source ~/.zprofile` (or `source ~/.bash_profile` for `bash`) to load the config into your current shell. Verify that ANDROID_HOME has been set by running `echo $ANDROID_HOME` and the appropriate directories have been added to your path by running `echo $PATH`. > Please make sure you use the correct Android SDK path. You can find the actual location of the SDK in the Android Studio "Preferences" dialog, under **Appearance & Behavior** → **System Settings** → **Android SDK**. @@ -109,11 +109,7 @@ If you want to start a new project with a specific React Native version, you can npx react-native init AwesomeProject --version X.XX.X ``` -You can also start a project with a custom React Native template, like TypeScript, with `--template` argument: - -```shell -npx react-native init AwesomeTSProject --template react-native-template-typescript -``` +You can also start a project with a custom React Native template with the `--template` argument.

Preparing the Android device

diff --git a/docs/_getting-started-macos-ios.md b/docs/_getting-started-macos-ios.md index 7359e734983..93a316dce4f 100644 --- a/docs/_getting-started-macos-ios.md +++ b/docs/_getting-started-macos-ios.md @@ -1,4 +1,4 @@ -import M1Cocoapods from './\_markdown-m1-cocoapods.mdx'; import RemoveGlobalCLI from './\_remove-global-cli.md'; +import RemoveGlobalCLI from './\_remove-global-cli.md'; ## Installing dependencies @@ -70,8 +70,6 @@ To install a simulator, open Xcode > Preferences... and select For more information, please visit [CocoaPods Getting Started guide](https://guides.cocoapods.org/using/getting-started.html). - - ### React Native Command Line Interface React Native has a built-in command line interface. Rather than install and manage a specific version of the CLI globally, we recommend you access the current version at runtime using `npx`, which ships with Node.js. With `npx react-native `, the current stable version of the CLI will be downloaded and executed at the time the command is run. @@ -107,11 +105,7 @@ If you want to start a new project with a specific React Native version, you can npx react-native init AwesomeProject --version X.XX.X ``` -You can also start a project with a custom React Native template, like TypeScript, with `--template` argument: - -```shell -npx react-native init AwesomeTSProject --template react-native-template-typescript -``` +You can also start a project with a custom React Native template with the `--template` argument. > **Note** If the above command is failing, you may have old version of `react-native` or `react-native-cli` installed globally on your pc. Try uninstalling the cli and run the cli using `npx`. diff --git a/docs/_getting-started-windows-android.md b/docs/_getting-started-windows-android.md index 1ae3a3c9c21..230190b7a62 100644 --- a/docs/_getting-started-windows-android.md +++ b/docs/_getting-started-windows-android.md @@ -128,11 +128,7 @@ If you want to start a new project with a specific React Native version, you can npx react-native init AwesomeProject --version X.XX.X ``` -You can also start a project with a custom React Native template, like TypeScript, with `--template` argument: - -```shell -npx react-native init AwesomeTSProject --template react-native-template-typescript -``` +You can also start a project with a custom React Native template with the `--template` argument.

Preparing the Android device

diff --git a/docs/_integration-with-exisiting-apps-java.md b/docs/_integration-with-exisiting-apps-java.md index f090f7083be..2e5b61eefb5 100644 --- a/docs/_integration-with-exisiting-apps-java.md +++ b/docs/_integration-with-exisiting-apps-java.md @@ -41,7 +41,7 @@ $ yarn add react-native This will print a message similar to the following (scroll up in the yarn output to see it): -> warning "react-native@0.52.2" has unmet peer dependency "react@16.2.0". +> warning "react-native@0.70.5" has unmet peer dependency "react@18.1.0" This is OK, it means we also need to install React: @@ -55,41 +55,54 @@ Add `node_modules/` to your `.gitignore` file. ## Adding React Native to your app -### Configuring maven +### Configuring Gradle -Add the React Native and JSC dependency to your app's `build.gradle` file: +React Native uses the React Native Gradle Plugin to configure your dependencies and project setup. -```gradle -dependencies { - implementation "com.android.support:appcompat-v7:27.1.1" - ... - implementation "com.facebook.react:react-native:+" // From node_modules - implementation "org.webkit:android-jsc:+" -} -``` +First, let's edit your `settings.gradle` file by adding this line: -> If you want to ensure that you are always using a specific React Native version in your native build, replace `+` with an actual React Native version you've downloaded from `npm`. +```groovy +includeBuild('../node_modules/react-native-gradle-plugin') +``` -Add an entry for the local React Native and JSC maven directories to the top-level `build.gradle`. Be sure to add it to the “allprojects” block, above other maven repositories: +Then you need to open your top level `build.gradle` and include this line: -```gradle -allprojects { +```diff +buildscript { repositories { - maven { - // All of React Native (JS, Android binaries) is installed from npm - url "$rootDir/../node_modules/react-native/android" - } - maven { - // Android JSC is installed from npm - url("$rootDir/../node_modules/jsc-android/dist") - } - ... + google() + mavenCentral() + } + dependencies { + classpath("com.android.tools.build:gradle:7.3.1") ++ classpath("com.facebook.react:react-native-gradle-plugin") } - ... } ``` -> Make sure that the path is correct! You shouldn’t run into any “Failed to resolve: com.facebook.react:react-native:0.x.x" errors after running Gradle sync in Android Studio. +This makes sure the React Native Gradle Plugin is available inside your project. +Finally, add those lines inside your app's `build.gradle` file (it's a different `build.gradle` file inside your app folder): + +```diff +apply plugin: "com.android.application" ++apply plugin: "com.facebook.react" + +repositories { + mavenCentral() +} + +dependencies { + // Other dependencies here ++ implementation "com.facebook.react:react-android" ++ implementation "com.facebook.react:hermes-android" +} +``` + +Those depedencies are available on `mavenCentral()` so make sure you have it defined in your `repositories{}` block. + +:::info +We intentionally don't specify the version for those `implementation` dependencies as the React Native Gradle Plugin will take care of it. If you don't use the React Native Gradle Plugin, you'll have to specify version manually. +::: ### Enable native modules autolinking @@ -156,12 +169,7 @@ In your `index.js`, create your component. In our sample here, we will add a ` { return ( @@ -173,18 +181,18 @@ const HelloWorld = () => { var styles = StyleSheet.create({ container: { flex: 1, - justifyContent: 'center' + justifyContent: 'center', }, hello: { fontSize: 20, textAlign: 'center', - margin: 10 - } + margin: 10, + }, }); AppRegistry.registerComponent( 'MyReactNativeApp', - () => HelloWorld + () => HelloWorld, ); ``` @@ -371,7 +379,11 @@ Once you reach your React-powered activity inside the app, it should load the Ja ### 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. There’s one additional step, which you’ll have to do before every release build. You need to execute the following to create a React Native bundle, which will be included with your native Android app: +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. + +If you use the React Native Gradle Plugin as described above, everything should work when running app from Android Studio. + +If you're not using the React Native Gradle Plugin, there’s one additional step which you’ll have to do before every release build. You need to execute the following to create a React Native bundle, which will be included with your native Android app: ```shell $ npx react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/com/your-company-name/app-package-name/src/main/assets/index.android.bundle --assets-dest android/com/your-company-name/app-package-name/src/main/res/ diff --git a/docs/_integration-with-exisiting-apps-objc.md b/docs/_integration-with-exisiting-apps-objc.md index 893187c9b91..220245e9761 100644 --- a/docs/_integration-with-exisiting-apps-objc.md +++ b/docs/_integration-with-exisiting-apps-objc.md @@ -1,4 +1,4 @@ -import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import constants from '@site/core/TabsConstants'; import M1Cocoapods from './\_markdown-m1-cocoapods.mdx'; +import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import constants from '@site/core/TabsConstants'; ## Key Concepts @@ -186,8 +186,6 @@ Pod installation complete! There are 3 dependencies from the Podfile and 1 total > If this fails with errors mentioning `xcrun`, make sure that in Xcode in **Preferences > Locations** the Command Line Tools are assigned. - - ### Code integration Now we will actually modify the native iOS application to integrate React Native. For our 2048 sample app, we will add a "High Score" screen in React Native. @@ -208,15 +206,10 @@ In your `index.js`, create your component. In our sample here, we will add a ` { - const contents = scores.map((score) => ( +import {AppRegistry, StyleSheet, Text, View} from 'react-native'; + +const RNHighScores = ({scores}) => { + const contents = scores.map(score => ( {score.name}:{score.value} {'\n'} @@ -237,18 +230,18 @@ const styles = StyleSheet.create({ flex: 1, justifyContent: 'center', alignItems: 'center', - backgroundColor: '#FFFFFF' + backgroundColor: '#FFFFFF', }, highScoresTitle: { fontSize: 20, textAlign: 'center', - margin: 10 + margin: 10, }, scores: { textAlign: 'center', color: '#333333', - marginBottom: 5 - } + marginBottom: 5, + }, }); // Module name diff --git a/docs/_integration-with-exisiting-apps-swift.md b/docs/_integration-with-exisiting-apps-swift.md index a1c8ea18456..cb3a21aa1a6 100644 --- a/docs/_integration-with-exisiting-apps-swift.md +++ b/docs/_integration-with-exisiting-apps-swift.md @@ -1,5 +1,3 @@ -import M1Cocoapods from './\_markdown-m1-cocoapods.mdx'; - ## Key Concepts The keys to integrating React Native components into your iOS application are to: @@ -154,8 +152,6 @@ Pod installation complete! There are 3 dependencies from the Podfile and 1 total > If you get a warning such as "_The `swift-2048 [Debug]` target overrides the `FRAMEWORK_SEARCH_PATHS` build setting defined in `Pods/Target Support Files/Pods-swift-2048/Pods-swift-2048.debug.xcconfig`. This can lead to problems with the CocoaPods installation_", then make sure the `Framework Search Paths` in `Build Settings` for both `Debug` and `Release` only contain `$(inherited)`. - - ### Code integration Now we will actually modify the native iOS application to integrate React Native. For our 2048 sample app, we will add a "High Score" screen in React Native. @@ -176,15 +172,10 @@ In your `index.js`, create your component. In our sample here, we will add a ` { - const contents = scores.map((score) => ( +import {AppRegistry, StyleSheet, Text, View} from 'react-native'; + +const RNHighScores = ({scores}) => { + const contents = scores.map(score => ( {score.name}:{score.value} {'\n'} @@ -205,18 +196,18 @@ const styles = StyleSheet.create({ flex: 1, justifyContent: 'center', alignItems: 'center', - backgroundColor: '#FFFFFF' + backgroundColor: '#FFFFFF', }, highScoresTitle: { fontSize: 20, textAlign: 'center', - margin: 10 + margin: 10, }, scores: { textAlign: 'center', color: '#333333', - marginBottom: 5 - } + marginBottom: 5, + }, }); // Module name diff --git a/docs/_integration-with-existing-apps-kotlin.md b/docs/_integration-with-existing-apps-kotlin.md index 9500da50e71..0ab43d37f3c 100644 --- a/docs/_integration-with-existing-apps-kotlin.md +++ b/docs/_integration-with-existing-apps-kotlin.md @@ -41,7 +41,7 @@ $ yarn add react-native This will print a message similar to the following (scroll up in the yarn output to see it): -> warning "react-native@0.52.2" has unmet peer dependency "react@16.2.0". +> warning "react-native@0.70.5" has unmet peer dependency "react@18.1.0" This is OK, it means we also need to install React: @@ -55,58 +55,54 @@ Add `node_modules/` to your `.gitignore` file. ## Adding React Native to your app -### Configuring maven +### Configuring Gradle -Add the React Native and JSC dependency to your app's `build.gradle` file: +React Native uses the React Native Gradle Plugin to configure your dependencies and project setup. -```gradle -dependencies { - implementation "com.android.support:appcompat-v7:27.1.1" - ... - implementation "com.facebook.react:react-native:+" // From node_modules - implementation "org.webkit:android-jsc:+" -} -``` +First, let's edit your `settings.gradle` file by adding this line: -> If you want to ensure that you are always using a specific React Native version in your native build, replace `+` with an actual React Native version you've downloaded from `npm`. +```groovy +includeBuild('../node_modules/react-native-gradle-plugin') +``` -Add an entry for the local React Native and JSC maven directories to the top-level `settings.gradle`. Be sure to add it to the “dependencyResolutionManagement” block, above other maven repositories: +Then you need to open your top level `build.gradle` and include this line: -```gradle -dependencyResolutionManagement { - ... +```diff +buildscript { repositories { - ... - maven { - url "$rootDir/../node_modules/react-native/android" - } - maven { - url("$rootDir/../node_modules/jsc-android/dist") - } + google() + mavenCentral() + } + dependencies { + classpath("com.android.tools.build:gradle:7.3.1") ++ classpath("com.facebook.react:react-native-gradle-plugin") } } ``` -> If your project has the dependency repositories configured in the top-level `build.gradle`, be sure to add the entries to the “allprojects” block above other maven repositories: +This makes sure the React Native Gradle Plugin is available inside your project. +Finally, add those lines inside your app's `build.gradle` file (it's a different `build.gradle` file inside your app folder): -```gradle -allprojects { - repositories { - maven { - // All of React Native (JS, Android binaries) is installed from npm - url "$rootDir/../node_modules/react-native/android" - } - maven { - // Android JSC is installed from npm - url("$rootDir/../node_modules/jsc-android/dist") - } - ... - } - ... +```diff +apply plugin: "com.android.application" ++apply plugin: "com.facebook.react" + +repositories { + mavenCentral() +} + +dependencies { + // Other dependencies here ++ implementation "com.facebook.react:react-android" ++ implementation "com.facebook.react:hermes-android" } ``` -> Make sure that the path is correct! You shouldn’t run into any “Failed to resolve: com.facebook.react:react-native:0.x.x" errors after running Gradle sync in Android Studio. +Those depedencies are available on `mavenCentral()` so make sure you have it defined in your `repositories{}` block. + +:::info +We intentionally don't specify the version for those `implementation` dependencies as the React Native Gradle Plugin will take care of it. If you don't use the React Native Gradle Plugin, you'll have to specify version manually. +::: ### Enable native modules autolinking @@ -173,12 +169,7 @@ In your `index.js`, create your component. In our sample here, we will add a ` { return ( @@ -190,18 +181,18 @@ const HelloWorld = () => { var styles = StyleSheet.create({ container: { flex: 1, - justifyContent: 'center' + justifyContent: 'center', }, hello: { fontSize: 20, textAlign: 'center', - margin: 10 - } + margin: 10, + }, }); AppRegistry.registerComponent( 'MyReactNativeApp', - () => HelloWorld + () => HelloWorld, ); ``` @@ -364,7 +355,11 @@ Once you reach your React-powered activity inside the app, it should load the Ja ### 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. There’s one additional step, which you’ll have to do before every release build. You need to execute the following to create a React Native bundle, which will be included with your native Android app: +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. + +If you use the React Native Gradle Plugin as described above, everything should work when running app from Android Studio. + +If you're not using the React Native Gradle Plugin, there’s one additional step which you’ll have to do before every release build. You need to execute the following to create a React Native bundle, which will be included with your native Android app: ```shell $ npx react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/com/your-company-name/app-package-name/src/main/assets/index.android.bundle --assets-dest android/com/your-company-name/app-package-name/src/main/res/ diff --git a/docs/_markdown-m1-cocoapods.mdx b/docs/_markdown-m1-cocoapods.mdx deleted file mode 100644 index 41161b15791..00000000000 --- a/docs/_markdown-m1-cocoapods.mdx +++ /dev/null @@ -1,11 +0,0 @@ -
- Note for Mac M1 users - -Mac M1 architecture is not directly compatible with Cocoapods. If you encounter issues when installing pods, you can solve it by running: - -- `sudo arch -x86_64 gem install ffi` -- `arch -x86_64 pod install` - -These commands install the `ffi` package, to load dynamically-linked libraries and let you run the `pod install` properly, and runs `pod install` with the proper architecture. - -
diff --git a/docs/accessibility.md b/docs/accessibility.md index de91a016c42..39e8ae64a04 100644 --- a/docs/accessibility.md +++ b/docs/accessibility.md @@ -18,7 +18,7 @@ When `true`, indicates that the view is an accessibility element. When a view is On Android, `accessible={true}` property for a react-native View will be translated into native `focusable={true}`. -```jsx +```tsx text one text two @@ -33,7 +33,7 @@ When a view is marked as accessible, it is a good practice to set an accessibili To use, set the `accessibilityLabel` property to a custom string on your View, Text or Touchable: -```jsx +```tsx Label for Input Field Click me @@ -274,7 +274,7 @@ Defines a string value that labels an interactive element. Identifies the element that labels the element it is applied to. The value of `aria-labelledby` should match the [`nativeID`](view.md#nativeid) of the related element: -```jsx +```tsx Label for Input Field @@ -293,6 +293,12 @@ Indicates that an element will be updated, and describes the types of updates th - **polite** Accessibility services should announce changes to this view. - **assertive** Accessibility services should interrupt ongoing speech to immediately announce changes to this view. +| Type | Default | +| ---------------------------------------- | ------- | +| enum(`'assertive'`, `'off'`, `'polite'`) | `'off'` | + +--- + ### `aria-modal`
iOS
Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. @@ -313,15 +319,15 @@ Indicates whether a selectable element is currently selected or not. In the case of two overlapping UI components with the same parent, default accessibility focus can have unpredictable behavior. The `importantForAccessibility` property will resolve this by controlling if a view fires accessibility events and if it is reported to accessibility services. It can be set to `auto`, `yes`, `no` and `no-hide-descendants` (the last value will force accessibility services to ignore the component and all of its children). -```jsx +```tsx First layout Second layout @@ -342,6 +348,40 @@ Use this property to assign a custom function to be called when someone activate Assign this property to a custom function which will be called when someone performs the "magic tap" gesture, which is a double-tap with two fingers. A magic tap function should perform the most relevant action a user could take on a component. In the Phone app on iPhone, a magic tap answers a phone call, or ends the current one. If the selected element does not have an `onMagicTap` function, the system will traverse up the view hierarchy until it finds a view that does. +### `role` + +`role` communicates the purpose of a component to the user of an assistive technology. Has precedence over the [`accessibilityRole`](accessibility#accessibilityrole) prop. + +`role` can be one of the following: + +- **alert** Used when an element contains important text to be presented to the user. +- **button** Used when the element should be treated as a button. +- **checkbox** Used when an element represents a checkbox which can be checked, unchecked, or have mixed checked state. +- **combobox** Used when an element represents a combo box, which allows the user to select among several choices. +- **grid** Used with ScrollView, VirtualizedList, FlatList, or SectionList to represent a grid. Adds the in/out of grid announcements to the android GridView. +- **heading** Used when an element acts as a header for a content section (e.g. the title of a navigation bar). +- **img** Used when the element should be treated as an image. Can be combined with button or link, for example. +- **link** Used when the element should be treated as a link. +- **list** Used to identify a list of items. +- **menu** Used when the component is a menu of choices. +- **menubar** Used when a component is a container of multiple menus. +- **menuitem** Used to represent an item within a menu. +- **none** Used when the element has no role. +- **presentation** Used when the element has no role. +- **progressbar** Used to represent a component which indicates progress of a task. +- **radio** Used to represent a radio button. +- **radiogroup** Used to represent a group of radio buttons. +- **scrollbar** Used to represent a scroll bar. +- **searchbox** Used when the text field element should also be treated as a search field. +- **slider** Used when an element can be "adjusted" (e.g. a slider). +- **spinbutton** Used to represent a button which opens a list of choices. +- **summary** Used when an element can be used to provide a quick summary of current conditions in the app when the app first launches. +- **switch** Used to represent a switch which can be turned on and off. +- **tab** Used to represent a tab. +- **tablist** Used to represent a list of tabs. +- **timer** Used to represent a timer. +- **toolbar** Used to represent a tool bar (a container of action buttons or components). + ## Accessibility Actions Accessibility actions allow an assistive technology to programmatically invoke the actions of a component. In order to support accessibility actions, a component must do two things: @@ -371,15 +411,15 @@ The `label` field is optional for standard actions, and is often unused by assis 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 which defines and handles several custom actions. -```jsx +```tsx { + onAccessibilityAction={event => { switch (event.nativeEvent.actionName) { case 'cut': Alert.alert('Alert', 'cut action success'); @@ -403,17 +443,13 @@ The `AccessibilityInfo` API allows you to determine whether or not a screen read Sometimes it is useful to trigger an accessibility event on a UI component (i.e. when a custom view appears on a screen or set accessibility focus to a view). Native UIManager module exposes a method ‘sendAccessibilityEvent’ for this purpose. It takes two arguments: view tag and a type of an event. The supported event types are `typeWindowStateChanged`, `typeViewFocused` and `typeViewClicked`. -```jsx -import { - Platform, - UIManager, - findNodeHandle -} from 'react-native'; +```tsx +import {Platform, UIManager, findNodeHandle} from 'react-native'; if (Platform.OS === 'android') { UIManager.sendAccessibilityEvent( findNodeHandle(this), - UIManager.AccessibilityEventTypes.typeViewFocused + UIManager.AccessibilityEventTypes.typeViewFocused, ); } ``` diff --git a/docs/accessibilityinfo.md b/docs/accessibilityinfo.md index 39fe88bcf58..0ba8355104c 100644 --- a/docs/accessibilityinfo.md +++ b/docs/accessibilityinfo.md @@ -13,8 +13,8 @@ Sometimes it's useful to know whether or not the device has a screen reader that ```SnackPlayer name=AccessibilityInfo%20Function%20Component%20Example&supportedPlatforms=android,ios -import React, { useState, useEffect } from "react"; -import { AccessibilityInfo, View, Text, StyleSheet } from "react-native"; +import React, {useState, useEffect} from 'react'; +import {AccessibilityInfo, View, Text, StyleSheet} from 'react-native'; const App = () => { const [reduceMotionEnabled, setReduceMotionEnabled] = useState(false); @@ -22,28 +22,24 @@ const App = () => { useEffect(() => { const reduceMotionChangedSubscription = AccessibilityInfo.addEventListener( - "reduceMotionChanged", - reduceMotionEnabled => { - setReduceMotionEnabled(reduceMotionEnabled); - } + 'reduceMotionChanged', + isReduceMotionEnabled => { + setReduceMotionEnabled(isReduceMotionEnabled); + }, ); const screenReaderChangedSubscription = AccessibilityInfo.addEventListener( - "screenReaderChanged", - screenReaderEnabled => { - setScreenReaderEnabled(screenReaderEnabled); - } + 'screenReaderChanged', + isScreenReaderEnabled => { + setScreenReaderEnabled(isScreenReaderEnabled); + }, ); - AccessibilityInfo.isReduceMotionEnabled().then( - reduceMotionEnabled => { - setReduceMotionEnabled(reduceMotionEnabled); - } - ); - AccessibilityInfo.isScreenReaderEnabled().then( - screenReaderEnabled => { - setScreenReaderEnabled(screenReaderEnabled); - } - ); + AccessibilityInfo.isReduceMotionEnabled().then(isReduceMotionEnabled => { + setReduceMotionEnabled(isReduceMotionEnabled); + }); + AccessibilityInfo.isScreenReaderEnabled().then(isScreenReaderEnabled => { + setScreenReaderEnabled(isScreenReaderEnabled); + }); return () => { reduceMotionChangedSubscription.remove(); @@ -54,24 +50,24 @@ const App = () => { return ( - The reduce motion is {reduceMotionEnabled ? "enabled" : "disabled"}. + The reduce motion is {reduceMotionEnabled ? 'enabled' : 'disabled'}. - The screen reader is {screenReaderEnabled ? "enabled" : "disabled"}. + The screen reader is {screenReaderEnabled ? 'enabled' : 'disabled'}. ); -} +}; const styles = StyleSheet.create({ container: { flex: 1, - alignItems: "center", - justifyContent: "center" + alignItems: 'center', + justifyContent: 'center', }, status: { - margin: 30 - } + margin: 30, + }, }); export default App; @@ -80,9 +76,12 @@ export default App; -```SnackPlayer name=AccessibilityInfo%20Class%20Component%20Example&supportedPlatforms=android,ios -import React, { Component } from 'react'; -import { AccessibilityInfo, View, Text, StyleSheet } from 'react-native'; + + + +```SnackPlayer name=AccessibilityInfo%20Class%20Component%20Example&supportedPlatforms=android,ios&ext=js +import React, {Component} from 'react'; +import {AccessibilityInfo, View, Text, StyleSheet} from 'react-native'; class AccessibilityStatusExample extends Component { state = { @@ -94,21 +93,21 @@ class AccessibilityStatusExample extends Component { this.reduceMotionChangedSubscription = AccessibilityInfo.addEventListener( 'reduceMotionChanged', reduceMotionEnabled => { - this.setState({ reduceMotionEnabled }); - } + this.setState({reduceMotionEnabled}); + }, ); this.screenReaderChangedSubscription = AccessibilityInfo.addEventListener( 'screenReaderChanged', screenReaderEnabled => { - this.setState({ screenReaderEnabled }); - } + this.setState({screenReaderEnabled}); + }, ); AccessibilityInfo.isReduceMotionEnabled().then(reduceMotionEnabled => { - this.setState({ reduceMotionEnabled }); + this.setState({reduceMotionEnabled}); }); AccessibilityInfo.isScreenReaderEnabled().then(screenReaderEnabled => { - this.setState({ screenReaderEnabled }); + this.setState({screenReaderEnabled}); }); } @@ -147,6 +146,83 @@ const styles = StyleSheet.create({ export default AccessibilityStatusExample; ``` + + + +```SnackPlayer name=AccessibilityInfo%20Class%20Component%20Example&supportedPlatforms=android,ios&ext=tsx +import React, {Component} from 'react'; +import {AccessibilityInfo, View, Text, StyleSheet} from 'react-native'; +import type {EmitterSubscription} from 'react-native'; + +class AccessibilityStatusExample extends Component { + reduceMotionChangedSubscription?: EmitterSubscription; + screenReaderChangedSubscription?: EmitterSubscription; + + state = { + reduceMotionEnabled: false, + screenReaderEnabled: false, + }; + + componentDidMount() { + this.reduceMotionChangedSubscription = AccessibilityInfo.addEventListener( + 'reduceMotionChanged', + reduceMotionEnabled => { + this.setState({reduceMotionEnabled}); + }, + ); + this.screenReaderChangedSubscription = AccessibilityInfo.addEventListener( + 'screenReaderChanged', + screenReaderEnabled => { + this.setState({screenReaderEnabled}); + }, + ); + + AccessibilityInfo.isReduceMotionEnabled().then(reduceMotionEnabled => { + this.setState({reduceMotionEnabled}); + }); + AccessibilityInfo.isScreenReaderEnabled().then(screenReaderEnabled => { + this.setState({screenReaderEnabled}); + }); + } + + componentWillUnmount() { + this.reduceMotionChangedSubscription?.remove(); + this.screenReaderChangedSubscription?.remove(); + } + + render() { + return ( + + + The reduce motion is{' '} + {this.state.reduceMotionEnabled ? 'enabled' : 'disabled'}. + + + The screen reader is{' '} + {this.state.screenReaderEnabled ? 'enabled' : 'disabled'}. + + + ); + } +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + }, + status: { + margin: 30, + }, +}); + +export default AccessibilityStatusExample; +``` + + + + @@ -158,8 +234,13 @@ export default AccessibilityStatusExample; ### `addEventListener()` -```jsx -static addEventListener(eventName, handler) +```tsx +static addEventListener( + eventName: AccessibilityChangeEventName | AccessibilityAnnouncementEventName, + handler: ( + event: AccessibilityChangeEvent | AccessibilityAnnouncementFinishedEvent, + ) => void, +): EmitterSubscription; ``` Add an event handler. Supported events: @@ -179,8 +260,8 @@ Add an event handler. Supported events: ### `announceForAccessibility()` -```jsx -static announceForAccessibility(announcement) +```tsx +static announceForAccessibility(announcement: string); ``` Post a string to be announced by the screen reader. @@ -189,8 +270,11 @@ Post a string to be announced by the screen reader. ### `announceForAccessibilityWithOptions()` -```jsx -static announceForAccessibilityWithOptions(announcement, options) +```tsx +static announceForAccessibilityWithOptions( + announcement: string, + options: 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. @@ -206,8 +290,8 @@ Post a string to be announced by the screen reader with modification options. By ### `getRecommendedTimeoutMillis()`
Android
-```jsx -static getRecommendedTimeoutMillis(originalTimeout) +```tsx +static getRecommendedTimeoutMillis(originalTimeout: number): Promise; ``` Gets the timeout in millisecond that the user needs. @@ -223,8 +307,8 @@ This value is set in "Time to take action (Accessibility timeout)" of "Accessibi ### `isAccessibilityServiceEnabled()`
Android
-```jsx -static isAccessibilityServiceEnabled(): Promise +```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. @@ -235,8 +319,8 @@ Check whether any accessibility service is enabled. This includes TalkBack but a ### `isBoldTextEnabled()`
iOS
-```jsx -static isBoldTextEnabled() +```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. @@ -245,8 +329,8 @@ Query whether a bold text is currently enabled. Returns a promise which resolves ### `isGrayscaleEnabled()`
iOS
-```jsx -static isGrayscaleEnabled() +```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. @@ -255,8 +339,8 @@ Query whether grayscale is currently enabled. Returns a promise which resolves t ### `isInvertColorsEnabled()`
iOS
-```jsx -static isInvertColorsEnabled() +```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. @@ -265,8 +349,8 @@ Query whether invert colors is currently enabled. Returns a promise which resolv ### `isReduceMotionEnabled()` -```jsx -static 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. @@ -275,8 +359,8 @@ Query whether reduce motion is currently enabled. Returns a promise which resolv ### `isReduceTransparencyEnabled()`
iOS
-```jsx -static isReduceTransparencyEnabled() +```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. @@ -285,8 +369,8 @@ Query whether reduce transparency is currently enabled. Returns a promise which ### `isScreenReaderEnabled()` -```jsx -static 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. @@ -295,28 +379,18 @@ Query whether a screen reader is currently enabled. Returns a promise which reso ### `prefersCrossFadeTransitions()`
iOS
-```jsx -static prefersCrossFadeTransitions() +```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. --- -### `removeEventListener()` - -```jsx -static removeEventListener(eventName, handler) -``` - -> **Deprecated.** Use the `remove()` method on the event subscription returned by [`addEventListener()`](#addeventlistener). - ---- - ### `setAccessibilityFocus()` -```jsx -static setAccessibilityFocus(reactTag) +```tsx +static setAccessibilityFocus(reactTag: number); ``` Set accessibility focus to a React component. diff --git a/docs/actionsheetios.md b/docs/actionsheetios.md index a56f4629f9e..fd060e0dec9 100644 --- a/docs/actionsheetios.md +++ b/docs/actionsheetios.md @@ -8,29 +8,29 @@ Displays native to iOS [Action Sheet](https://developer.apple.com/design/human-i ## Example ```SnackPlayer name=ActionSheetIOS&supportedPlatforms=ios -import React, { useState } from "react"; -import { ActionSheetIOS, Button, StyleSheet, Text, View } from "react-native"; +import React, {useState} from 'react'; +import {ActionSheetIOS, Button, StyleSheet, Text, View} from 'react-native'; const App = () => { - const [result, setResult] = useState("🔮"); + const [result, setResult] = useState('🔮'); const onPress = () => ActionSheetIOS.showActionSheetWithOptions( { - options: ["Cancel", "Generate number", "Reset"], + options: ['Cancel', 'Generate number', 'Reset'], destructiveButtonIndex: 2, cancelButtonIndex: 0, - userInterfaceStyle: 'dark' + userInterfaceStyle: 'dark', }, buttonIndex => { if (buttonIndex === 0) { // cancel action } else if (buttonIndex === 1) { - setResult(Math.floor(Math.random() * 100) + 1); + setResult(String(Math.floor(Math.random() * 100) + 1)); } else if (buttonIndex === 2) { - setResult("🔮"); + setResult('🔮'); } - } + }, ); return ( @@ -44,12 +44,12 @@ const App = () => { const styles = StyleSheet.create({ container: { flex: 1, - justifyContent: "center" + justifyContent: 'center', }, result: { fontSize: 64, - textAlign: "center" - } + textAlign: 'center', + }, }); export default App; @@ -61,8 +61,11 @@ export default App; ### `showActionSheetWithOptions()` -```jsx -static showActionSheetWithOptions(options, callback) +```tsx +static showActionSheetWithOptions: ( + options: ActionSheetIOSOptions, + callback: (buttonIndex: number) => void, +); ``` Display an iOS action sheet. The `options` object must contain one or more of: @@ -82,18 +85,18 @@ The 'callback' function takes one parameter, the zero-based index of the selecte Minimal example: -```jsx +```tsx ActionSheetIOS.showActionSheetWithOptions( { options: ['Cancel', 'Remove'], destructiveButtonIndex: 1, - cancelButtonIndex: 0 + cancelButtonIndex: 0, }, - (buttonIndex) => { + buttonIndex => { if (buttonIndex === 1) { /* destructive action */ } - } + }, ); ``` @@ -101,8 +104,8 @@ ActionSheetIOS.showActionSheetWithOptions( ### `dismissActionSheet()` -```jsx -static dismissActionSheet() +```tsx +static dismissActionSheet(); ``` Dismisses the most upper iOS action sheet presented, if no action sheet is present a warning is displayed. @@ -111,8 +114,12 @@ Dismisses the most upper iOS action sheet presented, if no action sheet is prese ### `showShareActionSheetWithOptions()` -```jsx -static showShareActionSheetWithOptions(options, failureCallback, successCallback) +```tsx +static showShareActionSheetWithOptions: ( + options: ShareActionSheetIOSOptions, + failureCallback: (error: Error) => void, + successCallback: (success: boolean, method: string) => void, +); ``` Display the iOS share sheet. The `options` object should contain one or both of `message` and `url` and can additionally have a `subject` or `excludedActivityTypes`: diff --git a/docs/activityindicator.md b/docs/activityindicator.md index 33e05f8d587..6659c0c6a2f 100644 --- a/docs/activityindicator.md +++ b/docs/activityindicator.md @@ -13,8 +13,8 @@ Displays a circular loading indicator. ```SnackPlayer name=ActivityIndicator%20Function%20Component%20Example -import React from "react"; -import { ActivityIndicator, StyleSheet, Text, View } from "react-native"; +import React from 'react'; +import {ActivityIndicator, StyleSheet, View} from 'react-native'; const App = () => ( @@ -28,13 +28,13 @@ const App = () => ( const styles = StyleSheet.create({ container: { flex: 1, - justifyContent: "center" + justifyContent: 'center', }, horizontal: { - flexDirection: "row", - justifyContent: "space-around", - padding: 10 - } + flexDirection: 'row', + justifyContent: 'space-around', + padding: 10, + }, }); export default App; @@ -44,8 +44,8 @@ export default App; ```SnackPlayer name=ActivityIndicator%20Class%20Component%20Example -import React, { Component } from "react"; -import { ActivityIndicator, StyleSheet, Text, View } from "react-native"; +import React, {Component} from 'react'; +import {ActivityIndicator, StyleSheet, View} from 'react-native'; class App extends Component { render() { @@ -63,13 +63,13 @@ class App extends Component { const styles = StyleSheet.create({ container: { flex: 1, - justifyContent: "center" + justifyContent: 'center', }, horizontal: { - flexDirection: "row", - justifyContent: "space-around", - padding: 10 - } + flexDirection: 'row', + justifyContent: 'space-around', + padding: 10, + }, }); export default App; diff --git a/docs/alert.md b/docs/alert.md index a347205a57c..e90473e384d 100644 --- a/docs/alert.md +++ b/docs/alert.md @@ -17,56 +17,48 @@ This is an API that works both on Android and iOS and can show static alerts. Al ```SnackPlayer name=Alert%20Function%20Component%20Example&supportedPlatforms=ios,android -import React, { useState } from "react"; -import { View, StyleSheet, Button, Alert } from "react-native"; +import React from 'react'; +import {View, StyleSheet, Button, Alert} from 'react-native'; const App = () => { const createTwoButtonAlert = () => - Alert.alert( - "Alert Title", - "My Alert Msg", - [ - { - text: "Cancel", - onPress: () => console.log("Cancel Pressed"), - style: "cancel" - }, - { text: "OK", onPress: () => console.log("OK Pressed") } - ] - ); + Alert.alert('Alert Title', 'My Alert Msg', [ + { + text: 'Cancel', + onPress: () => console.log('Cancel Pressed'), + style: 'cancel', + }, + {text: 'OK', onPress: () => console.log('OK Pressed')}, + ]); const createThreeButtonAlert = () => - Alert.alert( - "Alert Title", - "My Alert Msg", - [ - { - text: "Ask me later", - onPress: () => console.log("Ask me later pressed") - }, - { - text: "Cancel", - onPress: () => console.log("Cancel Pressed"), - style: "cancel" - }, - { text: "OK", onPress: () => console.log("OK Pressed") } - ] - ); + Alert.alert('Alert Title', 'My Alert Msg', [ + { + text: 'Ask me later', + onPress: () => console.log('Ask me later pressed'), + }, + { + text: 'Cancel', + onPress: () => console.log('Cancel Pressed'), + style: 'cancel', + }, + {text: 'OK', onPress: () => console.log('OK Pressed')}, + ]); return ( -