LoginSignup
6
5

More than 5 years have passed since last update.

Phoenix 1.4 で、React を動作させる

Last updated at Posted at 2019-05-01

年号も平成から令和に変わり、久しぶりにPhoenix でアプリを作成予定なので、React を使ってみる。
いつの間にか、Phoenix 1.4 においてJSのビルドツールは brunchからwebpackに変わっていたようだ。

開発環境

Phoenix : 1.4.3
Elixir : 1.8.1
node : 10.15.3
npm : 6.9.0
react : 16.8.6
react-dom : 16.8.6

Phoenix プロジェクト作成

Phoenix プロジェクトを作成し、依存ライブラリをインストールする。

$ cd $workdir
$ mix phx.new ReactPhoenix --app react_phoenix --no-ecto

Fetch and install dependencies? [Yn] Y

React ライブラリインストール

npm によって、reactreact-dom をインストールする。

$ cd $ cd ReactPhoenix/assets/node_modules/
$ npm install react react-dom --save

.babelrc ファイル編集

reactがプリコンパイルされるように.babelrcを設定する。

{
    "presets": [
        "@babel/preset-env",
        "@babel/react"
    ]
}

Webページテンプレート編集

index.html.eex を簡単シンプルに編集する。

lib/react_phoenix_web/templates/page/index.html.eex
<section class="row">
  <article class="column">
    <div id="root"></div>
  </article>
</section>

app.jsにReactのJSXコンポネントを記述

assets/js/app.js
import React from 'react'
import ReactDOM from 'react-dom'

const MyReactComponent = () => <div>こんにちはReact Component!!!</div>
ReactDOM.render(<MyReactComponent />, document.getElementById('root'))

Serverの起動

プロジェクトのホームディレクトリへ移動して、サーバを起動する。

$ cd ../..
$ mix phx.server

ホーム画面

index.html.eexに記述した<div id="root"></div>タグが、app.jsで作成したコンポネントに置き換わって表示されている。

スクリーンショット 2019-05-01 14.59.25.png

とりあえず、最低限の準備が整った。

6
5
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
6
5