LoginSignup
2
2

More than 5 years have passed since last update.

ReactにRailsのコントローラーからの処理を送り込む

Last updated at Posted at 2017-10-29

ReactをRailsのviewに使うとき、Railsのコントローラーでの処理結果などをReact内に使いたいときがある。
例えば、ログイン中のユーザー名をReactコンポーネント内で表示したいときとか。当然、Reactに直接current_user.nameなどを記載しても動かない。
そこで、current_user.nameを一旦、<div>で囲んで、どこかのhtml.erbに送り込む。

react.html.erb
<div id="user_name" data="<% current_user.name %>></div>

これを、React側から取得する。

React.js
const username = $("#user_name").attr('data');

$("#user_name").attr('data')の部分は、「idがuser_nameである<div>のdata属性の内容を取得する」、という意味。こうしてあげると、current_user_nameをusernameとしてreact内で利用できる。

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