Rails 6 and ReactJS

Tram Ho

Rails version 6 has been released! One of the most interesting things about Rails’s latest release is its treatment of JavaScript as a first class citizen. The default Webpacker is added to startup projects with Rails CLI, along with support for using Angular, React or Vue. Now we will try to create a simple Rails application with the support of React.

First, you’ll want to make sure you update to Rails 6. You’ll need to install Ruby 2.5 and above: type ruby -v into the terminal screen to see which version you’re working on. I use RVM so to install the specified version I want I will use the rvm install 2.6.3 command. Next is to update Rails CLI: gem update rails . Now try entering rails -v in the terminal screen to check the Rails version to see if we have Rails 6.0.0 or higher.

If it’s okay, we proceed to create a new application:

In the above command, I informed the rails to skip the testing framework, skip the bundling, and install the dependencies for React. The next thing we will want to do is add the react-rails gem, incorporate a generator for React components into the list of available Rails tasks as well as allow us to perform server-side renderings with React. Ok, now we add the gem and put the project in git’s control:

On the terminal screen, if you enter rails g --help , you will see 2 new suggested commands: react:install and react:component , we will run the first command to install and it will generate some New file in our project

That is all we need to do to install. If you take a look at package.json in the project’s root directory, you’ll see all the React needed dependencies like Babel and Webpack have been added. In addition, the above statement has added a few lines to app / javascript / packs / application.js.

We will quickly create some data to display using React:

Add db / seeds.rb (using gem Faker):

We need to run rails db:migrate && rails db:seed to create tables and initialize virtual data. Now let us try to create a component with the familiar rails generate ... command:

By specifying users: array, we say that the component expects a prop to call users an array. If you look at the file that has been created, you will see this setting in prop types.

We will set up the component as follows:

And set up at users_controller.rb:

Ok now run rails s and go to http: // localhost: 3000 / users in the browser and you will see a list of all users’ names are displayed.



Share the news now

Source : Viblo