How to port a React website to a mobile app in less than 5 minutes using Capacitor.js
Hello everyone, today, we will learn how to use the capacitor.js library to convert the existing react website to a mobile application in few easy steps. Before learning about capacitor.js the only way I knew to port react apps to mobile was Reactnative. But it involved rewriting the code in the view layer of the application which takes a lot of time. Instead, we can simply bundle the final build of our react application using capacitor.js to a mobile app, which is a lot quicker and easier to do as long as our web app is not too complicated or use native HTML APIs.
Prerequisites for this process are:-
You need Android Studio and emulator set up on your device for android apps. Make sure to add API level 28 or 29 SDK as shown below in Android Studio:- capacitorjs.com/docs/v3/getting-started/env..
You need XCode and simulator set up on your mac for IOS apps.
- Not necessary but it would be easy to follow along with this tutorial if you have used
create-react-app
to set up your react website.
I have a prebuilt react app for vaccine information which I will be using as an example. Source code can be found here:- github.com/codeclassifiers/storiesfeedapp/t..
If you are using this repo then run the npm install
command once after downloading the project.
So let's understand the process of converting react applications to mobile apps:-
First generate a production bundle of your application:-
npm run build
At the root of your app, install Capacitor:
npm install @capacitor/core@next @capacitor/cli@next
Then, initialize Capacitor using the CLI questionnaire:
npx cap init
The CLI will ask you a few questions, starting with your app name, and the package id you would like to use for your app. It will ask what directory your web assets get built into. For React, this is generally the build
folder.
The command will generate a capacitor.config.json
file in your project root folder.
Install the native platforms you want to target. I am only targeting the Android platform currently so the command would be:-
npx cap add android
To open the project in Android Studio, run:
npx cap open android
This will open the android ported application in Android studio. If you run the app using the run
app
button in android studio, you should be able to see the application running in the emulator as shown below:-
If at any point of time you make changes to react application then run npm run build
followed by npx cap update
to port those changes in the android application.
The next steps would be to customise the app icon, splash screens and Keystore generation before we make it live on Google Playstore. I will cover these steps in a different article.
That's it for today's article. Hope you learnt something new today. Have a nice day and goodbye ๐