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;
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.
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