Build Mobile-Friendly Web Apps with React Native Web
Publikováno: 21.2.2019
Over the years, building web applications that are mobile friendly has become easier with the advent of media queries and the introduction of service workers. Using media queries, we could make web...
Over the years, building web applications that are mobile friendly has become easier with the advent of media queries and the introduction of service workers. Using media queries, we could make web applications that different shapes when viewed on mobile devices. Service workers, with their powerful features, present web applications with powers only native applications have been known to possess — push notifications, background sync, etc.
React Native is a multi-platform solution developed by Facebook that lets you build mobile apps using JavaScript. These mobile apps are considered multi-platform because they’re written once and deployed across many platforms, like Android, iOS and the web. Today, we’ll see how we can utilize this powerful technology to build platform-focused applications on the web.
We’ll be building a simple application that displays user information from a random API using React Native components like ScrollView, Text and Image.
The library we’ll be using to build the demo is called React Native Web, "React Native for Web makes it possible to run React Native components and APIs on the web using React DOM”.
We’ll be building a simple application that will run both on the web and mobile using the React Native Web library, the application displays user information from a random API using React native components like ScrollView, Text, Image etc.
Prerequisites
To follow this tutorial, you’ll need to have Node > 6.0 installed. You’ll also need a package manager NPM (this comes packaged with Node) or Yarn(follow the installation guide here).
Basic knowledge of JavaScript and React is also required. You can follow the official React tutorial here to get up to speed with React.
Getting started
Before we get started, we’ll need to set up the project and install project dependencies. We’ll be making use of Create React App to bootstrap our application. We’re using Create React App because it can be configured to alias React Native. We’ll be installing polyfills for some of the latest JavaScript APIs like Promise
, Array.from
, etc., as the transpiler doesn’t provide those.
To bootstrap your application using Create React App, run the following command:
yarn create react-app random-people
or
npx create-react-app random-people
Run the following command to install the project’s development dependencies:
yarn add --dev babel-plugin-module-resolver babel-plugin-transform-object-rest-spread babel-plugin-transform-react-jsx-source babel-preset-expo
or
npm install --save-dev babel-plugin-module-resolver babel-plugin-transform-object-rest-spread babel-plugin-transform-react-jsx-source babel-preset-expo
The babel-plugin-module-resolver is a plugin that resolves your project modules when compiling with Babel. We’ll use this package to alias react-native to react-native-web when setting up the project config.
To build and run our application, we’ll be using Expo. Expo is an open-source toolchain built around React Native for building Android and iOS applications. It provides access to the system’s functionality like the Camera, Storage, etc.
Install the expo-cli by running the following command:
yarn global add expo-cli
or
npm i g expo-cli
The next step is to install expo locally, alongside React Native and React Native Web. Run the command below to install the packages:
yarn add expo react-native react-native-web react-art
or
npm i expo react-native react-native-web react-art
After downloading the packages needed to run and build the application, the next step is to setup the configuration files. Create a file called .babelrc
in the root of your project and update it with the following:
//.babelrc{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": ["transform-object-rest-spread", "transform-react-jsx-source"]
}
},
"plugins": [
[
"module-resolver",
{
"alias": {
"^react-native$": "react-native-web"
}
}
]
]
}
Create a file named app.json
. This file is used to configure parts of your application that don’t belong in the code like the application name
, description
, sdkVersion
, etc. You can find the options available for the app.json
file here.
Let’s update the package.json
file to include commands for running our application on Android and iOS emulators. Also, we’ll include the main
field referencing the App.js
file. This file will act as the entry file for the expo-cli. Open the package.json
file in a file editor of choice:
// package.json
{
"name": "random-people",
"version": "0.1.0",
"private": true,
"main": "./App.js",
...
"scripts": {
"start-web": "react-scripts start",
"build-web": "react-scripts build",
"test-web": "react-scripts test",
"eject-web": "react-scripts eject",
"start-native" : "expo start",
"android": "expo android",
"ios": "expo ios",
"build:ios": "expo build:ios",
"build:android": "expo build:android",
},
...
}
Run npm run start-web
to run the application and visit http://localhost:3000 to view the application.
Home component
Our application is a simple demo that displays users via the random user API. Using the API, we’ll get display a name and avatar of the returned users through some of the components provided by React Native. Within the src/
directory, create a file named home.js
. Open this file using an editor and update it with the snippet below:
//home.js
import React from "react";
import {
ScrollView,
ActivityIndicator,
StyleSheet
} from "react-native";
class Home extends React.Component {
state = {
users: [],
loading: true
};
componentDidMount() {
// TODO: get users
}
render() {
return (
<ScrollView
noSpacer={true}
noScroll={true}
style={styles.container}
>
<ActivityIndicator
style={[styles.centering, styles.gray]}
color="#ff8179"
size="large"
/>
</ScrollView>
);
}
}
var styles = StyleSheet.create({
container: {
backgroundColor: "whitesmoke"
},
centering: {
alignItems: "center",
justifyContent: "center",
padding: 8,
height: '100vh'
},
});
export default Home;
In the snippet above, the Home
component renders a ScrollView component that houses the component’s elements. Currently, the component displays an ActivityIndicator; this will be replaced by the user list when the call to the API is complete.
We create styles for the elements using the StyleSheet component. This allows us to style the component using properties similar to CSS properties.
Let’s create a method that gets random users from the Random User API. This method will be called during the componentDidMount
lifecycle. Update the home.js
component to include the getUsers
method:
// home.js
import React from 'react';
...
class Home extends React.Component {
state = {
...
};
componentDidMount() {
this.getUsers();
}
async getUsers() {
const res = await fetch("https://randomuser.me/api/?results=20");
const { results } = await res.json();
this.setState({ users: [...results], loading: false });
}
...
}
We can easily make requests using the native Fetch API. Results from the request are parsed and added to state. When the request is complete, we’ll hide the ActivityIncidator
by setting loading
to false.
App component
The AppComponent
holds the logic for the application. We’ll update the default view created by Create React App to suit that of our application by adding logic to display native components.
Create a new file named App.js
in the root of your project. This file will be similar to the src/App.js
file. The root App.js
file will act as the entry file for expo, and the src/App.js
file exists for Create React App builds. Update both files with the snippet below:
import React from 'react';
import {
AppRegistry,
StyleSheet,
View,
} from 'react-native';
import Home from './home'
class App extends React.Component {
render() {
return (
<View style={styles.appContainer}>
<Home />
</View>
);
}
}
const styles = StyleSheet.create({
appContainer: {
flex: 1,
},
});
AppRegistry.registerComponent('App', () => App);
export default App;
In the snippet above, we register our App component using the AppRegistry. The AppRegistry is the entry point of React Native applications.
Creating user item
Each user item will be displayed using a View
component. The View component is an important building block that supports layout using flexbox, styling and accessibility. The View component of each item will be within a SwipeableFlatList. Each item will display the user’s avatar, name and email. Create a file called user-item.js
within the src/
folder and update it with the code below:
// user-item.js
import React from "react";
import { View, Image, Text, StyleSheet } from "react-native";
const UserItem = ({ item: user }) => {
return (
<View style={styles.row}>
<Image style={styles.rowIcon} source={user.picture.medium} />
<View style={styles.rowData}>
<Text style={styles.rowDataText}>{`${user.name.title} ${
user.name.first
} ${user.name.last}`}</Text>
<Text style={styles.rowDataSubText}>{user.email}</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
row: {
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
padding: 15,
marginBottom: 5,
backgroundColor: "white",
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: "rgba(0,0,0,0.1)"
},
rowIcon: {
width: 64,
height: 64,
marginRight: 20,
borderRadius: "50%",
boxShadow: "0 1px 2px 0 rgba(0,0,0,0.1)"
},
rowData: {
flex: 1
},
rowDataText: {
fontSize: 15,
textTransform: "capitalize",
color: "#4b4b4b"
},
rowDataSubText: {
fontSize: 13,
opacity: 0.8,
color: "#a8a689",
marginTop: 4
}
});
export default UserItem;
To display the avatar of each user, we make use of the Image component. The component takes a source
prop which acts the src
which we are used to on the web. The component can be styled further as we have using styles.rowIcon
property.
Next, we’ll create the UserList
to display each UserItem
.
Creating users list
The FlatList component is one that is performant in its list rendering methods. It lazy-loads the items within the list, and only loads more items when the user has scrolled to the bottom of the list. The SwipeableFlatList is a wrapper around the FlatList provided by React Native Web, which makes each item within the list swipeable — so each item will reveals a set of actions when swiped.
Let’s create the SwipeableFlatList
for the users returned from the API. Import the SwipeableFlatList
component from the react-native
package and update the render function to display the list. Create a file called user-list.js
and update the file with the following:
import React from "react";
import { SwipeableFlatList } from "react-native";
import UserItem from "./user-item";
const UserList = ({ users }) => {
return (
<SwipeableFlatList
data={users}
bounceFirstRowOnMount={true}
maxSwipeDistance={160}
renderItem={UserItem}
/>
);
};
export default UserList;
data
: this prop represents the data that will be fed to each item within the list. Thedata
prop is usually an array.bounceFirstRowOnMount
: if true, it triggers on a bounce animation on the first item in the list, signifying that it has hidden actions within.maxSwipeDistance
: this prop sets a maximum swipeable distance for each item.- Finally, the
renderItem
prop takes a function that renders an item; this function will be passed anitem
prop that contains the data to be displayed.
Let’s update the home.js
file to include the new UserList
. Open the /src/home.js
file and update it with the following:
import React from "react";
import { ScrollView, StyleSheet, ActivityIndicator } from "react-native";
import UserList from "./user-list";
class Home extends React.Component {
state = {
users: [],
loading: true
};
...
render() {
return (
<ScrollView noSpacer={true} noScroll={true} style={styles.container}>
{this.state.loading ? (
<ActivityIndicator
style={[styles.centering]}
color="#ff8179"
size="large"
/>
) : (
<UserList users={this.state.users} />
)}
</ScrollView>
);
}
}
const styles = StyleSheet.create({
...
});
export default Home;
Now if you visit http://localhost:3000 on your browser, you should see a list of users, similar to the screenshot below:
If you can’t see users listed, go through the tutorial again to see what you’ve have missed along the way.
We’re using a SwipeableFlatList component which means each user item is swipeable, so let’s add actions that you can swipe to reveal. What’s the need of a SwipeableFlatList if it doesn’t reveal anything.
Adding actions to item
Each item within the list will be provided a set of actions that will be revealed when swiped to the left. The actions set will use the TouchableHighlight component encompassed by the View component. The TouchableHighlight component is used when we require viewers to respond to touches, more or less acting like a button. Create a file named user-actions.js
in the src/
folder. Open the file and copy the following contents into it:
import React from "react";
import {
View,
TouchableHighlight,
Text,
Alert,
StyleSheet
} from "react-native";
const styles = StyleSheet.create({
actionsContainer: {
flex: 1,
flexDirection: "row",
justifyContent: "flex-end",
alignItems: "center",
padding: 10
},
actionButton: {
padding: 10,
color: "white",
borderRadius: 6,
width: 80,
backgroundColor: "#808080",
marginRight: 5,
marginLeft: 5
},
actionButtonDestructive: {
backgroundColor: "#ff4b21"
},
actionButtonText: {
textAlign: "center"
}
});
const UserActions = () => {
return (
<View style={styles.actionsContainer}>
<TouchableHighlight
style={styles.actionButton}
onPress={() => {
Alert.alert("Tips", "You could do something with this edit action!");
}}
>
<Text style={styles.actionButtonText}>Edit</Text>
</TouchableHighlight>
<TouchableHighlight
style={[styles.actionButton, styles.actionButtonDestructive]}
onPress={() => {
Alert.alert(
"Tips",
"You could do something with this remove action!"
);
}}
>
<Text style={styles.actionButtonText}>Remove</Text>
</TouchableHighlight>
</View>
);
};
export default UserActions;
The TouchableHighlight component takes an onPress
callback that is triggered when the component is clicked. Each callback triggers an Alert
display. Styles are also applied to the encompassing View component and other components on the page.
To include the actions on each user item, update the UserList
component to include the renderQuickActions
prop, which also takes a function.
import React from "react";
...
import UserActions from "./user-actions";
const UserList = ({ users }) => {
return (
<SwipeableFlatList
...
renderQuickActions={UserActions}
/>
);
};
export default UserList;
Now when you swipe left on any user item it reveals two actions. It should be similar to the screenshot below:
Header component
Now that we’ve successfully fetched users and displayed them using native components, let’s liven the application by setting a header. Using the SafeAreaView component, we’ll create an area with defined boundaries. This will act as the header for our application. Create file called header.js
and update it with the code below:
// src/header.js
import React from 'react';
import {SafeAreaView, View, Text, StyleSheet} from 'react-native';
const Header = ({ onBack, title }) => (
<SafeAreaView style={styles.headerContainer}>
<View style={styles.header}>
<View style={styles.headerCenter}>
<Text accessibilityRole="heading" aria-level="3" style={styles.title}>{title}</Text>
</View>
</View>
</SafeAreaView>
);
const styles = StyleSheet.create({
headerContainer: {
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#ff4e3f',
backgroundColor: '#ff8179',
},
header: {
padding: 10,
paddingVertical: 5,
alignItems: 'center',
flexDirection: 'row',
minHeight: 50
},
headerCenter: {
flex: 1,
order: 2
},
headerLeft: {
order: 1,
width: 80
},
headerRight: {
order: 3,
width: 80
},
title: {
fontSize: 19,
fontWeight: '600',
textAlign: 'center',
color: 'white'
},
});
export default Header;
Now let’s add the Header
component to the App
component. This will display a simple header at the top of the application. Update the App.js
file to include the Header
component:
import React from 'react';
...
import Header from './header';
class App extends React.Component {
render() {
return (
<View style={styles.appContainer}>
<Header title="Random People" />
<Home />
</View>
);
}
}
const styles = StyleSheet.create({
...
});
AppRegistry.registerComponent('App', () => App);
export default App;
After the application refreshes the header will be added to the top of the application.
Looks great, doesn’t it? It won’t be winning any awards, but it might win a lot of prospective react-native-web users. We’ve been able to achieve a lot of functionality after writing minimal code.
Let’s see the various methods we can use to test the application on mobile.
Testing on mobile
To test the application on mobile, the expo-cli provides various method to test the application mobile. The first is using a URL generated after running the application, this URL can be visited on your mobile browser to test the application.
To test the application on mobile, the expo-cli provides various method to test the application mobile. The first is using a URL generated after running the application. This URL can be visited on your mobile browser to test the application.
Run the npm run start-native
command within your project folder to run the application using expo. Expo typically starts your application on port 19002
, so visit http://localhost:19002 to view the expo dev tools. Within the dev tools you can send a link as an SMS or email to your mobile phone.
You can select any of the three connection options — an external tunnel, LAN or Local connection. For the local connection, your mobile phone and work PC have to be connected to the same network, but the tunnel works regardless.
The next option for testing on a mobile device is using a emulator. Using Android studio or Xcode, you can boot emulators for their respective platforms. Download and install the tool for the platform of choice — Xcode for iOS or Android studio for Android. After installation, run npm run android
or npm run ios
to start the application on any of the emulators.
Deploying the application
We’ll be deploying our application to the Android Play store. To achieve this, we’ll need to update the app.json
to include Android specific properties. Open the app.json
file and update the file to include the android
field:
{
"expo": {
"sdkVersion": "31.0.0",
"name": "random-people",
"slug": "random-people",
"version": "0.1.0",
"description": "An application for displaying random people",
"primaryColor": "#ff8179",
"android": {
"package": "com.random.people"
}
}
}
The android.package
field is a unique value that will represent your package in the app store. You can read more on the package-naming convention here. After updating the file, run the npm run build:android
command.
This command will present you with a prompt, asking you to provide a keystore or to generate a new one. If you have an existing keystore, you can select this option or let expo generate one for your application.
After completion, a download link will be generated for your application. Clicking on this link will trigger a download for your APK.
To deploy the downloaded APKto the Android Play Store, visit the Play Console to create an account. After creating an account, you’ll be required to pay a registration fee of $25 before proceeding. After completing the registration process, visit this page and follow the steps to upload your application to the Play Store.
Summary
Using the React Native Web and React Native libraries, we’ve been able to create an application that can be deployed on several platforms using native components. Building multi-platform applications has never been easier. You can view the source code for the demo here.