LoginSignup
3
6

More than 5 years have passed since last update.

RailsでReactを使うには?(プロジェクト作成から)

Posted at

概要

Rails new (プロジェクト作成)からRailsのViewにReactを使えるようになるまでの手順です。
Bundlerを使った手順になるので、Bundlerのインストールは先に実施しておいてください。

実行環境

macOS Mojave 10.14.4
Rails 5.2.3
※Reactを使うのでnpmやyarnはインストールしておいてください

手順

Gemfile作成

bundle init
Gemfile
source "https://rubygems.org"
gem "rails"

Railsインストール

bundle install --path vendor/bundle

Railsプロジェクト作成

途中Gemfileを上書きするか聞かれるがYesで。

bundle exec rails new .

React インストール

gem 'react-rails'
gem 'webpacker'

下記コマンドでインストール。
webpackで利用するファイルとコマンドのインストールとreactをインストールする。

bundle install
bundle exec rails webpacker:install
bundle exec rails webpacker:install:react
bundle exec rails generate react:install

この段階で下記にjsが作成されています。

app/javascript

├── components
└── packs
    ├── application.js
    ├── hello_react.jsx
    └── server_rendering.js

確認用コントローラ作成

コントローラ名はなんでも大丈夫です。

bundle exec rails g controller StaticPages home

ここまでで、いったん下記にアクセスできるはずです。
http://localhost:3000/static_pages/home
本当は config/route.rb をいじってパスをいじりたいところですが、本筋からそれるのでそのまま進めます。

React読み込み準備

app/javascript 配下の components, packs を読み込むため、下記のファイルに読み込み処理を追加します。

app/views/layouts/application.html.erb

<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

これで app/javascript/components 配下にReactコードを書けば読み込むことができます。

Reactファイル作成

テスト用に下記のファイルを追加します。

app/javascript/components/test_react.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
const Hello = props => (
  <div>Hello {props.name}!</div>
)
Hello.defaultProps = {
  name: ‘Rails'
}
Hello.propTypes = {
  name: PropTypes.string
}
export default Hello

あとはviewにReactを読み込む処理を書くだけです。

Reactファイル読み込み

以下のように読み込み処理を追加します。場所はどこでもいいです。

app/views/static_pages/home.html.erb

<%= react_component("test_react", name: 'React') %>

”Hello React!” と表示されていればOKです。
以上

参考

ReactをRailsと共に使う方法
https://qiita.com/k-penguin-sato/items/e3cc04f787cf3254cfae

3
6
2

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
3
6