Hello World with NX and React Native
I’ve been exploring React Native recently with NX to add native applications to existing repositories that have to React applications in them. This is to start to see how you can use NX and shared libraries to have common logic and views shared between the mobile and web portions of the application or site. Here is the Hello World setup for nx that will add a React Native application to an NX repo. This starts by creating an NX repository, in case you don’t already have an application repo to start with.
Creating the Nx Workspace
The easiest way to make the repository is to use npx. First ensure you have the latest version of node installed, and then issue the following commands.
npx create-nx-workspace workspace \
--preset=react-native \
--appName=mobile
NX will ask you about using cloud builds, it’s up to you to choose, but for this sample, it’s probably best to choose No
. It will then install all the required dependencies, depending on your machine and internet connection, this may take a few minutes. Once it is finished, move into the workspace directory and continue on.
Building the Application
Now that you have the default application running, I always recommend before you add any code that you try to run the mobile app, just to troubleshoot any potential issues that you may have.
npx nx run-android mobile
This will start Metro, and hopefully, launch your app for you in the emulator. If you see an error like “No emulators, manually run the emulator”, you will need to do as it says, and install or choose an emulator for Android. One easy way to solve these problems is using React Native’s doctor command.
react-native doctor
This will help, depending on the issue, they may be fixed automatically (by choosing f
) or they may require you to do more, but instructions will be provided. Once you have the app running in the emulator, we can move on. Also if you are working on iOS, you can build with the following.
npx nx run-ios mobile
Running Tests
It’s a great habit to get into, to run the tests early and often. To do so simply run the following commands.
npx nx test-android mobile-e2e
Repository
Just in case you are interested in seeing the code, here is the public repository for the above.