DEV Community

Matteo Mazzarolo
Matteo Mazzarolo

Posted on • Originally published at mmazzarolo.com on

Run your React Native app on the web with React Native for Web

“React Native for Web” makes it possible to run React Native components and APIs on the web using React DOM — allowing you to target the Android, iOS, and web platforms using a single codebase.

The React Native for Web documentation has a few examples of how to get started from scratch. For example, you can use expo or create-react-native-app to create a new React Native project compatible with React Native for Web. Or you can use Create React App to generate a simple, web-only React app with built-in support of React Native for Web.

In this post, I’d like to take a different approach from the one used in the React Native for Web documentation: I’ll explain how to add React Native for Web to an existing React Native app using Create React App.

Setup the Create React App project

The standard way to setup a React app from scratch using Create React App is by using the create-react-app CLI to generate the entire project. However, in our case, we’re adding a React app on top of an existing project, so the setup process will be a bit different.

Dependencies

First of all, let’s install these dependencies:

# If you're using NPM...
npm install react-native-web react-scripts react-dom

# ...or, if you're using Yarn
yarn add react-native-web react-scripts react-dom
Enter fullscreen mode Exit fullscreen mode
  • react-native-web is the React Native for Web library. It provides a mapping of the React Native components and APIs to their web counterparts.
  • react-scripts are the scripts used by Create React App to bundle and run your web application.
  • react-dom is what allows React to run on the web. It’s recommended to install a version of React DOM that matches your currently installed version of React.

Directory Structure

Create React App expects your project to follow a specific directory structure.

Depending on how your current React Native setup looks like, you might need to make some changes to accommodate the Create React App convention.

The next steps will assume you’re starting with a directory structure similar to the following:

.
├── android/
│ └── ...
├── ios/
│ └── ...
├── src/
│ ├── App.js # The root component of your React Native app
│ └── ...
└── index.js # Where React Native's "registerComponent" is invoked
Enter fullscreen mode Exit fullscreen mode

For the project to build, these files must exist with exact filenames :

  • public/index.html: The HTML page template served to the users. Create React App injects your React application in this page.
  • src/index.js: The JavaScript entry-point of your React web application.

Normally these files are generated by the create-react-app CLI… but since we couldn’t use it, we need to go a step further and create them manually.

The Public Directory

Create a new directory named public at the root of your project. In it, we will put the index.html file and all the additional files that it uses.

To create its content, you can either a) copy and paste in the public directory the content of what the create-react-app CLI would have generated, or b) create just a minimal public/index.html file like the following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <title>Your App Title</title>
  </head>

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The JavaScript Entry Point

Create a new index.js file in your src directory:

import { AppRegistry } from "react-native";
import { App } from "./App.js";

const appName = "Your app name";

AppRegistry.registerComponent(appName, () => App);
AppRegistry.runApplication(appName, {
  // Mount the react-native app in the "root" div of index.html
  rootTag: document.getElementById("root"),
});
Enter fullscreen mode Exit fullscreen mode

This is the entry point of the JavaScript code that will be injected in your HTML file.

You might have noticed that you now have two different index.js files — one at the root of your project, and one in the src directory.

The metro bundler — which is the JavaScript bundler that builds your React Native app — will use the index.js file that you already have at the root of your project for building the Android/iOS app.

Webpack — used under the hood by Create React App — will instead use the new src/index.js.

To be a bit more explicit on which JS index file is used on a specific platform, I’d suggest renaming the root index.js file to index.native.js. See the official React-Native documentation for more details on the platform-specific extensions.

Create The Build Scripts

To complete the Create React App setup, add two script to your package.json to build your web app:

  "scripts": {
+ "web:start": "react-scripts start",
+ "web:build": "react-scripts build",
}
Enter fullscreen mode Exit fullscreen mode

Running the Web App

You can now use npm run web:start to spin-up the development environment of your web app and npm run web:build to create a production build.

The default configuration of Create React App already aliases all react-native imports to react-native-web by default, so you won’t have to worry about manually having to swap them based on the target platform.

That said, unless you’re extremely lucky, you won’t be able to run your React Native app on the web on the first try…

Here’s a list of a few common issues you might face.

Fixing the Dependency Tree Warning

The first time you run your web app you’ll probably see the following warning in the console:

There might be a problem with the project dependency tree.
It is likely not a bug in Create React App, but something you need to fix locally.

The react-scripts package provided by Create React App requires a dependency:

  "babel-jest": "^26.6.0"

Don't try to install it manually: your package manager does it automatically.
However, a different version of babel-jest was detected higher up in the tree:

  /Users/username/workspace/YourProject/node_modules/babel-jest (version: 25.5.1)

Manually installing incompatible versions is known to cause hard-to-debug issues.

If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That will permanently disable this message but you might encounter other issues.
Enter fullscreen mode Exit fullscreen mode

This warning shows up because React Native ships with a version of babel-jest (or other packages, depending on what your warning says) that is different from the one used by Create React App.

The warning itself will point you to several possible fixes.

The two options I would suggest you try are:

  • Ignore this check by adding SKIP_PREFLIGHT_CHECK=true to a .env file at the root of your project. This will force react-script to use the dependency versions set in your package.json instead of the ones required by Create React App. Most of the time these errors are caused by a slightly different version of babel-jest or jest that can still be compatible with the versions you were using in your React Native app — which is why this solution will likely work.
  • Or uninstall the incriminated dependencies and run again npm install or yarn install. This will make your React Native app use the dependencies shipped with Create React App.

Regardless of what choice you make here, this change is one of the things you should test for regressions when in the future you’ll update your project to a new version of React Native or react-scripts.

Resolve Native Module Conflicts

React Native for Web is compatible with many native modules that ship with React Native: Button, Views, TextInput, etc… will be automatically mapped to their web counterparts correctly when imported from react-native.

Unfortunately, using other external native libraries like react-native-sound or react-native-keep-awake can be a bit hit-and-miss because many native functionalities are not available on the web.

In these cases, your web app will fail to compile with errors such as Module not found.

The React Native “Platform Specific Code” documentation has some great tips on how you can run platform-specific code and solve these issues.

My suggestion is to abstract these native libraries in files with platform-specific extensions so that only the React Native bundler will import them.

For example, assuming you want to use the KeepAwake component exported by the react-native-keep-awake only in your React Native app you should create two files:

  • A file with the code that runs on the native app named KeepAwake.native.js that just acts as a proxy for the react-native-keep-awake library:
import KeepAwake from "react-native-keep-awake";
export default KeepAwake;
Enter fullscreen mode Exit fullscreen mode
  • A file with the code that runs on the web named KeepAwake.js that exports a mock/empty component:
import { Fragment } from "react";
export default Fragment;
Enter fullscreen mode Exit fullscreen mode

By following this strategy you can now import the module ignoring the extension (import KeepAwake from "./KeepAwake";). The right file will be picked up automatically by Create React App and by the React Native bundler.

You might already be familiar with the .android.js and .ios.js extension. This concept basically acts in the same way, differentiating the code that runs on the web from the one that runs your native app by suffixing the latter with the .native.js extension.

Customize Create React App

Eventually, you might need to customize your project beyond what Create React App allows you to do. Most of these customizations will probably be just slight changes to the Webpack and Babel configuration of Create React App where ejecting would be overkill — which is why you might wanna use something like react-app-rewired, customize-cra, or craco to apply these changes without ejecting.

One of the first few customizations you’ll want to apply to Create React App, is adding support for the __dev__ keyword on the web. The React Native bundler sets the global __dev__ variable to true in development mode when you work on your React Native app, while Create React App uses process.env.NODE_ENV to determine if the web app is running in development/production instead.

To have a unified development experience and make your web app aware of __dev__, we can use react-app-rewired + customize-cra to change the Create React App Webpack configuration, setting the __dev__ variable correctly.

Install the following dependencies:

# If you're using NPM...
npm install -S customize-cra react-app-rewired

# ...or, if you're using Yarn
yarn add customize-cra react-app-rewired
Enter fullscreen mode Exit fullscreen mode

Then create a config-overrides.js file at the root of your project. It will be used by react-app-rewired + customize-cra to apply customizations to Create React App:

const webpack = require("webpack");
const { override, addWebpackPlugin } = require("customize-cra");

module.exports = override(
  addWebpackPlugin(
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify(
        process.env.NODE_ENV || "development"
      ),
      // Add support for the __DEV__ global variable
      __DEV__ : process.env.NODE_ENV !== "production",
    })
  )
);
Enter fullscreen mode Exit fullscreen mode

To activate these customizations, update your existing calls to react-scripts in the package.json to use react-app-rewired instead:

  "scripts": {
- "web:start": "react-scripts start",
+ "web:start": "react-app-rewired start",
- "web:build": "react-scripts build",
+ "web:build": "react-app-rewired build",
}
Enter fullscreen mode Exit fullscreen mode

TypeScript

Create React App supports TypeScript. If your React Native is written in TypeScript, you just need to make sure your .tsconfig follows the same rules used in the Create React App TypeScript template.

Conclusion

It’s true, creating a React Native for Web project might not be as easy as creating a web app.

But in some cases the effort is definitely worth it: at the end of the day, you’re still building a native app and a web app using a single codebase.

I think the setup complexity is definitely justified here.

Thanks @necolas for creating and maintaining React Native for Web.

Top comments (0)