Phoenix.React
Use React as Template Engine in Phoenix applications.
Usage
# web/controllers/page_controller.ex
def index(conn, _params) do
render conn, serializable: [
title: "Hello :)",
content: "This is isomorphic application."
]
end/* web/templates/index.html.jsx */
export default function IndexPage({ title }) {
return (
<div>
<h1>{title}</h1>
<p>{content}</p>
</div>
);
}Installation
If available in Hex, the package can be installed as:
-
Add
phoenix_reactto your list of dependencies inmix.exs:
def deps do
[{:phoenix_react, "~> 0.1.0"}]
end-
Ensure
phoenix_reactis started before your application:
def application do
[applications: [:phoenix_react]]
end- Install NPM packages
npm install react react-dom babel-register --saveSetup
Compilers
In order to use Phoenix.React, we need to add it to the compilers:
# mix.esx
def project do
[app: :our_app,
...
compilers: [:phoenix, :gettext, :phoenix_react] ++ Mix.compilers ++ [:phoenix_react_components]
...]
end
We need to put :phoenix_react_components after Mix.compilers because the all view modules must be compiled before we run :phoenix_react_components compiler.
Code reload
This is to make javascript file to be generated every time we change components.
# config/dev.exs
config :our_app, MyApp.Endpoint,
reloadable_compilers: [:gettext, :phoenix, :phoenix_react, :elixir, :phoenix_react_components]Supervisor
Add Phoenix.React to supervisor tree in lib/our_app.ex
# lib/our_app.ex
[...]
children = [
# Start the Ecto repository
supervisor(OurApp.Repo, []),
# Start the endpoint when the application starts
supervisor(OurApp.Endpoint, []),
# Call start_link function in Phoenix.Worker.Supervisor
worker(Phoenix.Worker.Supervisor, [])
]
[...]Views
Use Phoenix.React.View in view/0 in web.ex
def view do
quote do
[...]
use Phoenix.React.View, root: "web/templates" # or "web/static/js/components"
end
end