Share code with React Native

A few days ago, I needed to restructure a react web app in such a way, that we can build a react native app (with create-react-native-app) using as much of the existing code as possible.
So the main goal was code reuse/code sharing, while not breaking react native's reloading or introducing a complicated setup.

Restructure the files

Let's start with the initial structure. The web app web contained all code, which was structured reducers, actions, api, components and so on:

Directory web/:

├── actions
├── api
├── components
├── constants
├── index.js
├── reducers
├── resources
└── ...

The desired structure should look like this:

├── app
├── shared # Contains shared actions, reducers etc. and the HTTP API
└── web

We then move all the code which should be used by both applications in the shared directory.
Now you could use a symlink in app/node_modules/shared which points to ../../../shared but this is not really a cross-plattform solution, when for example some of your colleagues uses windows.

Configure an additional project root

A better alternative is to include the shared directory in the lookup path of react native's package manager. Simply create a rn-cli.config.js in the app directory with this content:

const path = require('path');

module.exports = {
  getProjectRoots() {
    return [path.join(__dirname, '..', 'shared'), __dirname];

This adds the shared directory (which is one level above) as a new project root besides the app directory.


As you can see, the "trick" was really easy but if you're new to the react native world like me, it may be not that obvious. I hope that I could save some of you from searching stackoverflow and browsing github issues.

Useful resources

Comments on this post

comments powered by Disqus