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内で利用できる。