RailsでReactJSを使う〜準備編

RailsでReactJSを使う〜準備編

RailsでReactJSを使う〜準備編

RailsでReactJSを使う〜準備編 へのコメントはまだありません

RailsでReactJSを使ってみようという企画をスタートしてみます。
まずはRailsのプロジェクトを作って、ReactJSをインストールして、HelloWorldを出力するところまでの準備編です。

これから何回かにわたり連載する内容はGitHubの下記のURLで公開しています。
https://github.com/h-mito/rails_with_react

Railsプロジェクト作成、ReactJSインストール

[bash]
$ cd
$ cd workspace

$ rails new rails_with_react
$ cd rails_with_react

$ nano Gemfile
[/bash]

末尾に1行追加する
[bash]
# …省略
gem ‘react-rails’, ‘~> 1.0’ # 追加する
[/bash]

react-railsをインストールして、プロジェクトに組み込む
[bash]
$ bundle install

$ rails g react:install
[/bash]

Reactコンポーネントの作成、Hello World作成

[bash]
$ rails g react:component FirstTest
[/bash]

以下のようなソースがapp/assets/javascripts/componentsに生成されると思います。

[bash]
var FirstTest = React.createClass({

render: function() {
return

;
}
});
[/bash]

これでも問題ないのですが、ReactJS本家の Get Started風に以下のように書き換えます。
で、renderメソッドに Hello Worldの出力を追加します。

[bash]
class FirstTest extends React.Component{
constructor(props){
super(props);
}

render(){
return (

Hello World!

);
}
}
[/bash]

テスト用コントローラー作成

[bash]
$ rails g controller first index
[/bash]

Reactコンポーネントを出力

viewsに出来上がったビューに先ほど作ったReactコンポーネントを出力してみます。

[bash]

First#index

Find me in app/views/first/index.html.erb

<%= react_component('FirstTest') %>
[/bash]

動作確認

[bash]
$rails s
[/bash]

ブラウザーで 以下のURLへアクセスし、以下のような画像が出れば成功。

localhost:3000/first/index

react5

About the author:

Tags:

Related Posts

Leave a comment

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)

Back to Top