LoginSignup
28
33

More than 3 years have passed since last update.

【裏ワザ付き】一番シンプルなRailsにReactを導入する方法

Last updated at Posted at 2020-08-13

Rails + React or Vueの構成は最近のWeb系企業で非常にポピュラーな構成です。
今回はhookの登場でますます勢いを増すReactをRailsに導入します。

実行環境

ruby 2.6.3p62
Rails 6.0.2.2

Gemをインストール

Helperを使用する為にはGemのインストールが必要です。
Gemfileに以下を追記してbundle install
※Rails 5系の場合はgem 'webpacker'も必要

Gemfile
gem 'react-rails'
# Rails 5系は以下も追記
gem 'webpacker'

Reactをインストール

ターミナルで以下のコマンドを実行。

terminal
$ bin/rails wepacker:install:react
$ bin/rails g react:install

# Rails 5系では以下も実行
$ bin/rails webpacker:install

すると次の様な変更が加わります。

app/javascript/components/ディレクトリが追加
Reactのファイルはここに作成していきます。

app/javascript/packs/application.jsにReactを組み込む処理が追加

app/javascript/packs/application.js
// 以下のコードが末尾に追加
// Support component names relative to this directory:
var componentRequireContext = require.context("components", true);
var ReactRailsUJS = require("react_ujs");
ReactRailsUJS.useContext(componentRequireContext);

app/javascript/packs/server_rendering.jsにサーバー側のレンダリング処理(SSR)が追加

app/javascript/packs/server_rendering.js
// 以下のコードが末尾に追加
// By default, this pack is loaded for server-side rendering.
// It must expose react_ujs as `ReactRailsUJS` and prepare a require context.
var componentRequireContext = require.context("components", true);
var ReactRailsUJS = require("react_ujs");
ReactRailsUJS.useContext(componentRequireContext);

※Rails 5系の場合は加えてapp/views/layouts/applicationi.html.erbのヘッダーに以下を記載する必要があります(6ではデフォルトで記載)

app/views/layouts/applicationi.html.erb
<%= javascript_pack_tag 'application' %>

以上で準備は完了です。

コンポーネントの作成

試しにHelloWorldというコンポーネントを作成します。
以下のコマンドを実行します。

terminal
$ bin/rails g react:component HelloWorld greeting:string
Running via Spring preloader in process 12477
      create  app/javascript/components/HelloWorld.js

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

Railsへ導入

railsの erbファイル内のコンポーネントを適用したい箇所に以下のコードを追加することで導入完了です!
<%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>

裏技!

Reactのインストール時にapp/javascript/packs/application.jsに自動追記されるコードは、全てのページでReactのコードを読み込む処理なので、Reactが導入されていないページにも適用されレスポンスが低下してしまいます。
自動追記された部分を削除し、Reactを導入するページにのみ
<%= javascript_pack_tag 'server_rendering.js' %>
を追加することでこれを回避することができます。

28
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
33