React Js into Ruby On Rails application

Create New Application: 
$ rails new rails-react-webpacker
$ cd rails-react-webpacker
Add webpacker and react-rails to your Gemfile and run the installers

$ bundle install
$ rails webpacker:install 
$ rails webpacker:install:react
$ rails generate react:install
After the successful completion the of the above commands. You will have the directory structure like below image.

All of our React components shall go to app/javascript/components/directory.
The content of app/javascript/packs/application.js is as following.
console.log('Hello World from Webpacker')
var componentRequireContext = require.context("components", true)
var ReactRailsUJS = require("react_ujs")
ReactRailsUJS.useContext(componentRequireContext)

The line var componentRequireContext = require.context(“components”, true) makes the react components available to our rails app.
Now we just need to add the above file into our application layout file at app/views/layouts/application.html.erb
<%= javascript_pack_tag 'application' %>

Let’s create a home controller with index method. We will mount our first react component to app/views/home/index.html.erb file.
$ rails g controller home index

Now let’s create our first React Component.

 rails g react:component GreetUser name:string
Running the above command will create our first react component at app/javascript/components/GreetUser.js .
Now replace contents of app/javascript/components/GreetUser.js to match below.
// Path : app/javascript/components/GreetUser.js
import React from "react";
import PropTypes from "prop-types";
class GreetUser extends React.Component {
render () {
return (
<div>
<h1>Hello {this.props.name}, </h1>
<h3>Wow! This is your first react component!</h3>
</div>
);
}
}
GreetUser.propTypes = {
name: PropTypes.string
};
export default GreetUser;
In above file the GreetUser component is expecting name props.
Now to add the component to view we need to use the react_componenthelper. So change the contents of app/views/home/index.html.erb to match below.
<%= react_component 'GreetUser', name: 'Arvind' %>

Comments

  1. When planning a budget for your software development, make sure to take into account all factors and risks which might be involved. This article will help you with estimating software development cost

    ReplyDelete

Post a Comment

Popular Posts

How to pass hash in Postman

nginx: unrecognized service

Reading Excel Sheets using "Roo" gem in ruby on rails

Bootstrap Select Picker append add new item if search not exist

Add CORS to Nginx on AWS Elastic Beanstalk

Enable gzip compression on Elastic Beanstalk with nginx

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Get video duration by URL in Ruby on Rails

site-enables nginx setting in ruby in rails