Перейти к содержимому

Как запустить чужой файл через react native

  • автор:

React Native

With React Native you can develop native mobile applications for iOS and Android using JavaScript and React. It is created by Facebook and used for such well-known apps as Instagram, Airbnb, and now JetBrains’ own YouTrack mobile application. Learn more from the React Native official website.

WebStorm helps you create, edit, lint, run, debug, and maintain your React Native applications. WebStorm also provides code completion for React and Flow symbols.

Before you start

  1. Make sure you have Node.js on your computer.
  2. Make sure the JavaScript Debugger plugin is enabled in the settings. Press Control+Alt+S to open the IDE settings and then select Plugins . Click the Installed tab. In the search field, type JavaScript Debugger . For more information about plugins, refer to Managing plugins.

Creating a new React Native application

The recommended way to create a React Native application in WebStorm is to use a dedicated project generator, for example, the React Native CLI.

Creating a React Native app

  1. Click Create New Project on the Welcome screen or select File | New | Project from the main menu. The New Project dialog opens.
  2. In the left-hand pane, choose React Native .
  3. In the right-hand pane:
    1. Specify The path to the folder where the project-related files will be stored.
    2. In the Node Interpreter field, specify the Node.js interpreter to use. Select a configured interpreter from the list or choose Add to configure a new one.
    3. From the React Native list, select npx —package react-native-cli react-native . Alternatively, for npm version 5.1 and earlier, install the react-native-cli package yourself by running npm install -g react-native-cli in the Terminal Alt+F12 . When creating an application, select the folder where the react-native-cli package is stored.
  4. When you click Create , WebStorm generates a React Native -specific project with all the required configuration files, downloads the dependencies, and creates a run/debug configuration of the type React Native with default settings..
  5. Install other tools to get started with React Native, for example, an iOS simulator. The list of these tools depends on your operating system and the mobile platform you are going to target your application at. See React Native Getting Started guide for detailed installation instructions.

Starting with an existing React Native application

To continue developing an existing React Native application, open it in WebStorm and download the required dependencies.

Open the application sources that are already on your machine

  • Click Open on the Welcome screen or select File | Open from the main menu. In the dialog that opens, select the folder where your sources are stored.

Check out the application sources from your version control

  1. Click Get from VCS on the Welcome screen. Alternatively, select File | New | Project from Version Control or Git | Clone… from the main menu. Instead of Git in the main menu, you may see any other Version Control System that is associated with your project. For example, Mercurial or Perforce .
  2. In the dialog that opens, select your version control system from the list and specify the repository to check out the application sources from. For more information, refer to Check out a project (clone).

Download the dependencies

Opening an Angular application and downloading the dependencies from package.json

  1. Click Run ‘npm install’ or Run ‘yarn install’ in the popup: You can use npm, Yarn 1, or Yarn 2, refer to npm and Yarn for details.
  2. Select Run ‘npm install’ or Run ‘yarn install’ from the context menu of package.json in the editor or in the Project tool window.

Exclude the android and iOS folders from the project

ws_react_native_mark_as_excluded.png

  1. In the Project tool window, select the android or the iOS folder.
  2. From the context menu of the selection, choose Mark Directory As , and then choose Excluded .

Install other tools to get started with React Native, for example, an iOS simulator. The list of these tools depends on your operating system and the mobile platform you are going to target your application at. See React Native Getting Started guide for detailed installation instructions.

Project security

When you open a project that was created outside WebStorm and was imported into it, WebStorm displays a dialog where you can decide how to handle this project with unfamiliar source code.

Untrusted project warning

Select one of the following options:

  • Preview in Safe Mode : in this case, WebStorm opens the project in a preview mode. It means that you can browse the project’s sources but you cannot run tasks and script or run/debug your project. WebStorm displays a notification on top of the editor area, and you can click the Trust project… link and load your project at any time.
  • Trust Project : in this case, WebStorm opens and loads a project. That means the project is initialized, project’s plugins are resolved, dependencies are added, and all WebStorm features are available.
  • Don’t Open : in this case, WebStorm doesn’t open the project.

Projects created from the Welcome screen or via File | New | Project as described in Creating projects are automatically considered trusted.

Coding assistance

WebStorm provides code completion for React APIs and JSX in JavaScript code. Code completion works for React methods, React-specific attributes, HTML tags and component names, React events, component properties, and so on. See React: Completing Code for more information.

Code completion for React Native StyleSheet properties is also available:

Completion for React Native StyleSheet properties

If you are using Flow in your project, WebStorm can highlight the errors from this type checker in the editor. For more information, refer to Configuring Flow in WebStorm and Using Flow in WebStorm.

Running and debugging a React Native application

You can run and debug your application on a physical device or on a simulator. Before you launch your application, make sure that the simulator is already running or, if you are using a physical device, it is already connected to your computer.

WebStorm makes running and debugging React Native applications very flexible. For example, if you are starting your application for the first time, you can choose to run the React Native bundler, build the application, and open it on the simulator — all that as part of a running or debugging session. You can also skip launching the bundler if it is already running or refuse building the application if you have not made any changes to its native code since the previous run.

Create a React Native run/debug configuration

  1. Select Run | Edit Configurations from the menu, click the Add New Configuration button () and select React Native from the list to open the configuration settings .
  2. Choose whether you want WebStorm to build and launch the application for you:
    • Select the Build and launch checkbox if you are launching your application for the first time or if you have updated its native code since the last run.
    • Clear this checkbox if you haven’t made any changes to the native code of your application since the last build. When you start debugging, WebStorm waits for you to open your application in the simulator with the Remote debug enabled as described on the React Native official website
    • If your application uses Expo, clear the checkbox because this bundler takes care of the process itself. See Debug a React Native application that uses Expo.
  3. If you selected the Build and launch checkbox, choose the target platform, Android or iOS. Depending on your choice, WebStorm will run the bundler with react-native run-ios or with react-native run-android .
    • To emulate the Android platform, use an Android virtual device .
    • To emulate the iOS platform, you need to install the ios-sim command-line tool globally. You can do it through the Node Package Manager (npm) , refer to npm, pnpm, and Yarn, or by running the sudo npm install ios-sim -g command, depending on your operating system.

Optionally, in the Arguments field, type the arguments to be passed to React Native , for example, specify the simulator type through the ‑‑simulator flag: ‑‑simulator=»iPhone 4s» .

React Native Run/Debug Configuration

  • Specify the browser to use. In debugging React Native applications, WebStorm relies on the Chrome runtime, which is used by React Native itself. You can also use DevTools together with WebStorm. When you initiate a debugging session, WebStorm starts a new Chrome instance and attaches to it. If you don’t want to see any new Chrome windows, use the Chrome Headless mode.
  • In the Bundler host field, specify the host where the React Native bundler runs, the default value is localhost . If you are using Expo, you may need to change the default bundler host to ensure successful connection with the debugger. This connection may fail because WebStorm by default uses localhost to start debugging while Expo expects 127.0.0.1 or an external IP address depending on what is selected in Connection field of the Metro bundler configuration. For more information, refer to Debugging a React Native application that uses Expo.
  • In the Bundler port field, specify the port on which the React Native bundler runs, by default 8081 is chosen, learn more from the React Native official website. If your application uses Expo, you may need to change the port to 19000 or 19001 , depending on the Expo configuration. See Debug a React Native application that uses Expo below.
  • Specify the Node.js interpreter to use. If you choose the Project alias, WebStorm will automatically use the project default interpreter from the Node interpreter field on the Node.js page . In most cases, WebStorm detects the project default interpreter and fills in the field itself. You can also choose another configured local or remote interpreter or click and configure a new one. For more information, refer to Configuring remote Node.js interpreters, Configuring a local Node.js interpreter, and Using Node.js on Windows Subsystem for Linux.
  • Specify the path to react-native-cli and the working directory of the application. Optionally, type the environment variables for react-native run-android or react-native run-ios .
  • By default, WebStorm starts the React Native bundler automatically when you invoke the run/debug configuration. If you have already started the bundler from outside WebStorm, for example, from the command line, you can re-use it without stopping and restarting. Select your bundler in the Before Launch area and click .
  • For more information about the settings that are common for all run/debug configurations, see Run/debug configurations.

    Prepare a device or a simulator

    If you are using an Android device, you need to prepare it every time you start working with an application.

    An iOS simulator has to be installed only once, after that WebStorm starts it automatically with react-native run-ios .

    • To prepare an Android device, launch an Android virtual device or enable debugging over USB and connect to a physical Android device via USB. Learn more from the React Native official website.
    • To prepare an iOS simulator, open the embedded Terminal ( Alt+F12 ) and type: npm install —global ios-sim

    Run an application

    React Native packager is running

    • Select the newly created React Native configuration from the Select run/debug configuration list on the toolbar and click the Run button () next to the list. WebStorm opens the Run tool window and first starts the React Native bundler in a new React Native tab. After that, the react-native run-ios or react-native run-android command is executed, depending on the selected target platform. If the build is successful, the simulator shows your application:

    Debugging an application

    With WebStorm, you can debug applications that use the native React Native bundler and those that use Expo.

    In debugging React Native applications, WebStorm relies on the Chrome runtime, which is used by React Native itself. You can also use DevTools together with WebStorm. When you initiate a debugging session, WebStorm starts a new Chrome instance and attaches to it. If you don’t want to see any new Chrome windows, use the Chrome Headless mode.

    Debug a React Native application that uses a native bundler
    1. Set the breakpoints in your code as required.
    2. Create a new React Native run/debug configuration as described above. If the bundler is already running outside WebStorm, select it in the Before Launch area and click the Remove button ().
    3. To start your application, select the newly created React Native configuration from the Select run/debug configuration list on the toolbar and click the Run button () next to the list. WebStorm opens the Run tool window and runs the bundler in a new React Native tab.
    4. When the build is completed and the application appears in the simulator, open the In-App Developer Menu and choose Debug JS Remotely . Learn more from the React official website. The React Native app is running on the simulatorThe built-in WebStorm debugger connects to the simulator.
    5. When the first breakpoint is hit, proceed with the debugging session — step through the breakpoints, switch between frames, change values on-the-fly, examine a suspended program, evaluate expressions, and set watches. React Native debugging session
    Debug a React Native application that uses Expo

    With WebStorm, you can start debugging such React Native applications in several ways:

    • In the scripts section of your package.json file, create a script that runs Expo. Then specify this script as a Before launch task in the React Native run/debug configuration.
    • First run Expo manually or via a script from package.json and then initiate a debugging session without any Expo-related Before launch tasks .

    In either case, you may need to change the default bundler port, depending on how Expo is configured.

    1. Open your package.json file, locate the scripts section, and add a script that launches Expo.
    2. Set the breakpoints in your code as required.
    3. Create a new React Native run/debug configuration as described above and change the default settings as follows:
      1. Clear the Build and launch checkbox because this bundler takes care of the process itself.
      2. In the Bundler host field, change the default localhost setting to 127.0.0.1 or an external IP address depending on what is selected in Connection field of the Metro bundler configuration.
      3. In the Bundler port field, change the default 8081 setting to 19000 or 19001 , depending on the Expo configuration.
      4. In the Before launch area, select the default Start React Native Bundler task and click the Remove button (). React Native Debug configuration for debugging with Expo: Remove default Start bundler taskTo start Expo via a script automatically, click the Add button () and select Run npm script from the list. React Native Debug configuration for debugging with Expo: Add Run npm script taskIn the NPM Script dialog, select the npm script that starts Expo. React Native Debug configuration for debugging with Expo: Select npm script to run Expo
    4. Select the newly created configuration from the Select run/debug configuration list on the toolbar and click the Debug button () next to the list.
    5. Open your Expo client application on your phone or simulator, select the current application, and enable remote debugging, learn more from the Expo official website.
    6. When the first breakpoint is hit, proceed as when debugging an application that uses a native bundler.
    Configure Chrome Headless in WebStorm

    The Headless mode is supported for Chrome versions 59 and later on macOS and Linux and for versions 60 and later on Windows.

    1. Select Run | Edit Configurations from the main menu.
    2. In the Run/Debug Configurations dialog, select a React Native configuration,
    3. Next to the Browser for debugging field, click the Browse button (). The Web Browsers and Preview dialog opens.
    4. Select Chrome , click the Copy (), and rename the copied configuration, for example, to Chrome Headless .
    5. Select the new browser configuration, click the Edit button (), and type —headless for macOS and Linux or —headless —disable-gpu for Windows in the Chrome Settings dialog.
    6. In the run/debug configuration, choose the new Chrome Headless configuration from the Browser for debugging list.

    React Fundamentals

    React Native runs on React, a popular open source library for building user interfaces with JavaScript. To make the most of React Native, it helps to understand React itself. This section can get you started or can serve as a refresher course.

    We’re going to cover the core concepts behind React:

    If you want to dig deeper, we encourage you to check out React’s official documentation.

    Your first component​

    The rest of this introduction to React uses cats in its examples: friendly, approachable creatures that need names and a cafe to work in. Here is your very first Cat component:

    Here is how you do it: To define your Cat component, first use JavaScript’s import to import React and React Native’s Text Core Component:

    import React from 'react'; import Text> from 'react-native'; 

    Your component starts as a function:

    const Cat = () => >; 

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

    Here the Cat component will render a element:

    const Cat = () =>   return Text>Hello, I am your cat!Text>; >; 

    You can export your function component with JavaScript’s export default for use throughout your app like so:

    const Cat = () =>   return Text>Hello, I am your cat!Text>; >;  export default Cat; 

    This is one of many ways to export your component. This kind of export works well with the Snack Player. However, depending on your app’s file structure, you might need to use a different convention. This handy cheatsheet on JavaScript imports and exports can help.

    Now take a closer look at that return statement. Hello, I am your cat! is using a kind of JavaScript syntax that makes writing elements convenient: JSX.

    JSX​

    React and React Native use JSX, a syntax that lets you write elements inside JavaScript like so: Hello, I am your cat! . The React docs have a comprehensive guide to JSX you can refer to learn even more. Because JSX is JavaScript, you can use variables inside it. Here you are declaring a name for the cat, name , and embedding it with curly braces inside .

    Any JavaScript expression will work between curly braces, including function calls like :

    • TypeScript
    • JavaScript

    You can think of curly braces as creating a portal into JS functionality in your JSX!

    Because JSX is included in the React library, it won’t work if you don’t have import React from ‘react’ at the top of your file!

    Custom Components​

    You’ve already met React Native’s Core Components. React lets you nest these components inside each other to create new components. These nestable, reusable components are at the heart of the React paradigm.

    For example, you can nest Text and TextInput inside a View below, and React Native will render them together:

    Developer notes​

    If you’re familiar with web development, and might remind you of HTML! You can think of them as the and

    tags of application development.

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

    You can render this component multiple times and in multiple places without repeating your code by using :

    Any component that renders other components is a parent component. Here, Cafe is the parent component and each Cat is a child component.

    You can put as many cats in your cafe as you like. Each renders a unique element—which you can customize with props.

    Props​

    Props is short for “properties”. Props let you customize React components. For example, here you pass each a different name for Cat to render:

    • TypeScript
    • JavaScript

    Most of React Native’s Core Components can be customized with props, too. For example, when using Image , you pass it a prop named source to define what image it shows:

    Image has many different props, including style , which accepts a JS object of design and layout related property-value pairs.

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

    You can build many things with props and the Core Components Text , Image , and View ! But to build something interactive, you’ll need state.

    State​

    While you can think of props as arguments you use to configure how components render, state is like a component’s personal data storage. State is useful for handling data that changes over time or that comes from user interaction. State gives your components memory!

    As a general rule, use props to configure a component when it renders. Use state to keep track of any component data that you expect to change over time.

    The following example takes place in a cat cafe where two hungry cats are waiting to be fed. Their hunger, which we expect to change over time (unlike their names), is stored as state. To feed the cats, press their buttons—which will update their state.

    You can add state to a component by calling React’s useState Hook. A Hook is a kind of function that lets you “hook into” React features. For example, useState is a Hook that lets you add state to function components. You can learn more about other kinds of Hooks in the React documentation.

    • TypeScript
    • JavaScript

    Как клонировать create-react-app и запустить на локалке?

    На сайте с документацией я не нашел инфу про клонирование.

    Или я плохо искал?

    • Вопрос задан более трёх лет назад
    • 3700 просмотров

    Комментировать
    Решения вопроса 1
    inflexible @inflexible

    ну. npm init выполнять не нужно было) в клонированном проекте уже должен быть package.json в котором есть список зависимостей! выполняете npm install, чтобы установить все зависимости которые есть в проекте! дальше выполняете npm start или npm build (смотря что вам нужно)! но прежде чем запускать — зайдите в package.json и убедитесь что эти команды присутствуют в свойстве «scripts», возможно командой npm init вы обнулили файл)

    p.s. По клонированию ничего особо искать не нужно! Его можно сделать командой «git clone gitproject» или просто скачать архив и распаковать, это вообще не играет роли! Просто его origin будет ссылаться на этот «родительский» репозиторий! Но нужно понимать что папки node_modules не будет, поэтому после клонирования обьязательно нужно выполнить npm install!

    Integration with Existing Apps

    React Native is great when you are starting a new mobile app from scratch. However, it also works well for adding a single view or user flow to existing native applications. With a few steps, you can add new React Native based features, screens, views, etc.

    The specific steps are different depending on what platform you’re targeting.

    • Android (Kotlin)
    • Android (Java)
    • iOS (Objective-C)
    • iOS (Swift)

    Key Concepts​

    The keys to integrating React Native components into your Android application are to:

    1. Set up React Native dependencies and directory structure.
    2. Develop your React Native components in JavaScript.
    3. Add a ReactRootView to your Android app. This view will serve as the container for your React Native component.
    4. Start the React Native server and run your native application.
    5. Verify that the React Native aspect of your application works as expected.

    Prerequisites​

    Follow the React Native CLI Quickstart in the environment setup guide to configure your development environment for building React Native apps for Android.

    1. Set up directory structure​

    To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing Android project to an /android subfolder.

    2. Install JavaScript dependencies​

    Go to the root directory for your project and create a new package.json file with the following contents:

      "name": "MyReactNativeApp", "version": "0.0.1", "private": true, "scripts":   "start": "yarn react-native start" > > 

    Next, install the react and react-native packages. Open a terminal or command prompt, then navigate to the directory with your package.json file and run:

    npm install react-native 
    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.70.5 » has unmet peer dependency » react@18.1.0 «

    This is OK, it means we also need to install React:

    npm install react@version_printed_above 
    yarn add react@version_printed_above 

    Yarn has created a new /node_modules folder. This folder stores all the JavaScript dependencies required to build your project.

    Add node_modules/ to your .gitignore file.

    Adding React Native to your app​

    Configuring Gradle​

    React Native uses the React Native Gradle Plugin to configure your dependencies and project setup.

    First, let’s edit your settings.gradle file by adding this line:

    includeBuild('../node_modules/@react-native/gradle-plugin') 

    Then you need to open your top level build.gradle and include this line:

    buildscript   repositories   google()  mavenCentral()  >  dependencies   classpath("com.android.tools.build:gradle:7.3.1") + classpath("com.facebook.react:react-native-gradle-plugin")  > > 

    This makes sure the React Native Gradle Plugin 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):

    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.

    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​

    To use the power of autolinking, we have to apply it a few places. First add the following entry to settings.gradle :

    apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 

    Next add the following entry at the very bottom of the app/build.gradle :

    apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) 

    Configuring permissions​

    Next, make sure you have the Internet permission in your AndroidManifest.xml :

    uses-permission android:name="android.permission.INTERNET" /> 

    If you need to access to the DevSettingsActivity add to your AndroidManifest.xml :

    activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /> 

    This is only used in dev mode when reloading JavaScript from the development server, so you can strip this in release builds if you need to.

    Cleartext Traffic (API level 28+)​

    Starting with Android 9 (API level 28), cleartext traffic is disabled by default; this prevents your application from connecting to the Metro bundler. The changes below allow cleartext traffic in debug builds.

    1. Apply the usesCleartextTraffic option to your Debug AndroidManifest.xml ​

    application android:usesCleartextTraffic=«true« tools:targetApi=«28« > application>

    This is not required for Release builds.

    To learn more about Network Security Config and the cleartext traffic policy see this link.

    Code integration​

    Now we will actually modify the native Android application to integrate React Native.

    The React Native component​

    The first bit of code we will write is the actual React Native code for the new «High Score» screen that will be integrated into our application.

    1. Create a index.js file​

    First, create an empty index.js file in the root of your React Native project.

    index.js is the starting point for React Native applications, and it is always required. It can be a small file that require s other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will put everything in index.js .

    2. Add your React Native code​

    In your index.js , create your component. In our sample here, we will add a component within a styled :

    import React from 'react'; import AppRegistry, StyleSheet, Text, View> from 'react-native';  const HelloWorld = () =>   return ( View style=styles.container>> Text style=styles.hello>>Hello, WorldText> View> ); >; const styles = StyleSheet.create(  container:   flex: 1, justifyContent: 'center', >, hello:   fontSize: 20, textAlign: 'center', margin: 10, >, >);  AppRegistry.registerComponent( 'MyReactNativeApp', () => HelloWorld, ); 
    3. Configure permissions for development error overlay​

    If your app is targeting the Android API level 23 or greater, make sure you have the permission android.permission.SYSTEM_ALERT_WINDOW enabled for the development build. You can check this with Settings.canDrawOverlays(this) . This is required in dev builds because React Native development errors must be displayed above all the other windows. Due to the new permissions system introduced in the API level 23 (Android M), the user needs to approve it. This can be achieved by adding the following code to your Activity’s in onCreate() method.

    companion object   const val OVERLAY_PERMISSION_REQ_CODE = 1 // Choose any value >  ...  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)   if(!Settings.canDrawOverlays(this))   val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,  Uri.parse("package: $packageName")) startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE); > > 

    Finally, the onActivityResult() method (as shown in the code below) has to be overridden to handle the permission Accepted or Denied cases for consistent UX. Also, for integrating Native Modules which use startActivityForResult , we need to pass the result to the onActivityResult method of our ReactInstanceManager instance.

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)   if (requestCode == OVERLAY_PERMISSION_REQ_CODE)   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)   if (!Settings.canDrawOverlays(this))   // SYSTEM_ALERT_WINDOW permission not granted > > >  reactInstanceManager?.onActivityResult(this, requestCode, resultCode, data) > 
    The Magic: ReactRootView ​

    Let’s add some native code in order to start the React Native runtime and tell it to render our JS component. To do this, we’re going to create an Activity that creates a ReactRootView , starts a React application inside it and sets it as the main content view.

    class MyReactActivity : Activity(), DefaultHardwareBackBtnHandler   private lateinit var reactRootView: ReactRootView private lateinit var reactInstanceManager: ReactInstanceManager override fun onCreate(savedInstanceState: Bundle?)   super.onCreate(savedInstanceState)  SoLoader.init(this, false)  reactRootView = ReactRootView(this) val packages: ListReactPackage> = PackageList(application).packages // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(MyReactNativePackage()) // Remember to include them in `settings.gradle` and `app/build.gradle` too.  reactInstanceManager = ReactInstanceManager.builder() .setApplication(application) .setCurrentActivity(this) .setBundleAssetName("index.android.bundle") .setJSMainModulePath("index") .addPackages(packages) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .build() // The string here (e.g. "MyReactNativeApp") has to match // the string in AppRegistry.registerComponent() in index.js  reactRootView?.startReactApplication(reactInstanceManager, "MyReactNativeApp", null) setContentView(reactRootView) >  override fun invokeDefaultOnBackPressed()   super.onBackPressed() > > 

    If you are using a starter kit for React Native, replace the «HelloWorld» string with the one in your index.js file (it’s the first argument to the AppRegistry.registerComponent() method).

    Perform a “Sync Project files with Gradle” operation.

    If you are using Android Studio, use Alt + Enter to add all missing imports in your MyReactActivity class. Be careful to use your package’s BuildConfig and not the one from the facebook package.

    We need set the theme of MyReactActivity to Theme.AppCompat.Light.NoActionBar because some React Native UI components rely on this theme.

    activity android:name=".MyReactActivity" android:label="@string/app_name" android:theme="@style/Theme.AppCompat.Light.NoActionBar"> activity> 

    A ReactInstanceManager can be shared by multiple activities and/or fragments. You will want to make your own ReactFragment or ReactActivity and have a singleton holder that holds a ReactInstanceManager . When you need the ReactInstanceManager (e.g., to hook up the ReactInstanceManager to the lifecycle of those Activities or Fragments) use the one provided by the singleton.

    Next, we need to pass some activity lifecycle callbacks to the ReactInstanceManager and ReactRootView :

    override fun onPause()   super.onPause()  reactInstanceManager.onHostPause(this) >  override fun onResume()   super.onResume()  reactInstanceManager.onHostResume(this, this) >  override fun onDestroy()   super.onDestroy()  reactInstanceManager.onHostDestroy(this)  reactRootView.unmountReactApplication() > 

    We also need to pass back button events to React Native:

    override fun onBackPressed()   reactInstanceManager.onBackPressed() super.onBackPressed() > 

    This allows JavaScript to control what happens when the user presses the hardware back button (e.g. to implement navigation). When JavaScript doesn’t handle the back button press, your invokeDefaultOnBackPressed method will be called. By default this finishes your Activity .

    Finally, we need to hook up the dev menu. By default, this is activated by (rage) shaking the device, but this is not very useful in emulators. So we make it show when you press the hardware menu button (use Ctrl + M if you’re using Android Studio emulator):

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean   if (keyCode == KeyEvent.KEYCODE_MENU && reactInstanceManager != null)   reactInstanceManager.showDevOptionsDialog() return true > return super.onKeyUp(keyCode, event) > 

    Now your activity is ready to run some JavaScript code.

    Test your integration​

    You have now done all the basic steps to integrate React Native with your current application. Now we will start the Metro bundler to build the index.bundle package and the server running on localhost to serve it.

    1. Run the packager​

    To run your app, you need to first start the development server. To do this, run the following command in the root directory of your React Native project:

    npm start 
    yarn start 
    2. Run the app​

    Now build and run your Android app as normal.

    Once you reach your React-powered activity inside the app, it should load the JavaScript code from the development server and display:

    Creating a release build in Android Studio​

    You can use Android Studio to create your release builds too! It’s as quick as creating release builds of your previously-existing native Android app.

    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:

    $ 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/ 

    Don’t forget to replace the paths with correct ones and create the assets folder if it doesn’t exist.

    Now, create a release build of your native app from within Android Studio as usual and you should be good to go!

    Now what?​

    At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native.

    Key Concepts​

    The keys to integrating React Native components into your Android application are to:

    1. Set up React Native dependencies and directory structure.
    2. Develop your React Native components in JavaScript.
    3. Add a ReactRootView to your Android app. This view will serve as the container for your React Native component.
    4. Start the React Native server and run your native application.
    5. Verify that the React Native aspect of your application works as expected.

    Prerequisites​

    Follow the React Native CLI Quickstart in the environment setup guide to configure your development environment for building React Native apps for Android.

    1. Set up directory structure​

    To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing Android project to an /android subfolder.

    2. Install JavaScript dependencies​

    Go to the root directory for your project and create a new package.json file with the following contents:

      "name": "MyReactNativeApp", "version": "0.0.1", "private": true, "scripts":   "start": "react-native start" > > 

    Next, install the react and react-native packages. Open a terminal or command prompt, then navigate to the directory with your package.json file and run:

    npm install react-native 
    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.70.5 » has unmet peer dependency » react@18.1.0 «

    This is OK, it means we also need to install React:

    npm install react@version_printed_above 
    yarn add react@version_printed_above 

    Yarn has created a new /node_modules folder. This folder stores all the JavaScript dependencies required to build your project.

    Add node_modules/ to your .gitignore file.

    Adding React Native to your app​

    Configuring Gradle​

    React Native uses the React Native Gradle Plugin to configure your dependencies and project setup.

    First, let’s edit your settings.gradle file by adding this line:

    includeBuild('../node_modules/@react-native/gradle-plugin') 

    Then you need to open your top level build.gradle and include this line:

    buildscript   repositories   google()  mavenCentral()  >  dependencies   classpath("com.android.tools.build:gradle:7.3.1") + classpath("com.facebook.react:react-native-gradle-plugin")  > > 

    This makes sure the React Native Gradle Plugin 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):

    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.

    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​

    To use the power of autolinking, we have to apply it a few places. First add the following entry to settings.gradle :

    apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 

    Next add the following entry at the very bottom of the app/build.gradle :

    apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) 

    Configuring permissions​

    Next, make sure you have the Internet permission in your AndroidManifest.xml :

    uses-permission android:name="android.permission.INTERNET" /> 

    If you need to access to the DevSettingsActivity add to your AndroidManifest.xml :

    activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /> 

    This is only used in dev mode when reloading JavaScript from the development server, so you can strip this in release builds if you need to.

    Cleartext Traffic (API level 28+)​

    Starting with Android 9 (API level 28), cleartext traffic is disabled by default; this prevents your application from connecting to the Metro bundler. The changes below allow cleartext traffic in debug builds.

    1. Apply the usesCleartextTraffic option to your Debug AndroidManifest.xml ​

    application android:usesCleartextTraffic=«true« tools:targetApi=«28« > application>

    This is not required for Release builds.

    To learn more about Network Security Config and the cleartext traffic policy see this link.

    Code integration​

    Now we will actually modify the native Android application to integrate React Native.

    The React Native component​

    The first bit of code we will write is the actual React Native code for the new «High Score» screen that will be integrated into our application.

    1. Create a index.js file​

    First, create an empty index.js file in the root of your React Native project.

    index.js is the starting point for React Native applications, and it is always required. It can be a small file that require s other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will put everything in index.js .

    2. Add your React Native code​

    In your index.js , create your component. In our sample here, we will add a component within a styled :

    import React from 'react'; import AppRegistry, StyleSheet, Text, View> from 'react-native';  const HelloWorld = () =>   return ( View style=styles.container>> Text style=styles.hello>>Hello, WorldText> View> ); >; const styles = StyleSheet.create(  container:   flex: 1, justifyContent: 'center', >, hello:   fontSize: 20, textAlign: 'center', margin: 10, >, >);  AppRegistry.registerComponent( 'MyReactNativeApp', () => HelloWorld, ); 
    3. Configure permissions for development error overlay​

    If your app is targeting the Android API level 23 or greater, make sure you have the permission android.permission.SYSTEM_ALERT_WINDOW enabled for the development build. You can check this with Settings.canDrawOverlays(this); . This is required in dev builds because React Native development errors must be displayed above all the other windows. Due to the new permissions system introduced in the API level 23 (Android M), the user needs to approve it. This can be achieved by adding the following code to your Activity’s in onCreate() method.

    private final int OVERLAY_PERMISSION_REQ_CODE = 1; // Choose any value  ...  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)   if (!Settings.canDrawOverlays(this))   Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE); > > 

    Finally, the onActivityResult() method (as shown in the code below) has to be overridden to handle the permission Accepted or Denied cases for consistent UX. Also, for integrating Native Modules which use startActivityForResult , we need to pass the result to the onActivityResult method of our ReactInstanceManager instance.

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data)   if (requestCode == OVERLAY_PERMISSION_REQ_CODE)   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)   if (!Settings.canDrawOverlays(this))   // SYSTEM_ALERT_WINDOW permission not granted > > >  mReactInstanceManager.onActivityResult( this, requestCode, resultCode, data ); > 
    The Magic: ReactRootView ​

    Let’s add some native code in order to start the React Native runtime and tell it to render our JS component. To do this, we’re going to create an Activity that creates a ReactRootView , starts a React application inside it and sets it as the main content view.

    public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler   private ReactRootView mReactRootView; private ReactInstanceManager mReactInstanceManager;  @Override protected void onCreate(Bundle savedInstanceState)   super.onCreate(savedInstanceState); SoLoader.init(this, false);  mReactRootView = new ReactRootView(this); ListReactPackage> packages = new PackageList(getApplication()).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); // Remember to include them in `settings.gradle` and `app/build.gradle` too.  mReactInstanceManager = ReactInstanceManager.builder() .setApplication(getApplication()) .setCurrentActivity(this) .setBundleAssetName("index.android.bundle") .setJSMainModulePath("index") .addPackages(packages) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .build(); // The string here (e.g. "MyReactNativeApp") has to match // the string in AppRegistry.registerComponent() in index.js  mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);  setContentView(mReactRootView); >  @Override public void invokeDefaultOnBackPressed()   super.onBackPressed(); > > 

    If you are using a starter kit for React Native, replace the «HelloWorld» string with the one in your index.js file (it’s the first argument to the AppRegistry.registerComponent() method).

    Perform a “Sync Project files with Gradle” operation.

    If you are using Android Studio, use Alt + Enter to add all missing imports in your MyReactActivity class. Be careful to use your package’s BuildConfig and not the one from the facebook package.

    We need set the theme of MyReactActivity to Theme.AppCompat.Light.NoActionBar because some React Native UI components rely on this theme.

    activity android:name=".MyReactActivity" android:label="@string/app_name" android:theme="@style/Theme.AppCompat.Light.NoActionBar"> activity> 

    A ReactInstanceManager can be shared by multiple activities and/or fragments. You will want to make your own ReactFragment or ReactActivity and have a singleton holder that holds a ReactInstanceManager . When you need the ReactInstanceManager (e.g., to hook up the ReactInstanceManager to the lifecycle of those Activities or Fragments) use the one provided by the singleton.

    Next, we need to pass some activity lifecycle callbacks to the ReactInstanceManager and ReactRootView :

    @Override protected void onPause()   super.onPause();  if (mReactInstanceManager != null)   mReactInstanceManager.onHostPause(this); > >  @Override protected void onResume()   super.onResume();  if (mReactInstanceManager != null)   mReactInstanceManager.onHostResume(this, this); > >  @Override protected void onDestroy()   super.onDestroy();  if (mReactInstanceManager != null)   mReactInstanceManager.onHostDestroy(this); > if (mReactRootView != null)   mReactRootView.unmountReactApplication(); > > 

    We also need to pass back button events to React Native:

    @Override public void onBackPressed()   if (mReactInstanceManager != null)   mReactInstanceManager.onBackPressed(); > else   super.onBackPressed(); > > 

    This allows JavaScript to control what happens when the user presses the hardware back button (e.g. to implement navigation). When JavaScript doesn’t handle the back button press, your invokeDefaultOnBackPressed method will be called. By default this finishes your Activity .

    Finally, we need to hook up the dev menu. By default, this is activated by (rage) shaking the device, but this is not very useful in emulators. So we make it show when you press the hardware menu button (use Ctrl + M if you’re using Android Studio emulator):

    @Override public boolean onKeyUp(int keyCode, KeyEvent event)   if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null)   mReactInstanceManager.showDevOptionsDialog(); return true; > return super.onKeyUp(keyCode, event); > 

    Now your activity is ready to run some JavaScript code.

    Test your integration​

    You have now done all the basic steps to integrate React Native with your current application. Now we will start the Metro bundler to build the index.bundle package and the server running on localhost to serve it.

    1. Run the packager​

    To run your app, you need to first start the development server. To do this, run the following command in the root directory of your React Native project:

    npm start 
    yarn start 
    2. Run the app​

    Now build and run your Android app as normal.

    Once you reach your React-powered activity inside the app, it should load the JavaScript code from the development server and display:

    Creating a release build in Android Studio​

    You can use Android Studio to create your release builds too! It’s as quick as creating release builds of your previously-existing native Android app.

    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:

    $ 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/ 

    Don’t forget to replace the paths with correct ones and create the assets folder if it doesn’t exist.

    Now, create a release build of your native app from within Android Studio as usual and you should be good to go!

    Now what?​

    At this point you can continue developing your app as usual. Refer to our debugging and deployment docs to learn more about working with React Native.

    Key Concepts​

    The keys to integrating React Native components into your iOS application are to:

    1. Set up React Native dependencies and directory structure.
    2. Understand what React Native components you will use in your app.
    3. Add these components as dependencies using CocoaPods.
    4. Develop your React Native components in JavaScript.
    5. Add a RCTRootView to your iOS app. This view will serve as the container for your React Native component.
    6. Start the React Native server and run your native application.
    7. Verify that the React Native aspect of your application works as expected.

    Prerequisites​

    Follow the React Native CLI Quickstart in the environment setup guide to configure your development environment for building React Native apps for iOS.

    1. Set up directory structure​

    To ensure a smooth experience, create a new folder for your integrated React Native project, then copy your existing iOS project to a /ios subfolder.

    2. Install JavaScript dependencies​

    Go to the root directory for your project and create a new package.json file with the following contents:

      "name": "MyReactNativeApp", "version": "0.0.1", "private": true, "scripts":   "start": "yarn react-native start" > > 

    Install the react and react-native packages. Open a terminal or command prompt, then navigate to the directory with your package.json file and run:

    npm install react-native 
    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 «.

    This is OK, it means we also need to install React:

    npm install react@version_printed_above 
    yarn add react@version_printed_above 

    Installation process has created a new /node_modules folder. This folder stores all the JavaScript dependencies required to build your project.

    Add node_modules/ to your .gitignore file.

    3. Install CocoaPods​

    CocoaPods is a package management tool for iOS and macOS development. We use it to add the actual React Native framework code locally into your current project.

    We recommend installing CocoaPods using Homebrew.

    brew install cocoapods 

    It is technically possible not to use CocoaPods, but that would require manual library and linker additions that would overly complicate this process.

    Adding React Native to your app​

    Assume the app for integration is a 2048 game. Here is what the main menu of the native application looks like without React Native.

    Command Line Tools for Xcode​

    Install the Command Line Tools. Choose Settings. (or Preferences. ) in the Xcode menu. Go to the Locations panel and install the tools by selecting the most recent version in the Command Line Tools dropdown.

    Xcode Command Line Tools

    Configuring CocoaPods dependencies​

    Before you integrate React Native into your application, you will want to decide what parts of the React Native framework you would like to integrate. We will use CocoaPods to specify which of these «subspecs» your app will depend on.

    The list of supported subspec s is available in /node_modules/react-native/React.podspec . They are generally named by functionality. For example, you will generally always want the Core subspec . That will get you the AppRegistry , StyleSheet , View and other core React Native libraries. If you want to add the React Native Text library (e.g., for elements), then you will need the RCTText subspec . If you want the Image library (e.g., for elements), then you will need the RCTImage subspec .

    You can specify which subspec s your app will depend on in a Podfile file. The easiest way to create a Podfile is by running the CocoaPods init command in the /ios subfolder of your project:

    pod init 

    The Podfile will contain a boilerplate setup that you will tweak for your integration purposes.

    The Podfile version changes depending on your version of react-native . Refer to https://react-native-community.github.io/upgrade-helper/ for the specific version of Podfile you should be using.

    Ultimately, your Podfile should look something similar to this:

    # The target name is most likely the name of your project. target 'NumberTileGame' do  # Your 'node_modules' directory is probably in the root of your project,  # but if not, adjust the `:path` accordingly  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"  pod 'React', :path => '../node_modules/react-native/'  pod 'React-Core', :path => '../node_modules/react-native/'  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'  pod 'ReactCommon/callinvoker', :path => "../node_modules/react-native/ReactCommon"  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec' end 

    After you have created your Podfile , you are ready to install the React Native pod.

    $ pod install 

    You should see output such as:

    Analyzing dependencies Fetching podspec for `React` from `../node_modules/react-native` Downloading dependencies Installing React (0.62.0) Generating Pods project Integrating client project Sending stats Pod installation complete! There are 3 dependencies from the Podfile and 1 total pod installed. 

    If this fails with errors mentioning xcrun , make sure that in Xcode in Settings. (or 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.

    The React Native component​

    The first bit of code we will write is the actual React Native code for the new «High Score» screen that will be integrated into our application.

    1. Create a index.js file​

    First, create an empty index.js file in the root of your React Native project.

    index.js is the starting point for React Native applications, and it is always required. It can be a small file that require s other file that are part of your React Native component or application, or it can contain all the code that is needed for it. In our case, we will put everything in index.js .

    2. Add your React Native code​

    In your index.js , create your component. In our sample here, we will add a component within a styled

    import React from 'react'; import AppRegistry, StyleSheet, Text, View> from 'react-native';  const RNHighScores = (scores>) =>   const contents = scores.map(score => ( Text key=score.name>> score.name>:score.value> '\n'> Text> )); return ( View style=styles.container>> Text style=styles.highScoresTitle>>  2048 High Scores! Text> Text style=styles.scores>>contents>Text> View> ); >;  const styles = StyleSheet.create(  container:   flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#FFFFFF', >, highScoresTitle:   fontSize: 20, textAlign: 'center', margin: 10, >, scores:   textAlign: 'center', color: '#333333', marginBottom: 5, >, >);  // Module name AppRegistry.registerComponent('RNHighScores', () => RNHighScores); 

    RNHighScores is the name of your module that will be used when you add a view to React Native from within your iOS application.

    The Magic: RCTRootView ​

    Now that your React Native component is created via index.js , you need to add that component to a new or existing ViewController . The easiest path to take is to optionally create an event path to your component and then add that component to an existing ViewController .

    We will tie our React Native component with a new native view in the ViewController that will actually contain it called RCTRootView .

    1. Create an Event Path​

    You can add a new link on the main game menu to go to the «High Score» React Native page.

    2. Event Handler​

    We will now add an event handler from the menu link. A method will be added to the main ViewController of your application. This is where RCTRootView comes into play.

    When you build a React Native application, you use the Metro bundler to create an index.bundle that will be served by the React Native server. Inside index.bundle will be our RNHighScore module. So, we need to point our RCTRootView to the location of the index.bundle resource (via NSURL ) and tie it to the module.

    We will, for debugging purposes, log that the event handler was invoked. Then, we will create a string with the location of our React Native code that exists inside the index.bundle . Finally, we will create the main RCTRootView . Notice how we provide RNHighScores as the moduleName that we created above when writing the code for our React Native component.

    First import the RCTRootView header.

    #import React/RCTRootView.h> 

    The initialProperties are here for illustration purposes so we have some data for our high score screen. In our React Native component, we will use this.props to get access to that data.

    - (IBAction)highScoreButtonPressed:(id)sender   NSLog(@"High Score Button Pressed");  NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL: jsCodeLocation  moduleName: @"RNHighScores"  initialProperties: @  @"scores" : @[ @  @"name" : @"Alex", @"value": @"42" >, @  @"name" : @"Joel", @"value": @"10" > ] >  launchOptions: nil];  UIViewController *vc = [[UIViewController alloc] init];  vc.view = rootView; [self presentViewController:vc animated:YES completion:nil]; > 

    Note that RCTRootView initWithURL starts up a new JSC VM. To save resources and simplify the communication between RN views in different parts of your native app, you can have multiple views powered by React Native that are associated with a single JS runtime. To do that, instead of using [RCTRootView alloc] initWithURL , use RCTBridge initWithBundleURL to create a bridge and then use RCTRootView initWithBridge .

    When moving your app to production, the NSURL can point to a pre-bundled file on disk via something like [[NSBundle mainBundle] URLForResource:@»main» withExtension:@»jsbundle»]; . You can use the react-native-xcode.sh script in node_modules/react-native/scripts/ to generate that pre-bundled file.

    3. Wire Up​

    Wire up the new link in the main menu to the newly added event handler method.

    Event Path

    One of the easier ways to do this is to open the view in the storyboard and right click on the new link. Select something such as the Touch Up Inside event, drag that to the storyboard and then select the created method from the list provided.

    Test your integration​

    You have now done all the basic steps to integrate React Native with your current application. Now we will start the Metro bundler to build the index.bundle package and the server running on localhost to serve it.

    1. Add App Transport Security exception​

    Apple has blocked implicit cleartext HTTP resource loading. So we need to add the following our project’s Info.plist (or equivalent) file.

    key>NSAppTransportSecuritykey> dict> key>NSExceptionDomainskey> dict> key>localhostkey> dict> key>NSTemporaryExceptionAllowsInsecureHTTPLoadskey> true/> dict> dict> dict> 

    App Transport Security is good for your users. Make sure to re-enable it prior to releasing your app for production.

    2. Run the packager​

    To run your app, you need to first start the development server. To do this, run the following command in the root directory of your React Native project:

    npm start 

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *