LoginSignup
15
18

More than 5 years have passed since last update.

react-railsでhello world!!

Last updated at Posted at 2015-07-31

公式A JavaScript library for building user interfaces | Reactにある最初のhello world サンプルをrails上で動かすまでの手順。

まずはプロジェクトを作成。

rails new helloworld

gemにreact-railsを入れます。rails上でreactが使えるようになったり便利なヘルパーがあったりします。
ruby
$ vi Gemfile

# ...省略
gem 'react-rails', '~> 1.0' # 追加する

bundle install.

bundle install --path vendor/bundle/

reactを使うためのセットアップコマンド。必要なディレクトリなどが生成されます。

rails g react:install

つぎはcomponentを追加。このコマンドでなくても追加できます。

rails g react:component HelloWorld

中身を開いて、renderメソッドに描画する内容を書きます。今回はhello worldのみ。

$ vi app/assets/javascripts/components/HelloWorld.js.jsx
var HelloWorld = React.createClass({
  render: function() {
    return (
      <div>Hello World!!</div>
    )
  }
});

viewを呼ぶだけのcontrollerも作りましょう。

rails g controller home index

routes.rbにも追加。
ruby
$ vi config/routes.rb

root 'home#index'

最後に、react_componentを読んで、viewからreactのコンポーネントを呼びます。

$ vi app/views/home/index.html.erb
<%= react_component('HelloWorld') %>

これで完成。
あとはbrowserから確認するだけです。
bash
rails s

open http://localhost:3000

done.

続編もあるので興味あればご覧ください。
JavaScript - react-railsでhello world!!をES6化 - Qiita

15
18
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
15
18