Setup React with Phoenix 1.4

Phoenix 1.4 uses webpack by default for asset management. This is how you can get up and running with React -

  • Go to assets directory
  • Run “npm install -S react react-dom”
  • Then, run “npm install -D @babel/preset-react”
  • Edit the .babelrc file. It should have
    {
    "presets": ["@babel/preset-env", "@babel/preset-react"]
    }

That’s it. Now, edit app.js file under assets/js -

import React from "react";
import ReactDOM from "react-dom";
class Hello extends React.Component {
render ()
{
return "Hello React" ;
}
}

var mountNode = document.getElementById("app");
ReactDOM.render(, mountNode);
.

And, finally edit app.html.eex and add a div tag with id=”app”.

Run mix.phx server and checkout http://localhost:4000. You should see “Hello React”!