React + Rails

Una interesante combinación

Jairo Fernández

Desarrollador frontend en Youse

rails new react-app --webpack=react
rails webpacker:install

+ 108MB...

Aunque solo se usan para desarrollo, en producción es considerablemente bajo

rails generate react:install

Text

Text

+ 5 MB

gem 'webpacker'
gem 'react-rails'
bundle install
rails webpacker:install       
rails webpacker:install:react
rails generate react:install
# app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>MyApp2</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

Habilitamos los componentes en el layout principal

rails g react:component HelloWorld greeting:string

Creando nuestro primer componente

rails g react:component HelloWorld greeting:string
# app/javascript/components/HelloWorld.js

import React from "react"
import PropTypes from "prop-types"
class HelloWorld extends React.Component {
  render () {
    return (
      <React.Fragment>
        Greeting {this.props.greeting}
      </React.Fragment>
    );
  }
}

HelloWorld.propTypes = {
  greeting: PropTypes.string
};
export default HelloWorld

¿Cómo lo usamos?

rails g controller hello index
# app/controllers/hello_controller.rb

class HelloController < ApplicationController
  def index
  end
end
# config/routes.rb

Rails.application.routes.draw do
  get 'hello/index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
# app/views/hello/index.html.erb

<h1>Hello#index</h1>
<p>Find me in app/views/hello/index.html.erb</p>
# app/controllers/pages_controller.rb

class PagesController < ApplicationController
  def index
    @greet_from_controller = 'Hello from controller'
  end
end
# app/views/hello/index.html.erb

<%= react_component("HelloWorld", { greeting: @greet_from_controller }) %>
rails s

Que cosas fueron añadidas...

Que cosas fueron añadidas...

# app/javascript/packs/application.js

/* eslint no-console:0 */

console.log('Hello World from Webpacker')
// Support component names relative to this directory:
var componentRequireContext = require.context("components", true);
var ReactRailsUJS = require("react_ujs");
ReactRailsUJS.useContext(componentRequireContext);

La magia!

Live reload

bundle exec ./bin/webpack-dev-server

Hasta este momento

 

1. Estamos usando la configuración básica de React en nuestro proyecto

 

2. Ya podemos usar Reactjs en nuestros views.

rails g react:component Post title:string published:bool published_by:instanceOf{Person}

Recursos

React + Rails! Simple

By Jairo Fernández

React + Rails! Simple

  • 93
Loading comments...

More from Jairo Fernández