0

React With Ruby On Rails

React With Ruby On Rails

React With Ruby On Rails.png

With this article, We want to show you guy about React and we will apply react with Rails application. It will be the asome that you never see before with reload page with react. For the first begining what we need to know what is react ? what is engineer that develop react ? why do they need react ? And second step we start to write React with Rails application.

What is React ?

React (sometimes styled React.js or ReactJS) is an open-source JavaScript library providing a view for data rendered as HTML. React views are typically rendered using components that contain additional components specified as custom HTML tags. React promises programmers a model in which subcomponents cannot directly affect enclosing components ("data flows down"); efficient updating of the HTML document when data changes; and a clean separation between components on a modern single-page application.

Other Meaning React is a javascript library for building user interface (UIs). Some people use it as the V (View) in MVC (Model View Controller).

Why React?

With React was built to solove one problem: building large application with data that change over time. It means the complex application that updates every time as Facebook, Twitter, Dropbox, NetTLIX, react can handle it very easy. Because with react have:

  • It is better abstraction than MVC!
  • React keeps track of what needs to change in the DOM with its virtual DOM model.
  • All the view rendering code can assume that nothing changes during the rendering process as components recursively call render(). This makes reasoning about the rendering code much simpler.
  • The simpler conceptual model of always rendering the entire UI from a given state is akin to the server side rendering of HTML pages, that Rails programmers are more familiar with.

Who develop React ?

React have been developed by Facebook engineer. It does not use only facebook but it has been used by other famous company around the world as: PayPal, Instagram, Airbnb ...

How React works

In React, it allows us to solove problems by creating components. If a component gets too complex, we break it into smaller, simpler components.

Component.png

You can see with example above, we share components of that page to smaller component: Component Detail Movie, Component Mediaplayer, Component Recommend and Component Footer.

What Is a React Component ?

A simple meaning we can understand in react, a component works similary to javascript functions: It generates an out put everytime it is invoked.

React.png

It means you just write your code in your component (javascript code) that extends React Component will generate components from virtual dom to HTML. It spends to 3 steps of the thing, that you can see it below:

  • React Component -> Virtual DOM -> HTML
  • Virtual DOM diffing allows React to minmize changes to the DOM as a result of user actions therefore, increasing browser performance.

How to apply it on Ruby On Rails

Now let's begin it with Rails application, we will create new application:

$ rails new reactjs_with_rails

switch to folder new_with_rails, to use React with Rails application, you need to add gem react-rails into your application.

$ bundle install
$ rails g react:install

The react:install generator will automatically include the react JavaScript library in your asset pipeline

$ rails g react:install
Running via Spring preloader in process 13313
      create  app/assets/javascripts/components
      create  app/assets/javascripts/components/.gitkeep
      insert  app/assets/javascripts/application.js
      insert  app/assets/javascripts/application.js
      insert  app/assets/javascripts/application.js
      create  app/assets/javascripts/components.js

Like JQuery and the rest of the JavaScript libraries, react and react_ujs are included in the asset pipeline. The components folder in the assets/javascripts directory is where we’ll store our components. Speaking of components, these are the building blocks of the React framework. They’re used to separate the different sections of a user interface and are structured in a parent-child relationship, similar to the way nested AngularJS controllers work. How let's start with hello world in React, now we need to create controller and view in rails by the short code rails g controller statics

$ rails g controller statics
Running via Spring preloader in process 13619
      create  app/controllers/statics_controller.rb
      invoke  erb
      create    app/views/statics
      invoke  test_unit
      create    test/controllers/statics_controller_test.rb
      invoke  helper
      create    app/helpers/statics_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/statics.coffee
      invoke    scss
      create      app/assets/stylesheets/statics.scss

We create view touch app/views/statics/index.html.erb and create file component of react touch app/assets/javascripts/components/hello_world.jsx

// app/assets/javascripts/components/hello_world.js
class HelloWorld extends React.Component {
  render() {
    return(
      <h1>Hello World</h1>
    )
  }
}

and to show this in your view, you need to add code below into app/views/statics/index.html.erb

# app/views/statics/index.html.erb
<%= react_component "HelloWorld" %>

The react_component is part of react-rails. In this case, it’s used to put the component named HelloWorld from the components folder in the assets directory into the view.

react hello.png

How let's start to connnect react with model in rails. we create new model call it movies,

$ rails g model Movie title:string description:text
$ rails db:migrate

Now it's time to populate our database with sample data.

#db/seed.rb
30.times{Movie.create!(title: "Movie Title", description: "I am a description.")}

After that we need to run rails db:seed. How can we show 30 movies in view by using react that query by rails application. To handle this thing please follow us, now we create controller movie.

$ rails g controller movies

For using result query rails in react we need to use result of query in rails as json and in react we use the ajax to get result json from rails, so we need 2 step this:

  • Convert result of rails from controller to view as json in rails controller
  • use ajax to get result from json of rails in react component

To convert result of rails from controller to view as 'json' we want to introduce you about one gem it is called gem "responders", add it into gem file

gem "responders"

and then run bundle install, In app/controllers/movies_controller.rb we put method index.

# app/controllers/movies_controller.rb

class MoviesController < ApplicationController
  respond_to :json

  def index
    movies = Movie.all
    respond_with movies
  end
end

and in routing the controller

Rails.application.routes.draw do
  root "statics#index"
  resources :movies, only: :index
end

Now you can test it by link below:

http://localhost:3000/movies.json

movie_json.png

Now seconde step we create new file jsx, touch app/assets/javascripts/components/movies.jsx

class Movies extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      movies: [],
    }
  }

  componentDidMount() {
    var url = "http://localhost:3000/movies.json";

    $.ajax({
      url: url,
      method: "GET",
      dataType: "json",
      success: (data) => {
        this.setState({
          movies: data,
        });
      }
    });
  }

  render() {
    var movies = this.state.movies.map((movie) =>{
      return (
        <div key={movie.id}>
          <h3>{movie.title}</h3>
          <p>{movie.description}</p>
        </div>
      )
    });

    return (
      <div>
        {movies}
      </div>
    )
  }
}
  • constructor(props, context) is constructor of react
  • componentDidMount is executed after first render only on the client side. This is where AJAX requests and DOM or state updates should occur. This method is also used for integration with other JavaScript frameworks and any functions with delayed execution like setTimeout or setInterval. We are using it to update the state so we can trigger the other lifecycle methods.

We will receive result as this:

result.png

Conclusion

In this article, just sample how to use React in rails application, and if you want to see more advance about React, please follow our next article. We will show you how to use Component Life Cycle. We hope that this article will help you guy if you are beginner with React in Rails. code this article

Documentation


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí