Phoenix with React
Phoenix is a great framework, but sometimes we want to use frontend framework like React. In this article, you will learn how to use them together. First, we create a project with the following commands.
mix phx.new <project name> --no-ecto
cd <project name>/assets
npm i react react-dom @babel/preset-react remount
Edit assets/.babelrc
{ "presets": [ "@babel/preset-env", "@babel/preset-react" ] }
Create assets/js/src/app.js
import React from "react" import { define } from "remount" const Test = () => <h1> Hello World </h1> define({ "x-app": Test })
Edit assets/js/app.js
import "../css/app.scss" import "phoenix_html" import "./src/app.js"
Finally, replace all in
lib/<project name>_web/templates/page/index.html.eex
with the
following content
<x-app></x-app>
Now, we can develop with React and Phoenix together.