A problem I try to solve: I got this awesome idea, not only do I want to create a web app, but I also want to create a mobile app for it. Usually creating web and mobile apps require totally different tech stacks, and it is pretty hard to share code. This article shows how I added a React web app and a React Native mobile app in the same monorepo using Nx, and how I optimized codeshare between the two.
I am mostly a web developer, so let’s start with the web app first: https://xiongemi.github.io/studio-ghibli-search-engine. It is a search engine for movies and characters under Studio Ghibli:
Screenshot of web app
Example Repo: xiongemi/studio-ghibli-search-engine
Github page: https://xiongemi.github.io/studio-ghibli-search-engine
Now let’s create the corresponding mobile version of this app.
Tech Stack
- Monorepo: Nx
- Web Frontend: React
- API: https://ghibliapi.herokuapp.com/
Currently, there’s only a React web app within our Nx workspace. If I run nx graph
, the dependency graph looks like the below:
Dependency graph
React Native Setup
To get started we need to add React Native support to our Nx workspace:
❯
# npm
❯
npm install @nrwl/react-native --save-dev# yarn
❯
yarn add @nrwl/react-native --dev
Next, we can generate a new React Native app by running:
❯
npx nx generate @nrwl/react-native:app studio-ghibli-search-engine-mobile
Note, if you’re using VSCode you might want to try Nx Console for a more visual experience of running such commands.
As a result of running the above command, you should now have two new folders under the apps
directory: studio-ghibli-search-engine-mobile
and studio-ghibli-search-engine-mobile-e2e
studio-ghibli-search-engine-mobile created under apps
If we now run nx dep-graph
again, the dependency graph looks like this:
Dependency graph
Note that there is no code shared between studio-ghibli-search-engine-mobile
and studio-ghibli-search-engine-web
. However, our goal is to reuse some of the functionality that we have previously written for the web version on our new React native version of the app.
Code that Could NOT be Shared
Even though our goal is to share as much as possible between our React web app and the React Native app, there are parts that simply cannot be shared.
UI
We have to rewrite all the UI components for the mobile app. Unlike Cordova or Ionic, React Native is NOT a webview. The JavaScript we wrote got interpreted and converted to mobile native elements. Hence we cannot simply reuse UI HTML elements written for the React web app.
Here’s a quick list of libraries we’ve used for the React web app and a corresponding React Native counterpart library we can use.
Routing
- react-router-dom for web
- @react-navigation/native for mobile
Material Design Library
- @mui/material for web
- react-native-paper for mobile
Besides the above React Native libraries, there are some core utility libraries that need to be installed:
- react-native-reanimated
- react-native-gesture-handler
- react-native-screens
- react-native-safe-area-context
- @react-native-community/masked-view
- react-native-vector-icons
The corresponding install command would be:
❯
# npm
❯
npm install @react-navigation/native @react-navigation/native-stack react-native-paper react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save# yarn
❯
yarn add @react-navigation/native @react-navigation/native-stack react-native-paper react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
Storage
For the React Web app, we use redux-persist, which persists the redux store in localstorage
. However, localstorage
is not supported by React Native.
For the web, the variable persistConfig
passed to persistStore from redux-persist is:
1import storage from 'redux-persist/lib/storage';
2const persistConfig = {
3 key: 'root',
4 storage: storage,
5 whitelist: ['search', 'films', 'people'],
6 transforms: [transformEntityStateToPersist],
7};
8
However, for the mobile, we need to install the library @react-native-async-storage/async-storage
:
❯
# npm
❯
npm install @react-native-async-storage/async-storage --save-dev# yarn
❯
yarn add @react-native-async-storage/async-storage --dev
As a result, the persistConfig
passed to persistStore from redux-persist becomes:
1import AsyncStorage from '@react-native-async-storage/async-storage';
2const persistConfig = {
3 key: 'root',
4 storage: AsyncStorage,
5 whitelist: ['search', 'films', 'people'],
6 transforms: [transformEntityStateToPersist],
7};
8
History
On the React web app, we use connected-react-router to put the router state into the Redux store. However, the History API (windows.history) is not supported by React Native. As an alternative, we can use createMemoryHistory
.
For the web app, the history is:
1import { createHashHistory, History } from 'history';
2const history: History = createHashHistory();
3
For the mobile app, the history is:
1import { createMemoryHistory, History } from 'history';
2const history: History = createMemoryHistory();
3
To make our code more re-usable we could slightly refactor the creation of the root reducer with connected-react-router, such that it takes the history
object as an argument:
1import { combineReducers } from '@reduxjs/toolkit';
2import { connectRouter } from 'connected-react-router';
3import { History } from 'history';
4import { filmsSlice } from '../films/films.slice';
5import { peopleSlice } from '../people/people.slice';
6import { searchSlice } from '../search/search.slice';
7import { RootState } from './root-state.interface';
8export const createRootReducer = (history: History) =>
9 combineReducers<RootState>({
10 films: filmsSlice.reducer,
11 router: connectRouter(history) as any,
12 search: searchSlice.reducer,
13 people: peopleSlice.reducer,
14 });
15
Query Parameters
When you develop on the web, the easiest way to pass ahead state or information, in general, is to leverage the URL query parameters. In our search app example, we can simply have something like ?search=searchText
.
We can use react-router-dom to push a new history entry.
1import { useHistory } from 'react-router-dom';
2const history = useHistory();
3const submitSearchForm = (text: string) => {
4 history.push(`${AppRoutes.results}?search=${text}`);
5};
6
To read and parse the current query parameter search
:
1import { useLocation } from 'react-router-dom';
2const params = new URLSearchParams(useLocation().search);
3const searchParam = params.get('search');
4
Although the mobile app URLs are not visible, we can still pass parameters. Note that we have to use a different package @react-navigation/native
though.
1import { useNavigation } from '@react-navigation/native';
2const navigation = useNavigation();
3const submitSearchForm = () => {
4 navigation.navigate(AppRoutes.results, { search: text });
5};
6
To read and parse the parameter:
1import { RouteProp, useRoute } from '@react-navigation/native';
2const route = useRoute<RouteProp<{ params: { search: string } }>>();
3const searchParam = route.params?.search;
4
To type checking with typescript for react-navigation, we need to create a type RootStackParamList
for mappings of route name to the params of the route:
1export type RootStackParamList = {
2 [AppRoutes.search]: undefined;
3 [AppRoutes.results]: { search: string };
4};
5
We also need to specify a global type for your root navigator:
1declare global {
2 // eslint-disable-next-line @typescript-eslint/no-namespace
3 namespace ReactNavigation {
4 // eslint-disable-next-line @typescript-eslint/no-empty-interface
5 interface RootParamList extends RootStackParamList {}
6 }
7}
8
So we create the stack navigator, we need to pass the above RootStackParamList
type:
1import { createNativeStackNavigator } from '@react-navigation/native-stack';
2const Stack = createNativeStackNavigator<**RootStackParamList**>();
3
Environment Variables
Nx comes with a set of different options for handling environment variables. In our workspace, we have a simple .env
file at the workspace root:
1NX_REQUEST_BASE_URL=://ghibliapi.herokuapp.com
2
This works nicely for our React web build, but it doesn’t for our React Native application. This is because React Native and React apps use different Javascript bundlers. React Native uses Metro and React uses Webpack. Therefore, when we try to access process.env.NX_REQUEST_BASE_URL
, we get undefined
.
To solve this, we can use the react-native-config library
❯
# npm
❯
npm install react-native-config --save-dev# yarn
❯
yarn add react-native-config --dev
Here’s an example of how to set up react-native-config: https://github.com/luggit/react-native-config#setup.
After that, we can have a simple utility function to retrieve the environment variables in our app.
1import Config from 'react-native-config';
2export function getEnv(envName: string) {
3 return process.env[envName] || Config[envName];
4}
5
To access the environment variable NX_REQUEST_BASE_URL
, we can then simply use the above function:getEnv(‘NX_REQUEST_BASE_URL’)
.
Fetch With HTTP
On the web, you most probably lean on the fetch API to make network requests. On iOS, however, you’ll get an error saying: TypeError: Network request failed
.
It turns out that React Native does not allow HTTP requests by default: https://stackoverflow.com/questions/38418998/react-native-fetch-network-request-failed.
To fix this, for iOS, open apps/studio-ghibli-search-engine-mobile/ios/StudioGhibliSearchEngineApp/Info.plist
and add the request URL to NSExceptionDomains
under NSAppTransportSecurity
:
1<key>NSAppTransportSecurity</key>
2 <dict>
3 <key>NSExceptionDomains</key>
4 <dict>
5 <key>localhost</key>
6 <dict>
7 <key>NSExceptionAllowsInsecureHTTPLoads</key>
8 <true/>
9 </dict>
10 <key>ghibliapi.herokuapp.com</key>
11 <dict>
12 <key>NSExceptionAllowsInsecureHTTPLoads</key>
13 <true/>
14 </dict>
15 </dict>
16 </dict>
17
Similarly, for Android, open apps/studio-ghibli-search-engine-mobile/android/app/src/main/res/xml/network_security_config.xml
, and add the request URL to this config file:
1
2<network-security-config>
3 <domain-config cleartextTrafficPermitted="true">
4 <domain includeSubdomains="true">10.0.2.2</domain>
5 <domain includeSubdomains="true">localhost</domain>
6 <domain includeSubdomains="true">herokuapp.com</domain>
7 </domain-config>
8</network-security-config>
9
This should get rid of the network error.
It seems like there are quite a few customizations that need to be done for React Native apps. However, the majority of non-UI code could be reused.
Code that Could be Shared
All the business logic code that is not UI could be shared. For this example, I got 3 libraries in my monorepo and all of them could be shared:
- models: types and interface definitions
- services: services that interact with API
- store: redux store
With Nx, it requires zero configuration to share the above library code. Even though when I created these libraries for a web app, I used commands like nx generate @nrwl/react:lib store
, I could still use them directly in my react native mobile app.
For example, I need to create a film page to display film details with film id passed in as a parameter:
Screenshot of Film Page on Mobile (left: iOS, right: Android)
I would do import from the store library directly:
1import {
2 filmsActions,
3 filmsSelectors,
4 RootState,
5} from '@studio-ghibli-search-engine/store';
6
The film component would become:
1import { AnyAction, ThunkDispatch } from '@reduxjs/toolkit';
2import {
3 filmsActions,
4 filmsSelectors,
5 RootState,
6} from '@studio-ghibli-search-engine/store';
7
8const mapStateToProps = (state: RootState) => {
9 return {
10 getFilm: (id: string) => filmsSelectors.selectFilmById(id)(state),
11 };
12};
13
14const mapDispatchToProps = (
15 dispatch: ThunkDispatch<RootState, void, AnyAction>
16) => {
17 return {
18 fetchFilms() {
19 dispatch(filmsActions.fetchFilms());
20 },
21 };
22};
23
24type mapStateToPropsType = ReturnType<typeof mapStateToProps>;
25type mapDispatchToPropsType = ReturnType<typeof mapDispatchToProps>;
26
27type FilmProps = mapStateToPropsType & mapDispatchToPropsType;
28
29export { mapStateToProps, mapDispatchToProps };
30export type { FilmProps };
31
1import { RouteProp, useRoute } from '@react-navigation/native';
2import { FilmEntity } from '@studio-ghibli-search-engine/models';
3import { getEnv } from '@studio-ghibli-search-engine/services';
4import React, { useEffect, useState } from 'react';
5import { SafeAreaView, ScrollView, Image, View } from 'react-native';
6import {
7 Button,
8 Divider,
9 Headline,
10 Paragraph,
11 Subheading,
12 Title,
13} from 'react-native-paper';
14import { styles } from 'react-native-style-tachyons';
15import { connect } from 'react-redux';
16
17import Loading from '../shared/loading/loading';
18import { useLink } from '../shared/open-link/open-link';
19
20import { FilmProps, mapDispatchToProps, mapStateToProps } from './film.props';
21
22export function Film({ getFilm, fetchFilms }: FilmProps) {
23 const [film, setFilm] = useState<FilmEntity>();
24
25 const route = useRoute<RouteProp<{ params: { id: string } }>>();
26 const id = route.params?.id;
27
28 const openHboMax = useLink(getEnv('NX_HBO_STREAMING_URL'), 'HBO Max');
29 const openNetflix = useLink(getEnv('NX_NETFLIX_STREAMING_URL'), 'Netflix');
30
31 useEffect(() => {
32 fetchFilms();
33 }, [fetchFilms]);
34
35 useEffect(() => {
36 setFilm(getFilm(id));
37 }, [id, getFilm]);
38
39 return film ? (
40 <SafeAreaView>
41 <ScrollView contentInsetAdjustmentBehavior="automatic">
42 <View style={[styles.pa3]}>
43 <Image
44 style={{ height: 200, width: '100%', resizeMode: 'contain' }}
45 source={{ uri: film.movieBanner }}
46 />
47 <Headline>{film.title}</Headline>
48 <Subheading>
49 {film.originalTitle} / {film.originalTitleRomanised}
50 </Subheading>
51 <Paragraph>Release: {film.releaseDate}</Paragraph>
52 <Paragraph>Director: {film.director}</Paragraph>
53 <Paragraph>Producer: {film.producer}</Paragraph>
54 <Paragraph>Running Time: {film.runningTime} minutes</Paragraph>
55 <Paragraph>Rotten Tomatoes Score: {film.rtScore}</Paragraph>
56
57 <Divider />
58
59 <Title>Plot</Title>
60 <Paragraph>{film.description}</Paragraph>
61
62 <Divider />
63
64 <Button onPress={openHboMax}>Watch on HBO Max</Button>
65 <Button onPress={openNetflix}>Watch on Netflix</Button>
66 </View>
67 </ScrollView>
68 </SafeAreaView>
69 ) : (
70 <Loading />
71 );
72}
73
74export default connect(mapStateToProps, mapDispatchToProps)(Film);
75
Note I could import from @studio-ghibli-search-engine/models
, @studio-ghibli-search-engine/services
and @studio-ghibli-search-engine/store
directly.
Now when I run nx dep-graph
, it shows the dependency graph below where all these 3 libraries are shared between web and mobile:
Dependency graph
For this example project, to create the mobile app, it took me some time to rewrite the entire UI. However, I do not need to make any changes to the above libraries.
Screenshots of Mobile App (left: iOS, right: Android)
Conclusion
In this article, we ended up building both, a React-based web application and a corresponding React Native app in the same repository using Nx.
Nx’s architecture promotes the separation of concerns, splitting things into apps
(which are technology-specific) and libs
which can be technology-specific or technology-independent. That allows us to easily have our common business logic in a technology-independent library which in turn (thanks to Nx’s setup) be easily linked to both, our React web and React Native mobile app.
Although there are UI-specific differences we need to account for, that simply comes with one being a web tech stack and the other being a native app, we were still able to share big chunks of the technology-independent business logic of our application. That ultimately helps with maintenance and having feature parity across different platforms.
(Note, the repository with the code for this article is linked at the very top)