LoginSignup
7
9

More than 3 years have passed since last update.

既存のRailsアプリにReactを導入する方法

Posted at

概要

yarn、Webpacker、react-railsを使います。

1.Yarnのインストール

nodeが入っている場合

$brew install yarn --without-node

nodeが入っていない場合

$brew install yarn

2.Webpacker をインストール

Gemfileにwebpackerを追加します。

Gemfile
gem 'webpacker'

bundle(bundle install)を実行。
インストールが終わったら、以下を実行。

$bundle exec rails webpacker:install

3.既存アプリへReactを導入する

$bundle exec rails webpacker:install:react

application.html.slimに以下追記

application.html.slim
= javascript_pack_tag    'application'

4.Gem react-railsをインストール

gem 'react-rails'

bundle(bundle install)を実行。

$rails g react:install

5.実際に使ってみる

以下でReactコンポーネントを作成。

$rails g react:component Hello

app/javascript/components/以下にHello.jsが作成されます。

次に先ほど作成したコンポーネントを表示させたい画面のビューファイルに以下を挿入します。

= react_component("Hello" )

react_componentメソッドで先ほど作成したコンポーネントを呼び出します。

次に,railsのモデルデータをReactのコンポーネントに渡す方法です。
今回はユーザーデータを渡します。では、先ほどの挿入した箇所を以下に変更してください。

= react_component("Hello" , user: @user)

次にHelloコンポーネントのretuen内を以下のようにします。

Hello.js
render () {
    return (
       <div>
         {this.props.user.name}
       </div>
    );
  }

これで、挿入したビューの画面にアクセスすると、先ほど渡したユーザーの名前が表示されます。

7
9
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
7
9