Building web applications with React Native

React Native is a JavaScript library that allows developers to build mobile applications for iOS and Android platforms using the same code base. It is based on the popular React web framework developed by Facebook. But did you know that it is also possible to build web applications using React Native? In this tutorial, we will explore how to use React Native for web development.

Getting Started

Before we begin, ensure that you have the following requirements installed in your system:

  • Node.js
  • npm or yarn package manager
  • React Native CLI

To create a new React Native project, open your terminal and execute the following command:

npx react-native init my-app

This command creates a new project named my-app in your current working directory. Once the process is complete, navigate to the project directory and execute the command below to start the development server:

cd my-app
npm start

This opens the Metro Bundler console in your terminal. Metro is a JavaScript bundler responsible for building your application. In addition to the bundler console, it opens a browser tab where you can run your application in development mode.

Configuring React Native for Web

In order to use React Native for web development, you will need to install the react-native-web package. This package provides a way to render React Native components in the browser using CSS and HTML.

To install it, execute the following command:

npm install react-native-web

After installing the package, we need to modify the project configuration to support web development. In the project root directory, create a file named metro.config.js and include the following modifications:

const { getDefaultConfig } = require('metro-config');

const config = getDefaultConfig(__dirname);

module.exports = {
  ...config,
  resolver: {
    ...config.resolver,
    sourceExts: [...config.resolver.sourceExts, "web.js", "web.ts", "web.tsx"],
  },
};

This configuration maps all the .web.js, .web.ts, and .web.tsx files to be recognized by the bundler. We will use these files to write web-specific code.

Creating a Shared Component

We will start by creating a shared component that we will use in both platforms. In the src directory, create a file named Button.js. This file defines a simple button component that accepts the title and onPress props:

import React from "react";
import { TouchableOpacity } from "react-native";

const Button = ({ title, onPress }) => (
  <TouchableOpacity onPress={onPress} style={{ backgroundColor: '#6495ED', padding: 10 }}>
    <Text>{title}</Text>
  </TouchableOpacity>
);

export default Button;

This button component will have the same appearance in both the web and mobile platforms. To use this component in the web platform, we will create a duplicate file named Button.web.js that renders the same button using HTML and CSS:

import React from "react";

const Button = ({ title, onPress }) => (
  <button onClick={onPress} style={{ backgroundColor: '#6495ED', padding: 10 }}>
    {title}
  </button>
);

export default Button;

Notice that we changed the TouchableOpacity component to a button HTML element. Also, we removed the import { TouchableOpacity } from "react-native"; line.

Creating the Web Platform

With the shared component ready, let’s create the web platform by adding a new file named index.web.js in the project root directory. This file will contain the web application entry point.

import { AppRegistry } from "react-native";
import App from "./src/App";
import { name as appName } from "./app.json";

AppRegistry.registerComponent(appName, () => App);

AppRegistry.runApplication(appName, {
  initialProps: {},
  rootTag: document.getElementById("root"),
});

This code registers the main App component and runs it on the #root element in the index.html file. In order to use React Native components in the web platform, we need to modify the index.html file to include the necessary script tags. In the project root directory, create a file named index.html with the following content:

<!DOCTYPE html>
<html>
  <head>
    <title>React Native Web App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://unpkg.com/react-native-web/dist/index.js"></script>
    <script src="./index.web.js"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

This file includes the react-native-web and index.web.js script tags. It also includes the #root element where we will render our application.

Building for Web

We are now ready to build and run our application. Execute the following command in your terminal:

npm run web

This command starts the webpack bundler and generates a dist directory with the built application files. Once the process is complete, open the index.html file in your web browser to see your React Native web application running.

Creating the Mobile Platform

To create the mobile platform, we will reuse the shared component defined earlier. In the src directory, create a file named App.js and include the following code:

import React from "react";
import { StyleSheet, View } from "react-native";
import Button from "./Button";

const App = () => {
  return (
    <View style={styles.container}>
      <Button title="Press Me!" onPress={() => alert("Hello World!")} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});

export default App;

This file defines the main App component that renders the shared Button component. We also defined a StyleSheet object to style the container.

Building for Mobile

To build the mobile application, execute the following command in your terminal:

npx react-native run-android

This command launches the application on an Android emulator or device connected to your computer. You can also use the run-ios command to launch the application on an iOS simulator or device.

Conclusion

In this tutorial, we explored how to use React Native for web development. We started by configuring React Native for web development, created a shared button component, and built both a web and a mobile platform using the same code base. We hope this tutorial will help you get started with building web applications using React Native. Happy coding!

Related Post