How to set up a Rails 7 project with React and Jest
With Rails 7, we got some new ways of working with Javascript. The importmap was introduced by DHH as a default option for new Rails projects, and also he made a video showing how to use React with it, without .jsx.
But honestly, it’s a little weird.
So, I will show how to work with React in Rails 7, with all the old, good, and battle tested tools that we all already know, and also a lovely way to keep these tools integrated too:
Let's do it.
1. Create a new rails 7 project with -j=esbuild option:
$ rails new your_project -j=esbuild
2. Install react and react-dom:
$ cd your_project && npm i react react-dom
3. Create a file in: app/javascript/react/src/components/Hello.jsx:
import * as React from 'react'
import * as ReactDOM from 'react-dom'
const Hello = () => {
return (<div>Hello, Rails 7!</div>)
}
// Use it if you don't plan to use "remount"
// document.addEventListener('DOMContentLoaded', () => {
// ReactDOM.render(<Hello />, document.getElementById('hello'))
// })
export default Hello
4. Install remount:
With remount we can render our components using simple HTML tags wherever in the project.
$ npm i remount
5. Create a file in: app/javascript/react/src/index.js:
In this file, we will map all our components to specifics HTML tags.
import { define } from 'remount'
import Hello from "./components/Hello"
define({ 'hello-component': Hello })
6. Import the React index in: app/javascript/application.js:
// Entry point for the build script in your package.json
import "./react/src/index.js"
7. Generate a controller for test purposes:
rails g controller hello world
8. Import our component in app/views/hello/world.html.erb:
<h1>Hello#world</h1>
<hello-component/>
9. Run the app with ./bin/dev:
Yes, no rails server
With ./bin/dev
our changes in react components will be watched.
$ ./bin/dev
Now you can see our component in http://localhost:3000/hello/world
Testing our component with Jest
Testing is important in the front-end side too, right? Don’t miss that!
1. Install jest and dependencies:
$ npm install — save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer
2. Create a babel.config.js in the root rails app with:
module.exports = {
presets: [‘@babel/preset-env’, ‘@babel/preset-react’],
};
3. Now, write the tests in app/javascript/react/src/components/Hello.test.jsx:
import React from 'react'
import renderer from 'react-test-renderer';
import Hello from './Hello';
test('My test', () => {
// Write tests here
});
4. Finally, run:
npm run test
And we are done!
Enjoy it!
❤️
Next steps
Improve your skills with remount, esbuild and jest: