react-native Documentation

A framework for building native apps with React.

0 stars C++ C++ 43 files ยท ~13,282 tokens
RAW Doc

Technical Documentation: infinitered/react-native

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

React Native

[Getting Started](https://reactnative.dev/docs/getting-started) ยท [Learn the Basics](https://reactnative.dev/docs/tutorial) ยท [Showcase](https://reactnative.dev/showcase) ยท [Contribute](https://reactnative.dev/docs/contributing) ยท [Community](https://reactnative.dev/help) ยท [Support](https://github.com/facebook/react-native/blob/HEAD/.github/SUPPORT.md)

React Native brings React's declarative UI framework to iOS and Android. With React Native, you use native UI controls and have full access to the native platform.

  • Declarative. React makes it painless to create interactive UIs. Declarative views make your code more predictable and easier to debug.
  • Component-Based. Build encapsulated components that manage their state, then compose them to make complex UIs.
  • Developer Velocity. See local changes in seconds. Changes to JavaScript code can be live reloaded without rebuilding the native app.
  • Portability. Reuse code across iOS, Android, and other platforms.

React Native is developed and supported by many companies and individual core contributors. Find out more in our ecosystem overview.

Contents

๐Ÿ“‹ Requirements

React Native apps may target iOS 13.4 and Android 6.0 (API 23) or newer. You may use Windows, macOS, or Linux as your development operating system, though building and running iOS apps is limited to macOS. Tools like Expo can be used to work around this.

๐ŸŽ‰ Building your first React Native app

Follow the Getting Started guide. The recommended way to install React Native depends on your project. Here you can find short guides for the most common scenarios:

๐Ÿ“– Documentation

The full documentation for React Native can be found on our website.

The React Native documentation discusses components, APIs, and topics that are specific to React Native. For further documentation on the React API that is shared between React Native and React DOM, refer to the React documentation.

The source for the React Native documentation and website is hosted on a separate repo, @facebook/react-native-website.

๐Ÿš€ Upgrading

Upgrading to new versions of React Native may give you access to more APIs, views, developer tools, and other goodies. See the Upgrading Guide for instructions.

React Native releases are discussed in this discussion repo.

๐Ÿ‘ How to Contribute

The main purpose of this repository is to continue evolving React Native core. We want to make contributing to this project as easy and transparent as possible, and we are grateful to the community for contributing bug fixes and improvements. Read below to learn how you can take part in improving React Native.

[Code of Conduct][code]

Facebook has adopted a Code of Conduct that we expect project participants to adhere to.
Please read the full text so that you can understand what actions will and will not be tolerated.

[Contributing Guide][contribute]

Read our Contributing Guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to React Native.

[Open Source Roadmap][roadmap]

You can learn more about our vision for React Native in the Roadmap.

Good First Issues

We have a list of good first issues that contain bugs which have a relatively limited scope. This is a great place to get started, gain experience, and get familiar with our contribution process.

Discussions

Larger discussions and proposals are discussed in @react-native-community/discussions-and-proposals.

๐Ÿ“„ License

React Native is MIT licensed, as found in the LICENSE file.

React Native documentation is Creative Commons licensed, as found in the LICENSE-docs file.


Overview (`.circleci/README.md`)

Circle CI

This directory was home to the Circle CI configuration files.
In July 2024 we moved to GitHub Actions, and week this folder for backward compatibility, as we want to keep on using Circle CI for the release of React Native <= 0.74.


Overview (`packages/assets/README.md`)

@react-native/assets-registry

Version

Installation

text
yarn add --dev @react-native/assets-registry

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/assets.

Overview (`packages/babel-plugin-codegen/README.md`)

@react-native/babel-plugin-codegen

Version

Installation

text
yarn add --dev @babel/core @react-native/babel-plugin-codegen

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/babel-plugin-codegen.

Overview (`packages/community-cli-plugin/README.md`)

@react-native/community-cli-plugin

This is an internal dependency of React Native. Please don't depend on it directly.

CLI entry points supporting core React Native development features.

Formerly @react-native-community/cli-plugin-metro.

Commands

`start`

Start the React Native development server.

Usage

sh
npx react-native start [options]

Options

Option Description
--port <number> Set the server port.
--host <string> Set the server host.
--projectRoot Set the path to the project root.
--watchFolders <list> Specify additional folders to be added to the watch list.
--assetPlugins <list> Specify additional asset plugins.
--sourceExts <list> Specify additional source extensions to bundle.
--max-workers <number> Set the maximum number of workers the worker-pool will spawn for transforming files. Defaults to the number of the cores available on your machine.
--transformer <string> Specify a custom transformer.
--reset-cache Remove cached files.
--custom-log-reporter-path <string> Specify a module path exporting a replacement for TerminalReporter.
--https Enable HTTPS connections.
--key Specify path to a custom SSL key.
--cert Specify path to a custom SSL cert.
--config <string> Path to the CLI configuration file.
--no-interactive Disable interactive mode.

`bundle`

Build the bundle for the provided JavaScript entry file.

Usage

sh
npx react-native bundle --entry-file <path> [options]

Options

Option Description
--entry-file Set the path to the root JavaScript entry file.
--platform <string> Set the target platform (either "android" or "ios"). Defaults to "ios".
--transformer <string> Specify a custom transformer.
--dev [boolean] If false, warnings are disabled and the bundle is minified. Defaults to true.
--minify [boolean] Allows overriding whether bundle is minified. Defaults to false if --dev is set. Disabling minification can be useful for speeding up production builds for testing purposes.
--bundle-output <string> Specify the path to store the resulting bundle.
--bundle-encoding <string> Specify the encoding for writing the bundle (https://nodejs.org/api/buffer.html#buffer_buffer).
--resolver-option <string...> Custom resolver options of the form key=value. URL-encoded. May be specified multiple times.
--sourcemap-output <string> Specify the path to store the source map file for the resulting bundle.
--sourcemap-sources-root <string> Set the root path for source map entries.
--sourcemap-use-absolute-path Report SourceMapURL using its full path.
--max-workers <number> Set the maximum number of workers the worker-pool will spawn for transforming files. Defaults to the number of the cores available on your machine.
--assets-dest <string> Specify the directory path for storing assets referenced in the bundle.
--reset-cache Remove cached files.
--read-global-cache Attempt to fetch transformed JS code from the global cache, if configured. Defaults to false.
--config <string> Path to the CLI configuration file.

Contributing

Changes to this package can be made locally and tested against the rn-tester app, per the Contributing guide. During development, this package is automatically run from source with no build step.


Overview (`packages/core-cli-utils/README.md`)

@react-native/core-cli-utils

A collection of utilites to help Frameworks build their React Native CLI tooling. This is not intended to be used directly use users of React Native.

Usage

js
import { Command } from 'commander';
import cli from '@react-native/core-cli-utils';
import debug from 'debug';

const android = new Command('android');

const frameworkFindsAndroidSrcDir = "...";
const tasks = cli.clean.android(frameworkFindsAndroidSrcDir);
const log = debug('fancy-framework:android');

android
    .command('clean')
    .description(cli.clean.android)
    .action(async () => {
        const log = debug('fancy-framework:android:clean');
        log(`๐Ÿงน let me clean your Android caches`);
        // Add other caches your framework needs besides the normal React Native caches
        // here.
        for (const task of tasks) {
            try {
                log(`\t ${task.label}`);
                // See: https://github.com/sindresorhus/execa#lines
                const {stdout} = await task.action({ lines: true })
                log(stdout.join('\n\tGradle: '));
            } catch (e) {
                log(`\t โš ๏ธ whoops: ${e.message}`);
            }
        }
    });

And you'd be using it like this:

bash
$ ./fancy-framework android clean
๐Ÿงน let me clean your Android caches
    Gradle: // a bunch of gradle output
    Gradle: ....

Features

  • "@react-native/core-cli-utils/version.js" contains the platform and tooling version requirements for react-native.

Contributing

Changes to this package can be made locally and linked against your app. Please see the Contributing guide.


Overview (`packages/debugger-frontend/README.md`)

@react-native/debugger-frontend

Debugger frontend for React Native based on Chrome DevTools.

This package is internal to React Native and is intended to be used via @react-native/dev-middleware.

Usage

The package exports the absolute path to the directory containing the frontend assets.

js
const frontendPath = require('@react-native/debugger-frontend');

// Pass frontendPath to a static server, etc

Contributing

Source repo

Source code for this package lives in the facebookexperimental/rn-chrome-devtools-frontend repo. See below for how we build and check in changes.

Updating the frontend assets

The compiled assets for the debugger frontend are periodically checked into this package under the dist/ folder. To update these, run node scripts/debugger-frontend/sync-and-build from the root of your react-native checkout.

sh
# For main
node scripts/debugger-frontend/sync-and-build --branch main

# For stable branches (e.g. '0.73-stable')
node scripts/debugger-frontend/sync-and-build --branch 0.73-stable

By default, this will clone and build from facebookexperimental/rn-chrome-devtools-frontend.


Overview (`packages/dev-middleware/README.md`)

@react-native/dev-middleware

Dev server middleware supporting core React Native development features. This package is preconfigured in all React Native projects.

Usage

Middleware can be attached to a dev server (e.g. Metro) using the createDevMiddleware API.

js
import { createDevMiddleware } from '@react-native/dev-middleware';

function myDevServerImpl(args) {
  ...

  const {middleware, websocketEndpoints} = createDevMiddleware({
    projectRoot: metroConfig.projectRoot,
    serverBaseUrl: `http://${args.host}:${args.port}`,
    logger,
  });

  await Metro.runServer(metroConfig, {
    host: args.host,
    ...,
    unstable_extraMiddleware: [
      middleware,
      // Optionally extend with additional HTTP middleware
    ],
    websocketEndpoints: {
      ...websocketEndpoints,
      // Optionally extend with additional WebSocket endpoints
    },
  });
}

Included middleware

@react-native/dev-middleware is designed for integrators such as @expo/dev-server and @react-native/community-cli-plugin. It provides a common default implementation for core React Native dev server responsibilities.

We intend to keep this to a narrow set of functionality, based around:

  • Debugging โ€”ย The Chrome DevTools protocol (CDP) endpoints supported by React Native, including the Inspector Proxy, which facilitates connections with multiple devices.
  • Dev actions โ€”ย Endpoints implementing core Dev Menu actions, e.g. reloading the app, opening the debugger frontend.

HTTP endpoints

DevMiddlewareAPI.middleware

These are exposed as a connect middleware handler, assignable to Metro.runServer or other compatible HTTP servers.

GET `/json/list`, `/json` ([CDP](https://chromedevtools.github.io/devtools-protocol/#endpoints))

Returns the list of available WebSocket targets for all connected React Native app sessions.

GET `/json/version` ([CDP](https://chromedevtools.github.io/devtools-protocol/#endpoints))

Returns version metadata used by Chrome DevTools.

GET `/debugger-frontend`

Subpaths of this endpoint are reserved to serve the JavaScript debugger frontend.

POST `/open-debugger`

Open the JavaScript debugger for a given CDP target. Must be provided with one of the following query params:

  • deviceโ€Œ โ€” An ID unique to a combination of device and app, stable across installs. Implemented by getInspectorDeviceId on each native platform.
  • target โ€”ย The target page ID as returned by /json/list for the current dev server session.
  • appId (deprecated, legacy only) โ€”ย The application bundle identifier to match (non-unique across multiple connected devices). This param will only match legacy Hermes debugger targets.

Example

text
curl -X POST 'http://localhost:8081/open-debugger?target=<targetId>'

WebSocket endpoints

DevMiddlewareAPI.websocketEndpoints

`/inspector/device`

WebSocket handler for registering device connections.

`/inspector/debug`

WebSocket handler that proxies CDP messages to/from the corresponding device.

Contributing

Changes to this package can be made locally and tested against the rn-tester app, per the Contributing guide. During development, this package is automatically run from source with no build step.


Overview (`packages/eslint-config-react-native/README.md`)

@react-native/eslint-config

Version

Installation

text
yarn add --dev eslint prettier @react-native/eslint-config

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Usage

Add to your eslint config (.eslintrc, or eslintConfig field in package.json):

json
{
    "extends": "@react-native"
}

Overview (`packages/eslint-plugin-react-native/README.md`)

@react-native/eslint-plugin

This plugin is intended to be used in @react-native/eslint-config. You probably want to install that package instead.

Installation

text
yarn add --dev eslint @react-native/eslint-plugin

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Usage

Add to your eslint config (.eslintrc, or eslintConfig field in package.json):

json
{
    "plugins": ["@react-native"]
}

Rules

`platform-colors`

Enforces that calls to PlatformColor and DynamicColorIOS are statically analyzable to enable performance optimizations.

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/eslint-plugin-react-native.

Overview (`packages/eslint-plugin-specs/README.md`)

@react-native/eslint-plugin-specs

Version

Installation

text
yarn add --dev @react-native/eslint-plugin-specs

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/eslint-plugin-specs.

Overview (`packages/gradle-plugin/README.md`)

@react-native/gradle-plugin

Version

A Gradle Plugin used to support development of React Native applications for Android.

Installation

text
yarn add @react-native/gradle-plugin

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. ./gradlew -p packages/gradle-plugin test.

Overview (`packages/helloworld/README.md`)

Hello World Test Application

This is the React Native HelloWorld test app. It is for internal use and shouldn't be dependend on.


Overview (`packages/hermes-inspector-msggen/README.md`)

@react-native/hermes-inspector-msggen

Version

Installation

text
yarn add --dev @babel/cli @babel/core @babel/preset-env @babel/preset-flow jest @react-native/hermes-inspector-msggen

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/hermes-inspector-msggen.

Overview (`packages/metro-config/README.md`)

@react-native/metro-config

Version

Installation

text
yarn add --dev @react-native/js-polyfills metro-config @react-native/metro-babel-transformer metro-runtime @react-native/metro-config

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/metro-config.

Overview (`packages/normalize-color/README.md`)

@react-native/normalize-colors

Version

Installation

text
yarn add --dev @react-native/normalize-colors

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/normalize-color.

Overview (`packages/polyfills/README.md`)

@react-native/js-polyfills

Version

Installation

text
yarn add @react-native/js-polyfills

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/polyfills.

Overview (`packages/react-native-babel-preset/README.md`)

@react-native/babel-preset

Babel presets for React Native applications. React Native itself uses this Babel preset by default when transforming your app's source code.

If you wish to use a custom Babel configuration by writing a babel.config.js file in your project's root directory, you must specify all the plugins necessary to transform your code. React Native does not apply its default Babel configuration in this case. So, to make your life easier, you can use this preset to get the default configuration and then specify more plugins that run before it.

Usage

As mentioned above, you only need to use this preset if you are writing a custom babel.config.js file.

Installation

Install @react-native/babel-preset in your app:

with npm:

sh
npm i @react-native/babel-preset --save-dev

or with yarn:

sh
yarn add -D @react-native/babel-preset

Configuring Babel

Then, create a file called babel.config.js in your project's root directory. The existence of this babel.config.js file will tell React Native to use your custom Babel configuration instead of its own. Then load this preset:

text
{
  "presets": ["module:@react-native/babel-preset"]
}

You can further customize your Babel configuration by specifying plugins and other options. See Babel's babel.config.js documentation to learn more.

Help and Support

If you get stuck configuring Babel, please ask a question on Stack Overflow or find a consultant for help. If you discover a bug, please open up an issue.


Overview (`packages/react-native-bots/README.md`)

Danger

Danger is a JavaScript runtime which helps you provide continuous feedback inside GitHub.
It's used inside Github Actions to analyze the contents of a GitHub pull request.

If you want to test changes to Danger, I'd recommend checking out an existing PR and then running the danger pr command.
You'll need a GitHub Public Access Token (PAT). It will look like ghp_<REDACTED>.

So, for example:

text
DANGER_GITHUB_API_TOKEN=ghp_<REDACTED> yarn danger pr https://github.com/facebook/react-native/pull/1234

Code Analysis Bot

The code analysis bot provides lint and other results as inline reviews on GitHub. It runs as part of the Circle CI analysis workflow.

If you want to test changes to the Code Analysis Bot, I'd recommend checking out an existing PR and then running the analyze pr command.
You'll need a GitHub token. You can re-use this one: 312d354b5c36f082cfe9 07973d757026bdd9f196 (just remove the space).
So, for example:

text
GITHUB_TOKEN=[ENV_ABOVE] GITHUB_PR_NUMBER=1234 yarn lint-ci

Overview (`packages/react-native-codegen/README.md`)

@react-native/codegen

Version

Installation

text
yarn add --dev @react-native/codegen

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/react-native-codegen.

Overview (`packages/react-native-info/README.md`)

react-native-info

This package is intended to be used as a part of creating issues with the React Native project. It provides accurate information about your system, and helps our team triage and debug issues.

Usage

text
$ cd YourProject
$ npx react-native-info@latest
info Fetching system and libraries information...
System:
  OS: macOS 14.4.1
  CPU: (10) arm64 Apple M1 Pro
  Memory: 527.52 MB / 32.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 20.12.0
...

Notes

This is built upon the work of the React Native Community CLI ๐ŸŽ‰.


Overview (`packages/react-native-test-library/README.md`)

Important

This package is for testing only. It is a subject to frequent change. It does not represent the recomended structure for React native libraries. It should not be used as a referece for such purposes.

Building

text
yarn install
yarn build
npx react-native codegen

Overview (`packages/react-native/README.md`)

Where is the template?

The React Native Template has moved from being shipping inside the react-native package to it's own package: @react-native-community/template.

Why has it moved?

The React Native Frameworks RFC0759 provides background information.

When was it moved?

The 0.75 release.


Overview (`packages/rn-tester/README.md`)

RNTester

The RNTester showcases React Native views and modules.

Running this app

Before running the app, make sure you ran:

sh
git clone https://github.com/facebook/react-native.git
cd react-native
yarn install

Running on iOS

If you are testing non-fabric component, search for and modify the fabric_enabled flag in RNTester's Podfile.

ruby
fabric_enabled = false

Also, if you previously built RNTester with fabric enabled, you might need to clean up the build files and Pods.

sh
# Clean the generated files and folders to clean install RNTester
cd packages/rn-tester
yarn clean-ios

If you are still having a problem after doing the clean up (which can happen if you have built RNTester with older React Native versions where files were generated inside the react-native folder.), the best way might be to clean-install react-native (e.g. remove node_modules and yarn install). If after cleaning up, you are still having issues, you might also want to try RCT_NEW_ARCH_ENABLED=0 bundle exec pod install to disable the new architecture as it might be conflicting.

Both macOS and Xcode are required.

  1. cd packages/rn-tester
  2. Install Bundler: gem install bundler. We use bundler to install the right version of CocoaPods locally.
  3. Install Bundler and CocoaPods dependencies: bundle install && bundle exec pod install or yarn setup-ios-hermes. In order to use JSC instead of Hermes engine, run: USE_HERMES=0 bundle exec pod install or yarn setup-ios-jsc instead.
  4. Open the generated RNTesterPods.xcworkspace. This is not checked in, as it is generated by CocoaPods. Do not open RNTesterPods.xcodeproj directly.

Note for Apple Silicon users

If you own a Mac laptop with Apple Silicon, you need to run some different commands to install and run cocoapods.

  • sudo arch -x86_64 gem install ffi: this installs the ffi package to load dynamically-linked libraries.
  • arch -x86_64 pod install: this run pod install with the right architecture.

Running on Android

You'll need to have all the prerequisites (SDK, NDK) for Building React Native installed.

You can build and run RN-Tester by using this command from the root of the repo:

sh
yarn android

If you wish to use JSC instead you should invoke:

sh
cd packages/rn-tester
yarn install-android-jsc
yarn start

[!NOTE]
Building for the first time can take a while.

If you're using a physical device, run adb reverse tcp:8081 tcp:8081 to make sure the device can access Metro.

See Running on Device for additional instructions on using a physical device.

Building from source

Building the app on both iOS and Android means building the React Native framework from source. This way you're running the latest native and JS code the way you see it in your clone of the github repo.

This is different from apps created using react-native init which have a dependency on a specific version of React Native JS and native code, declared in a package.json file (and build.gradle for Android apps).


Overview (`packages/typescript-config/README.md`)

@react-native/typescript-config

This package provides the default tsconfig.json used by newly built React Native apps.

This template is customized for specific versions of React Native, and should be updated in sync with the rest of your app.


Overview (`packages/virtualized-lists/README.md`)

@react-native/virtualized-lists

Version

Installation

text
yarn add @react-native/virtualized-lists

Note: We're using yarn to install deps. Feel free to change commands to use npm 3+ and npx if you like

Testing

To run the tests in this package, run the following commands from the React Native root folder:

  1. yarn to install the dependencies. You just need to run this once
  2. yarn jest packages/virtualized-lists.

Overview (`scripts/release-testing/README.md`)

scripts/release-testing

Scripts supporting local manual release testing. See also How to Test a Release.

Commands

For information on command arguments, run node <command> --help.

`test-e2e-local`

Set up, build, and install a given test app configuration.

`test-e2e-local-clean`

Clean up all file system and cache state between tests.


Overview (`scripts/releases-ci/README.md`)

scripts/releases-ci

CI-only release scripts โ€” intended to run from a CI workflow (CircleCI or GitHub Actions).

Commands

For information on command arguments, run node <command> --help.

`prepare-package-for-release`

Prepares files within the react-native package and template for the target release version. Writes a new commit and tag, which will trigger publish-npm.js in a new workflow.

`publish-npm`

Prepares release artifacts and publishes the react-native package to npm.

`publish-updated-packages`

Publishes all updated packages (excluding react-native) to npm. Triggered when a commit on a release branch contains #publish-packages-to-npm.


Overview (`scripts/releases/README.md`)

scripts/releases

Scripts related to creating a React Native release. These are the lower level entry points used by scripts/releases-ci.

Commands

For information on command arguments, run node <command> --help.

`create-release-commit`

Creates a release commit to trigger a new release.

`remove-new-arch-flags`

Updates native build files to disable the New Architecture.

`set-version`

Bump the version of all packages.

  • Updates package.json metadata for all workspaces and the project root.
  • Updates relevant native files in the react-native package.

If --skipReactNativeVersion is passed, the react-native package version will be left unmodified as "1000.0.0" (special static version on main), and native files will not be touched.

`set-rn-artifacts-version`

[!Note]
Deprecated: Prefer set-version. This entry point is a subset of set-version, and is used only by test workflows. We will replace these call sites in future.

Updates relevant native files in the react-native package to materialize the given release version. This is run by set-version unless --skipReactNativeVersion is passed.


Overview (`tools/eslint/README.md`)

react-native/tools/eslint

This directory contains ESLint rules for the react-native repository itself.
They are configured in .eslintrc.js using the eslint-plugin-lint package.

For ESLint rules intended for projects that consume React Native, add them to
the @react-native-community/eslint-plugin package instead.


Overview (`packages/gradle-plugin/react-native-gradle-plugin/README.md`)

React Native Gradle Plugin

This plugin is used by React Native Apps to configure themselves.

NOTE: It's important that this folder is called react-native-gradle-plugin as it's used
by users in their build.gradle file as follows:

gradle
buildscript {
    // ...
    dependencies {
        classpath("com.facebook.react:react-native-gradle-plugin")
    }
}

The name of the artifact is imposed by the folder name.


Overview (`packages/react-native/ReactAndroid/README.md`)

Building React Native for Android

See the Building from Source guide on the React Native website.

Running tests

When you submit a pull request CircleCI will automatically run all tests.
To run tests locally, see Testing guide on the React Native website.


Overview (`packages/react-native/ReactApple/README.md`)

ReactApple

ReactApple contains code to ship React Native apps to Apple devices. The dominant language is Objective-C.

New libraries built with Apple frameworks or intended to ship to Apple devices should live in this directory.


Overview (`packages/react-native/android/README.md`)

The `/android` folder inside `react-native`

Starting from React Native 0.71, we're not shipping the /android folder inside the React Native NPM package
anymore due to sizing constraints on NPM. The Android artifacts are distributed via Maven Central.
You can read more about it in this RFC:
https://github.com/react-native-community/discussions-and-proposals/pull/508

If you're a library author and you're manipulating the React Native .aar files, to extract headers,
extract .so files or do anything with it, you're probably doing something wrong. React Native
0.71 ships with all the necessary logic to let you consume it transparently by just using:

text
implementation("com.facebook.react:react-android")
// or to keep backward compatibility with older versions of React Native:
implementation("com.facebook.react:react-native:+")

You should consider refactoring your library code not to unzip/manipulate the React Native .aar files.

This README.md file is kept in this folder as some libraries are checking the existence of the /android folder
and failing user builds if the folder is missing.


Overview (`packages/react-native/Libraries/Renderer/README.md`)

React & React Native Versions

This page describes how React and React Native versions interact each other.
The version alignment between the two frameworks relies on two synchronization points:

  1. The versions in the package.json of the new app template. For example for React Native 0.68.1 the versions are aligned as follows:
text
"dependencies": {
    "react": "17.0.2",
    "react-native": "0.68.1"
  },
  1. The React renderers shipped with React Native inside this folder, the ./Libraries/Renderer folder, of React Native.

This practically means that you can't bump the version of React in your package.json to a later version,
as you will still be using the older renderer from the folder mentioned above. Bumping the react version in your package.json will lead to unexpected behaviors.

For the sake of React 18, the first version of React Native compatible with React 18 is 0.69.0. Users on React Native 0.68.0 and previous versions won't be able to use React 18.

If you use the react-native upgrade command or the React Native Upgrade Helper, you'll bump to the correct React version once you upgrade React Native.


Overview (`packages/react-native/scripts/featureflags/README.md`)

Feature Flags

Feature flags are values that determine the behavior of specific parts of React
Native. This directory contains the configuration for those values, and scripts
to generate files for different languages to access and customize them.

There are 2 types of feature flags:

  • Common: can be accessed from any language and they provide consistent values
    everywhere.
  • JS-only: they can only be accessed and customized from JavaScript.

Definition

The source of truth for the definition of the flags is the file
ReactNativeFeatureFlags.config.js in this directory.

Example contents:

javascript
module.exports = {
  common: {
    enableNativeBehavior: {
      description: 'Enable some behavior both in native and in JS.',
      defaultValue: false
    }
  },
  jsOnly: {
    enableJSBehavior: {
      description: 'Enables some behavior in the JS layer.',
      defaultValue: false
    }
  }
};

After any change to these definitions, the code that provides access to them
must be regenerated running this from the react-native

shell
yarn featureflags --update

Access

You can access the common feature flags from anywhere in your application using
the ReactNativeFeatureFlags interface (available in C++/Objective-C++,
Kotlin/Java and JavaScript). JS-only feature flags can only be accessed from
JavaScript.

Accessing feature flags should be considered fast for all use cases.
Feature flags are cached at every layer, which prevents having to go through JNI
when accessing the values from Kotlin and through JSI when accessing the values
from JavaScript.

C++ / Objective-C

c++
#include <react/featureflags/ReactNativeFeatureFlags.h>

if (ReactNativeFeatureFlags::enableNativeBehavior()) {
  // do something
}

Kotlin

kotlin
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags

fun someMethod() {
  if (ReactNativeFeatureFlags.enableNativeBehavior()) {
    // do something
  }
}

JavaScript

javascript
import * as ReactNativeFeatureFlags from 'react-native/src/private/featureflags/ReactNativeFeatureFlags';

if (ReactNativeFeatureFlags.enableNativeBehavior()) {
  // Native flag
}

if (ReactNativeFeatureFlags.enableJSBehavior()) {
  // JS-only flag
}

Customization

Feature flags provide the default values defined in the configuration unless
overrides are applied at the application level. Overrides for common feature
flags can only be defined in native, while overrides for JS-ony flags can only
be defined in JavaScript.

Overrides must be applied before any of the available feature flags has been
accessed. This prevents having inconsistent behavior during the lifecycle of the
application.

C++/Objective-C

c++
#include <react/featureflags/ReactNativeFeatureFlags.h>
#include <react/featureflags/ReactNativeFeatureFlagsDefaults.h>

class CustomReactNativeFeatureFlags : public ReactNativeFeatureFlagsDefaults {
 public:
  CustomReactNativeFeatureFlags();

  bool enableNativeBehavior() override {
    return true;
  }
}

ReactNativeFeatureFlags::override(std::make_unique<CustomReactNativeFeatureFlags>());

Kotlin

kotlin
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsDefaults

fun overrideFeatureFlags() {
  ReactNativeFeatureFlags.override(object : ReactNativeFeatureFlagsDefaults() {
    override fun useMicrotasks(): Boolean = true
  })
}

JavaScript

javascript
import * as ReactNativeFeatureFlags from 'react-native/src/private/featureflags/ReactNativeFeatureFlags';

ReactNativeFeatureFlags.override({
  enableJSBehavior: () => true,
});

Architecture

The architecture of this feature flags system can be described as follows:

  • A shared C++ core, where we provide access to the flags and allow
    customizations.
  • A Kotlin/Java interface that allows accessing and customizing the values in
    the C++ core (via JNI).
  • A JavaScript interface that allows accessing the common values (via a native
    module) and accessing and customizing the JS-only values.

This image has an embedded Excalidraw diagram,
so you can upload it there if you need to make further modifications.


Overview (`packages/react-native/ReactApple/Libraries/RCTFoundation/README.md`)

RCTFoundation

RCTFoundation is a collection of lightweight utility libraries.

Rules for RCTFoundation libraries:

  • They must only depend on other RCTFoundation libraries.
  • Headers cannot contain C++.
  • They have modular set to true in BUCK.
  • They have complete_nullability set to true.
  • They have enabled Clang compiler warnings.
  • They have documentation.
  • They have unit tests.

Overview (`packages/react-native/ReactCommon/react/runtime/README.md`)

Bridgeless Mode for iOS

This library is not ready for integration for production nor local experimentation. Expect breaking changes regularly if you use any of these APIs. Use at your own risk!


Overview (`packages/react-native/ReactApple/Libraries/RCTFoundation/RCTDeprecation/README.md`)

RCTDeprecation contains C macros to identify deprecated APIs at build-time.


Overview (`packages/react-native/ReactCommon/react/nativemodule/devtoolsruntimesettings/README.md`)

Options for DevTools Settings

Module Survives native restarts Survives JavaScript VM restarts
DevToolsRuntimeSettings No Yes
DevToolsSettings Yes Yes

Overview (`packages/rn-tester/js/examples/Experimental/PlatformTest/README.md`)

RNTester PlatformTest

A barebones manual testing framework designed to work as a mechanism for recreating Web Platform Tests in React Native in order to verify their compliance with W3C specifications.

Usage

Any new test case will start as a new React component which at the very least accepts a harness prop which will contain all of the framework's testing APIs. This component you write will be passed into the component prop of a RNTesterPlatformTest element whose other props are used for documenting your test. Rendering this RNTesterPlatformTest will look similar to something like this:

js
function ExampleTestCase ({ harness }) { /* ... */ }

<RNTesterPlatformTest
  title="Example Test"
  description="Imagine there's a detailed description of this example test here"
  instructions={[
    "This is the example test's first step",
    "A second step",
    "A third step",
  ]}
  component={ExampleTestCase}
/>

As of writing this README there are 2 different types of tests that the harness prop provides:

`test(testcase: (TestContext) => void, testName: string, options?: TestOptions)`

This is a method to create "regular" test reminiscent of other frameworks such as Jest. These are meant to be run imperatively, and while that means that they technically could work in a useEffect hook as a way to run the test "on mount" โ€” it is instead recommended to try and keep these tests in callbacks instead. A good alternative to running the test on mount would be to instead put the test in a callback and render a "Start Test" button which executes the callback.

The first argument is the closure in which you will run your test and make assertions. The assertions are contained in the TestContext object which is provided in the test closure's first argument and contains the following assertions:

  • assert_true(a: boolean, description: string): void
  • assert_equals(a: any, b: any, description: string): void
  • assert_greater_than_equal(a: number, b: number, description: string): void
  • assert_less_than_equal(a: number, b: number, description: string): void

An optional third argument can be used for specifying additional options to the test โ€” that object currently has the following properties (all of which are optional themselves):

  • skip: boolean: In cases where we want the test to be registered but we don't want it to contribute to the pass/fail count.

Here's what a basic/contrived example which verifies the layout of a basic view:

js
const EXPECTED_WIDTH = 100;
const EXPECTED_HEIGHT = 200;

function BasicLayoutTestCase({harness}) {
  const viewRef = useRef(null);

  const runTest = useCallback(() => {
    const view = viewRef.current;
    if (view != null) {
      view.measureInWindow(({width, height}) => {
        harness.test(({assert_equals}) => {
          assert_equals(
            width,
            EXPECTED_WIDTH,
            `view's computed width should be ${EXPECTED_WIDTH}`,
          );
          assert_equals(
            height,
            EXPECTED_HEIGHT,
            `view's computed width should be ${EXPECTED_HEIGHT}`,
          );
        }, "view's width and height are correct");
      });
    }
  }, [harness]);

  return (
    <>
      <View
        ref={viewRef}
        style={{width: EXPECTED_WIDTH, height: EXPECTED_HEIGHT}}
      />
      <Button title="Start Test" onPress={runTest} />
    </>
  );
}

`useAsyncTest(description: string, timeoutMs?: number): AsyncPlatformTest`

This is a hook which can be used to represent tests that expect something to happen some time in the future. If the test isn't marked as "done" within a certain amount of time (10 seconds by default but can be optionally specified in the hook's second argument). This hook returns an object containing a done function which is used for marking the completion of the async test.

Here's what a basic example would look like for verifying that pointermove events are emitted:

js
function BasicPointerMoveTestCase({harness}) {
  const testPointerMove = harness.useAsyncTest('pointermove event received');

  return (
    <View
      style={{width: 100, height: 100, backgroundColor: 'black'}}
      onPointerMove={() => testPointerMove.done()}
    />
  );
}

Overview (`packages/react-native/ReactAndroid/src/main/jni/first-party/jni-hack/README.md`)

This buck module exists so that targets that need to be built against both 1) Android (where we can and should use the Android NDK jni headers) and 2) the host platform(generally for local unit tests) can depend on a single target and get the right jni header for whatever platform they're building against automatically.


Overview (`packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/README.md`)

Bridgeless Mode for Android

This library is not ready for integration for production nor local experimentation. Expect breaking changes regularly if you use any of these APIs. Use at your own risk!


--- METRICS ---