Hey Developers!
I am a React Native Developer and received one project with two different applications, having similar business logics and UI designs. And then I realized, there will be some duplicate or redundant code in both applications, and as a developer, we should follow DRY (Don’t Repeat Yourself) principle.
That’s why, I started looking for an architecture to avoid duplicate code across the projects. And then I came across one of the most popular options to do so — MONOREPO.
In this article, You will see how you can use multiple applications with React Native in one Monorepo-
Firstly, let’s understand the term Monorepo -
Simply said, it is a repository that contains code for many projects and packages.
Monorepo allows you to have multiple projects share common dependencies instead of installing the dependencies for each of them, while simplifying code sharing between projects, allowing you to import code from one package to another and Redux logic.
Great! Now that we got the concept straight, let’s start implementation using Nx.
Nx is a smart, fast and extensible build system with first class monorepo support and powerful integrations.
Now, let’s make the project structure —
npx create-nx-workspace <your_app_name> --preset=react-native
nx generate application <your_app_name>
This should generate <your_app> folder under apps.
Now you can install the starter project of Nx React Native. If you run:
To create a common library, where you keep common code/logics for both the applications:
This should generate <your_lib> folder under libs.
There can be some common components as well that are used across both React Native apps.
nx generate component <your-component-name> --project=ui --export
This generates the folder <your-component-name> under ui/src/lib.
Now you can write your common UI code in the above component and use this component in both the application in app.js.
When you run nx run-ios <your-app-name> and nx run-android <your-app-name>, you should see something like this:
Congratulations! You have created React Native mobile apps. 🎉🎉
Nx + React Native is a powerful tool that allows you to have multiple mobile applications code in the same repo with shared business logic.
For Source code, you can check the Github repo.
Happy Coding!😊