0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Reactとの連携(1)

Last updated at Posted at 2021-05-01

今回は「index.html.erb」表示まで

react用アプリケーション作成

rails
rails new RailsReactApp --webpack=react

indexページ作る

rails
rails g controller hello index
app/controllers/hello_controller.rb
class HelloController < ApplicationController
  def index
  end
end

indexファイルコーディング

rails
<%= javascript_pack_tag 'hello_react' %>

<h1 class="display-4 text-primary">
Hello#index</h1>
<div id="hello"></div>

Viewファイル修正

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>RailsReactApp</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <link rel="stylesheet"
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css
    bootstrap.css>
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

Reactで表示完了

20210502-001817.png

Reactを利用した処理が実行されています。
appフォルダ内の JavaScriptフォルダ内にはpacksというフォルダがあり、この中にhello_react.jsxというファイルが用意されています。このスクリプトが読み込まれています。
*標準でReactコンポーネントのJavaScriptファイルについて、拡張子を「.js」ではなく「.jsx」にすることが推奨されている。
今日はここまで

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?