• Stars
    star
    500
  • Rank 88,178 (Top 2 %)
  • Language
    Elixir
  • License
    MIT License
  • Created over 7 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Make rendering React.js components in Phoenix easy

ReactPhoenix

Build Status Hex.pm

Functions to make rendering React.js components easy in Phoenix.

Combined with the javascript also included in this package, rendering React components in your Phoenix views is now much easier. Using the Phoenix default of Webpack, this package can make getting React into your application much faster than switching over to a different system.

Note regarding Phoenix versions <= 1.3

Phoenix versions 1.3 and earlier use Brunch by default instead of Webpack for asset compilation. The setup for apps using Brunch is different than apps using Webpack. If you'd like to read the old guide for 1.3/Brunch, you can read the Phoenix 1.3 README.

Installation in 4 (or 5) EASY STEPS!

This package is meant to be quick and painless to install into your Phoenix application. It is a thin wrapper to call the React render function from your Phoenix template and assumes you already have React in your project.

1. Declare the dependency

The package can be installed by adding react_phoenix to your list of dependencies in mix.exs:

def deps do
  [
    {:react_phoenix, "~> 1.3"}
  ]
end

After adding to your mix file, run:

mix deps.get

2. Add the javascript dependency to package.json

In order to correctly render a React component in your view templates, a provided javascript file must be included in your assets/package.json file in the dependencies section. It might look like this:

{
  ...
  "dependencies": {
    "phoenix": "file:../deps/phoenix",
    "phoenix_html": "file:../deps/phoenix_html",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-phoenix": "file:../deps/react_phoenix" <-- ADD THIS!
  },
  ...
}

Then run (from your assets directory)

npm install

or

yarn

yarn users

If you face the following error using yarn:

Error: "You may need an appropriate loader to handle this file type"

You may need to add the below to your assets/webpack.config.js file.

{ test: /\.jsx$/, use: { loader: 'babel-loader' } }

npm users

npm unfortunately needs an extra bit of configuration to make it happy. Add the following block to your assets/webpack.config.js file. If you use yarn to manage your dependencies, this extra bit of configuration should not be necessary.

module.exports = (env, options) => ({
  ...
  // ADD THIS BLOCK Ë…Ë…Ë…
  resolve: {
    alias: {
      react: path.resolve(__dirname, './node_modules/react'),
      'react-dom': path.resolve(__dirname, './node_modules/react-dom')
    }
  }
  // ADD THIS BLOCK ^^^
  ...
});

3. Make sure React and Babel presets are installed

Since we want React and would like to write JSX in our app, we need to make sure we get the packages brunch needs in order to compile our files.

# using npm
npm install react react-dom --save
npm install @babel/preset-env @babel/preset-react --save-dev

or

# using yarn
yarn add react react-dom
yarn add --dev @babel/preset-env @babel/preset-react

We also need to activate those presets from the assets/.babelrc file:

// Configure your plugins
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react" // <-- ADD THIS!
  ]
}

4. Import and initialize the javascript helper

In your main application javascript file (usually assets/js/app.js), add the following line:

import "react-phoenix"

5. (optional) Import the module into your views for less typing

If you'd like to just call react_component(...) in your views instead of the full ReactPhoenix.ClientSide.react_component(...), you can import ReactPhoenix.ClientSide into your lib/APPNAME_web.ex views section. It might look like this:

def view do
  quote do
    use Phoenix.View,
      root: "web/templates",
      namespace: MyPhoenixApp

    import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1]

    use Phoenix.HTML

    import MyPhoenixApp.ErrorHelpers
    import MyPhoenixApp.Gettext
    alias MyPhoenixApp.Router.Helpers, as: Routes

    import ReactPhoenix.ClientSide # <-- ADD THIS!
  end
end

Usage

Once installed, you can use react_component in your views by:

  1. Making sure that the component you'd like rendered is in the global namespace. You can do that in app.js like this (for example):

    import MyComponent from "./components/my_component"
    window.Components = {
      MyComponent
    }
  2. In your view template, you can then render it like this:

    # with no props
    <%= ReactPhoenix.ClientSide.react_component("Components.MyComponent") %>
    
    # with props
    <%= ReactPhoenix.ClientSide.react_component("Components.MyComponent", %{language: "elixir", awesome: true}) %>
    
    # with props and a target html element id option
    <span id="my-react-span"><%= @react_html %></span>
    <%= ReactPhoenix.ClientSide.react_component("Components.Characters", %{people: people}, target_id: "my-react-span") %>

    This will render a special div element in your html output that will then be recognized by the javascript helper as a div that should be turned into a React component. It will then render the named component in that div (or a different element specified by ID via the target_id option).

What about server-side rendering?

I couldn't quite get this working with Brunch, but I hope to have time to look at it again with Webpack.

Documentation and other stuff

This package is heavily inspired by the react-rails project.

For more detailed documentation, check out the hex docs at https://hexdocs.pm/react_phoenix

More Repositories

1

vox

The static site builder for Elixir lovers
Elixir
114
star
2

trello-cli

It's Trello, but snappy!
Crystal
35
star
3

ex6502

An emulator of the 6502 processor written in Elixir with a focus on modern variants (65c02).
Elixir
18
star
4

dotfiles

My dotfiles
Vim Script
14
star
5

react-phoenix-example-1.3

An example Phoenix 1.3 app using ReactPhoenix for server-side and client-side rendering of React.js components
Elixir
11
star
6

f1-game-telemetry

Elixir telemetry listener and parser for the Codemaster's F1 2018 game.
Elixir
6
star
7

fantasy-f1-rules

Rules for our custom fantasy Formula 1 league
6
star
8

pco-api-elixir

An Elixir package for consuming Planning Center Online's public API
Elixir
5
star
9

pco-dashboard

Elixir
5
star
10

sd-elixir-todo

An example application using Elixir and Ecto
Elixir
3
star
11

GOTOchgo2021

Live-coded project changed from a traditional controller-driven web app to a LiveView one for GOTOconf Chicago 2021
Elixir
3
star
12

mortgage

A hex package including a set of Elixir functions dealing with mortgages and mortgage notes.
Elixir
3
star
13

reddit-watcher

A GenServer backend and Phoenix front-end to monitor a reddit subreddit for new results for a specific search
Elixir
3
star
14

rubyfighter

A Ruby utility to help memorize Bible verses using Fighter Verses
2
star
15

trapper

A small URL bookmarking service built on Sinatra
Ruby
1
star
16

pc-connection-card

Elixir
1
star
17

ex_stathat

Elixir
1
star
18

bang-bang-con-2019

My slides from my talk "Custom Sudoku books with Ruby!! and LaTeX!!" from !!Con 2019
JavaScript
1
star
19

monkey-scripts

My personal Tampermonkey scripts
JavaScript
1
star
20

vox-example

An example blog build using the Vox static site builder
Elixir
1
star