Adding React.js to Rails
We will be building our application's frontend in
React.js, and for this, we will be using
react-rails gem to bring React to our
Ruby on Rails application.
Add the following line to the end of the Gemfile
:
Then install the newly added gem:
Setup React pipeline
Let's install React and other required npm packages by running:
Complete the React integration by running:
Executing the command above installs the most recent edition of react_ujs
, which brings about certain disruptive modifications. To revert, let's downgrade it to version 3.1.1
using the subsequent command:
And now we have successfully added React.js support to our application.
We have to delete the folders inside app/assets
directory which were
automatically created upon running the above command.
Run the following from the root of the project:
Setting up the asset manifest
We need to create a proper manifest file to help Rails
locate our assets built by ESBuild.
Run the following commands to set it up:
Explicitly registering React components
Fully replace app/javascript/packs/application.js
with the following
lines of code:
These lines register our React components with ReactRailsUJS, allowing Rails to find and render the correct component.
Directory structure
The src
folder is where the JavaScript code specific to the application is
handled at. This includes apis
, commons
etc.
In upcoming chapters, when we create the components
folder, we will be adding
it under the src
folder.
This is done so as to handle all the JavaScript/client code under a single path
and have more control over it.
With the last change we made to application.js
, we have ensured
that our Vite configuration knows that our application-relevant
code should be loaded from the src
folder.
If you want to load components or JavaScript files from a different directory, then
override the default by updating the Vite configuration. If a specified path
fails to resolve, Vite will fall back to its standard behavior.
Note: npm install
command would add package-lock.json
which isn't required
as we are using Yarn. Thus avoid using npm install
. If executed then please
don't commit the package-lock.json
file. Add package-lock.json
to the
.gitignore
file. Use yarn add
command for installing new packages.
Now let's commit the changes: