Ruby on Rails
What is React with Rails App
The rails application, that provides a backend with React JS. The beauty of Rails with the efficiency of React will let us build powerful and modern applications informed by current trends. By using the React JS library to render components from within a Rails view instead of the Rails action view, your application will benefit from the latest advancements in the JavaScript programming language and front-end development. So we can easily create a React with Rails app.
What is React JS?
React is the open-source, flexible, declarative JS library created by Facebook. It is a UI library that allows developers to create UI efficiently. We can create components of UI using React. React can be used for the development of single-page or mobile applications. React JS uses virtual DOM (Document Object Model) that allows us to access and change document contents, layout, and structure. Virtual DOM allows us to update the changes without rewriting the entire HTML doc virtually. This renders updates much faster and ensures fast performance.
The virtual DOM is a node tree. That lists the elements and their attributes and contents as objects and properties. The render() method of React creates a node tree from the React Components. Every time data changes in a React app, a new Virtual DOM representation of the user interface is created.
What is the Rails framework?
Rails is the backend framework created in the ruby programming language. This provides a lot of features for the backend server. We can easily write the backend of the web application in rails. Rails (framework) includes everything needed to create database-backed web applications according to the Model-View-Controller (MVC) pattern.
What is WebPack?
A webpack is a static module bundler for modern JavaScript applications and is used to manage the Javascript modules. When webpack processes your application, it internally builds a dependency graph that maps every module your project needs.
Rails provides a webpack as a gem named webpacker, Webpacker makes it easy to use the JavaScript pre-processor and webpack bundler to manage applications like JavaScript in Rails. By using webpacker we can create a React with Rails app.
Create React with Rails App using Webpacker
When we create the Rails application with react then the webpacker installs the react module in the rails using yarn. Webpack instructs Rails to configure the React JS and automatically install the dependencies of React in Rails.
Lets setups the project by using the following command
rails new blog-rails -d=postgresql --webpack=react
This command creates the rails project. It will add the “hello_react.jsx” file in the app/javascript/packs folder. This file has a React component that renders some layout. After that run the command to create the database
rails db:create
Run the command "rails s". This command runs the server. And you can test it by visiting the "http://localhost:3000" link.
Create a home controller with the command:
rails g controller home index
This command not only creates the controller but also creates the index action with the layout file. Then go to the layout file and remove all code i.e.
<%= javascript_pack_tag 'hello_react' %>
Go to file routes.rb to add the new routes as follows
root 'home#index'
Enter the key "Ctrl + c", this will stop the server. Then run the command "rails s". This command runs the server. And you can test it by visiting the "http://localhost:3000" link. You will see the page saying Hello React!.
In the "hello_react.jsx" file, a hello component renders the "Hello React!".
Also, we can add routes to React. For routes, we need some concepts of React JS.
BrowserRouter
It uses the HTML5 history APIs pushState, replaceState, and the popState event to keep the User Interface in sync with the URL.
Route
It represents the path for the URL. If we want to render a component in another URL then we use Route.
Switch
This component is used to render the first matching route in the browser window. We have two routes first for the home page and second, for the about us page. We define these routes in the Switch component the result is, It will render the home page because the home page route is defined first.
Define Components
Create the component folder inside the javascript folder. Inside this directory, create the three components: Home, About Us, and Blog. Also, define the APP component. In this component, we define the Routes for these components.
Home Component
import React from 'react'
import { Link } from "react-router-dom";
class Home extends React.Component {
render() {
return (
<>
<h1> This is home page.</h1>
<Link to="/blog"> Go To Blog </Link>
<br/>
<Link to="/about-us"> Go To About Us </Link>
</>
)
}
}
export default Home
AboutUs Component
import React from 'react'
import { Link } from "react-router-dom";
class AboutUs extends React.Component{
render() {
return (
<>
<h1> This is about us page.</h1>
<Link to="/blog"> Go To Blog </Link>
<br/>
<Link to="/"> Go To Home </Link>
</>
)
}
}
export default AboutUs
Blog Controller
import React from 'react'
import { Link } from "react-router-dom";
class Blog extends React.Component{
render() {
return (
<>
<h1> This is blog page.</h1>
<Link to="/"> Go To Home </Link>
<br/>
<Link to="/about-us"> Go To About Us </Link>
</>
)
}
}
export default Blog
App Component
import React from 'react';
import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import Home from "../components/Home";
import AboutUs from "../components/AboutUs";
import Blog from "../components/Blog";
class App extends React.Component {
render() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/blog" exact component={Blog} />
<Route path="/about-us" exact component={AboutUs} />
</Switch>
</Router>
)
}
}
export default App
Then add the new route in routes.rb as: get '/*path', to: 'home#index'
After that go to the /app/javascript/packs/ and run the command:
mv hello_react.jsx Index.jsx
Now you need to replace the code inside the /app/view/home/index.html.erb with
<%= javascript_pack_tag 'Index' %>
Inside the index.jsx file code should be like:
import React from 'react'
import ReactDOM from 'react-dom'
import App from "../components/App";
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<App />,
document.body.appendChild(document.createElement('div')),
)
})
When you navigate the http://localhost:3000/ then you will see the home page
When you navigate the http://localhost:3000/blog then you will see the blog page.
When you navigate the http://localhost:3000/about-us then you will see the about us page.
Conclusion
In this tutorial, you created a basic React with Rails app, using PostgreSQL as your database. This app provides a complete understanding of using React JS in Ruby on Rails application. Also, you have learned the routes in React and how we can manage Rails Routes with React Routes.
Rails is most suitable framework to build your startup.
Rails is a go-to web framework when you want to create a complex web application. But when it comes to APIs there are many players like Roda, Sinatra, Padrino, Grape and, Rails API.
A universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems. Sometimes it is referred to as a 'globally unique identifier'.
We value your privacy
We use cookies and other tracking technologies to enhance your experience on our website. We may store and/or access information on a device and process personal data, such as your IP address and browsing data, for personalized advertising and content, advertising and content measurement, audience research, and services development. Additionally, we may use precise geolocation data and identification through device scanning. Please note that your consent will be valid across all our subdomains. You can change or withdraw your consent at any time. We respect your choices and are committed to providing you with a transparent and secure browsing experience.