Phpstorm React Native



The contents of this page describe what a Native Bridge is within React Native, and how to create one within a project.

Description

React-native, react and native-base version RN: 0.45.1 React: 16.0.0-alpha.12 NativeBase: 2.2.0 Expected behaviour Since NativeBase has its type definitions file.

  1. Reactjs typescript react-native phpstorm webstorm. Follow edited Mar 3 '17 at 13:43. Asked Mar 3 '17 at 13:32. RedGiant RedGiant. 3,952 6 6 gold badges 41 41 silver badges 115 115 bronze badges. Add a comment 2 Answers Active Oldest Votes. Libraries configured.
  2. React Native Console an IDEA/WebStorm/Android Studio Plugin for run React Native commands and coding easier Notice.

One of the many benefits of using the React Native framework is that it does not pigeonhole app development by limiting it to the current platform API or the many third-party libraries that are usually required in order to create and build a project. Sometimes development necessitates for the creation of a module that does not exist either within the platform API or there is no comparable module found within the npm library at npmjs.org. React Native allows developers to create their own module(s) in Native Code (Objective-C & Java for MQ purposes) and bridge them into the project so that the top level JavaScript layer can interact with those modules and use them within that JS layer.

The contents of this page describe what a Native Bridge is within React Native, and how to create one within a project.


What is a Native Bridge?

When you hear the term 'Native Bridge', think of npm packages.

Many (but not all) react-native npm packages that are added/installed into a project are Native Bridges. If the package is a pure JS package, then it is just that - pure JavaScript. If a react-native package contains an `ios` directory and an `android` directory, it is most-likely a Native Bridge. Those two directories are typically where the Native code should live for each platform, which then connects to one or more JS files which should be included within the npm package. Once a package has been added or installed in the project, the developer normally imports the package via those earlier mentioned included JS files into a class within their project, and is then able to interact with the native code to perform some sort of functionality within that class. Some of the more common native elements that are often interacted with are the device camera, photo albums or adding events to calendars.

That whole ability to communicate from the Native module to the top JS layer within the app is what we refer to as a Native Bridge.

Phpstorm React Native Free


Creating a Native Bridge:

For this example we will create a very simply Flash module that checks a device for whether it has a flash or not:

Note: This is not a tutorial in Objective C or Java so I will not spend time explaining what the code does; Only why something is required for bridging purposes.

Step 1: Create the Native iOS code in Objective C

Open the React Native project in XCode as one should not create .h and .m files within PhpStorm of VisualStudio Code or whatever their preferred editor is. Creating these files should occur in XCode.

To create a file, choose the folder where you want the file to live within the project, (good place is where the main.m file resides) and right click, then select New File... and choose either the Header File or Objective-C-File and it will be added to the project. There will be some additional boiler plate options that you can choose, but starting with a blank class is always a good route to go.

Phpstorm react native app

Objective C generally requires a header (.h) file and a message (.m) file.

For the flash library we first create the '.h' file which looks like this:

Flash.h

#import<Foundation/Foundation.h>

#if__has_include(<React/RCTAssert.h>)

#import<React/RCTBridgeModule.h>

#else

#import'RCTBridgeModule.h'

#endif

@interfaceFlash : NSObject <RCTBridgeModule>

@end

The main take away here is that this header (.h) file implements the RCTBridgeModule protocol, which is required to bridge the native code to the JS code. For completion sake, it defines the Flash class that we are about to implement.

Next we have the message (.m) file and it looks like this:

Flash.m

#import<AVFoundation/AVFoundation.h>

#import'Flash.h'

@implementationFlash

RCT_EXPORT_MODULE()

+ (BOOL)requiresMainQueueSetup

{

returnYES;

}

// Check the device for flash capabilities and return callback of success // or fail

RCT_EXPORT_METHOD(hasFlash:(RCTResponseSenderBlock)successCallback errorCallback:(RCTResponseSenderBlock)errorCallback)

{

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

if([device hasTorch] && [device hasFlash]) {

successCallback(@[]);

}

else{

errorCallback(@[]);

}

}

@end

React Native will not expose any methods of Flash module to the JS layer unless explicitly told to. This is done using the RCT_EXPORT_METHOD() macro to wrap the hasFlash method of the Flash class.

The code above returns a Promise to the JS layer of either Success or Failure of the code run within the RCT_EXPORT_METHOD wrapper. That is it for the iOS Native code.

Step 2: Create the Native Android code in Java

Open the React Native project in Android Studio as one should not create .java files within PhpStorm of VisualStudio Code or whatever their preferred editor is. PhpStorm will not read the file type properly and you won't have access to proper intellisense.

We now need to drill down to the correct place to add our native Java Flash code. Within the top level android directory open the folders in this path `app → src → main → java → com.{project name} `

Within this directory, create a new directory and call it 'flash'. It is within this new directory that the flash module Java files will be created.

Right click the 'Flash' directory and select 'New → Java Class' and name it FlashPackage. Then we need to fill it with some code. When we are done it will look like this:

FlashPackage.java

packagecom.myawesomeproject.flash;

importcom.facebook.react.ReactPackage;

importcom.facebook.react.bridge.NativeModule;

importcom.facebook.react.bridge.ReactApplicationContext;

importcom.facebook.react.uimanager.ViewManager;

importjava.util.Collections;

importjava.util.List;

importjava.util.ArrayList;

publicclassFlashPackage implementsReactPackage

{

@Override

publicList<NativeModule> createNativeModules(ReactApplicationContext reactContext) {

List<NativeModule> modules = newArrayList<>();

modules.add(newFlashModule(reactContext));

returnmodules;

}

@Override

publicList<ViewManager> createViewManagers(ReactApplicationContext reactContext) {

returnCollections.emptyList();

}

}

This Java file implements the RCTBridgeModule protocol, which as we know from before, is required to bridge the native code to the JS code.

Next we have the flash module where the actual logic resides and and it looks like this:

FlashModule.java

packagecom.myawesomeproject.flash;

importandroid.content.pm.PackageManager;

importcom.facebook.react.bridge.Callback;

importcom.facebook.react.bridge.ReactApplicationContext;

importcom.facebook.react.bridge.ReactContextBaseJavaModule;

importcom.facebook.react.bridge.ReactMethod;

publicclassFlashModule extendsReactContextBaseJavaModule

{

/**

* Member Variables

*/

privatefinalReactApplicationContext reactContext;

/**

* Constructor

*

* @param reactContext ReactApplicationContext

*/

publicFlashModule(ReactApplicationContext reactContext) {

super(reactContext);

this.reactContext = reactContext;

}


@Override

publicString getName() {

return'Flash';

}


@ReactMethod

publicvoidhasFlash(Callback successCallback, Callback errorCallback) {

// Check for whether the device has a flash or not

if(reactContext.getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {

successCallback.invoke();

}

else{

errorCallback.invoke();

}

}

}

React

Now that we have these 2 files created, we need to tell the MainApplication.java file to use this newly created Flash module. The MainApplication.java file is located in the parent directory to where we created the flash directory. It should be a sibling to the Flash directory. Open that file and within the import section we would add the following code:

Import

importcom.myawesomeproject.flash.FlashPackage;

Next, we need to tell React Native about the package. Within the same MainApplication.java file look for a ReactNativeHost method and add your Flash package. The method should then look similar to this:

Add Flash Package

privatefinalReactNativeHost mReactNativeHost = newReactNativeHost(this)

{

@Override

publicbooleangetUseDeveloperSupport() {

returnBuildConfig.DEBUG;

}


@Override

protectedList<ReactPackage> getPackages() {

@SuppressWarnings('UnnecessaryLocalVariable')

List<ReactPackage> packages = newPackageList(this).getPackages();

// Packages that cannot be autolinked yet can be added manually

// here, for example: packages.add(new MyReactNativePackage());

packages.add(newFlashPackage());

returnpackages;

}


@Override

protectedString getJSMainModuleName() {

return'index';

}

};

And with that we now need to move over to the JS layer and create our JavaScript file that will actually bridge the Native layer and the upper level JS layer.

Step 3: Create the TypeScript or JavaScript file for Native level interactions

We need to create a file that will talk to the RCT_EXPORT_MODULE() in the Native land and any methods to be used in JavaScript land. Now we can safely do this in PhpStorm or whatever code editor is your preference.

Phpstorm React Native App

You can place this file anywhere you want that makes sense to you in your project. This example is done with TypeScript as that is the standard that we use in MQ projects. For Flash it looks like this:

Flash.ts

/**

* Imports

*/

import {NativeModules} from 'react-native';


/**

* Native definition and export

*/


// Use Native Code directly

export const Flash: any = NativeModules.Flash;

And with that, we can now import the Flash.ts file and it's method into other files within the project.

Native

An example of what that looks like is this:

Example Usage

import { MQFlash } from '../nativeStuff/Flash';

... {Within the class}

public componentDidMount(): void

{

// Perform the check for whether the device has flash capability

Flash.hasFlash(

() => {

// Has flash

console.log( 'CameraModal::componentDidMount:Flash Detected');

this.setState( { hasFlash: true} );

},

() => {

// Does not have flash

console.log( 'CameraModal::componentDidMount:No Flash Detected');

this.setState( { hasFlash: false} );

}

);

} // End of componentDidMount()

...

This implementation should return a Success or Failure and then console.log will display the correct response based on whether the returned promise was a value of success or failure.

And with that, this is what we would call a valid Native Bridge.

For further reading about Native Modules in React Native, see the official ios documentation here and the official android documentation here.



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.

PhpStorm helps you create, edit, lint, run, debug, and maintain your React Native applications. PhpStorm 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 and TypeScript bundled plugin is enabled on the Settings/Preferences | Plugins page, see Managing plugins for details.

Creating a new React Native application

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

  1. Click Create New Project on the Welcome screen or select File | New | Project from the main menu. The Create 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 TerminalAlt+F12. When creating an application, select the folder where the react-native-cli package is stored.

  4. When you click Create, PhpStorm 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 PhpStorm 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 Directory 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

Phpstorm react native app
  1. Click Get from VCS on the Welcome screen or select VCS | Get from Version Control from the main menu.

  2. In the invoked dialog, select your version control system from the list and specify the repository to check out the application sources from.

Download the dependencies

  • Click Run 'npm install' or Run 'yarn install' in the popup:

    You can use npm, Yarn 1, or Yarn 2, see npm and Yarn for details.

To exclude the android and iOS folders from the project

  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.

Coding assistance

PhpStorm 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:

If you are using Flow in your project, PhpStorm can highlight the errors from this type checker in the editor. See Configuring Flow in PhpStorm and Using Flow in WebStorm for details.

Native

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.

PhpStorm 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. On the main menu, go to Run | Edit Configurations, click and select React Native from the list. The Run/Debug Configuration: React Native opens.

  2. Choose whether you want PhpStorm 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, PhpStorm 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, PhpStorm will run the bundler with react-native run-ios or with react-native run-android.

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

  4. 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 PhpStorm 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. See Debugging a React Native application that uses Expo for details.

  5. 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.

  6. Choose the Node.js interpreter to use. This can be a local Node.js interpreter or a 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.

  7. By default, PhpStorm starts the React Native bundler automatically when you invoke the run/debug configuration. If you have already started the bundler from outside PhpStorm, 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 .

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 PhpStorm 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

  • Choose the newly created React Native configuration in the Select run/debug configuration list on the toolbar and click next to it. PhpStorm 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 PhpStorm, you can debug applications that use the native React Native bundler and those that use Expo.

In debugging React Native applications, PhpStorm relies on the Chrome runtime, which is used by React Native itself. You can also use DevTools together with PhpStorm. When you initiate a debugging session, PhpStorm 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 PhpStorm, select it in the Before Launch area and click .

  3. To start your application, select the newly created React Native configuration from the Select run/debug configuration list on the toolbar and click next to it. PhpStorm 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 built-in PhpStorm 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.

Debug a React Native application that uses Expo

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

  • Create a script that runs Expo and then specify this script as a Before launch task in the React Native run/debug configuration.

  • First run Expo manually or via a script 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. Set the breakpoints in your code as required.

  2. 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 .

      To start Expo via a script automatically, click and select Run npm script from the list.

      In the NPM Script dialog that opens, select the npm script that starts Expo.

  3. Select the newly created configuration and click .

  4. 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.

  5. When the first breakpoint is hit, proceed as when debugging an application that uses a native bundler.

To configure Chrome Headless in PhpStorm

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

  1. Click next to the Browser for debugging field. The Web Browsers dialog opens.

  2. Select Chrome, click , and rename the copied configuration, for example, to Chrome Headless.

  3. Select the new browser configuration, click , and type --headless for macOS and Linux or --headless --disable-gpu for Windows in the Chrome Settings dialog.

  4. In the run/debug configuration, choose the new Chrome Headless configuration from the Browser for debugging list.