Skip to content

hungry-egg/phx-frontend-react

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React bindings for phx_frontend Elixir library

Installation

  • Follow the instructions from the phx_frontend library to render js apps with Phoenix Liveview.

  • Add the npm dependency phx-frontend-react in the assets folder, e.g.

npm install --save phx-frontend-react --prefix assets

Usage

If we have a React Counter component that we would normally use in React like so

<Counter
  counter={4}
  onIncrement={(amount) => console.log(`Increment by ${amount}`)}
/>

then we can render it from a LiveView with

  def render(assigns) do
    ~H"""
      <.js_app
        id="my-counter"
        component="Counter"
        props={%{counter: @counter}}
        callbacks={%{onIncrement: "increment"}}
      />
    """
  end

  def handle_event("increment", %{amount: amount}, socket) do
    IO.puts("Increment by #{amount}")
    {:noreply, socket}
  end

To do the above you need configure the hook in your app.js like so:

// ...
import { createJsApps } from "phx-frontend";
+import createReactApp from "phx-frontend-react";
+import Counter from "path/to/react/counter/component";
// ...

let liveSocket = new LiveSocket("/live", Socket, {
  // ...
  hooks: {
    // ...
    jsApp: createJsApps({
      // ...
+      Counter: createReactApp(Counter, {
+        // not needed if you don't need to map callback params
+        callbackParams: {
+          onIncrement: (amount) => ({ amount }),
+        },
+      }),
    }),
  },
});

// ...

If you don't map callbackParams then handle_event will be called with an empty map %{}. In that case you can omit the options arg to createReactApp in app.js:

Counter: createReactApp(Counter);

About

React bindings for phx_frontend Elixir library

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published