tme_317

tme_317

Issues Rendering React Components inside LiveView

I’ve been experimenting using the recently landed LV-JS interop features to render React components inside LiveView. I can simplify my app by doing much with LV but don’t want to rewrite all my existing components yet!

It works pretty well but ran into 2 minor issues. I am rendering the React components modeled on the way GitHub - geolessel/react-phoenix: Make rendering React.js components in Phoenix easy · GitHub does it which is pretty simple. You render a div in the LV with data- properties (props map encoded as JSON) like such:

~L"""
    <div data-react-class="Components.LikeButton" data-react-props="<%= Jason.encode!(@props)%>" phx-hook="React" phx-update="ignore"></div> 
"""

Then in the new LiveView Hooks mounted and updated callbacks in my entrypoint JS I have this:

// ...
import LikeButton from "../zlib/LikeButton.js";

window.Components = {
  LikeButton
};

function renderReact(el, pushEvent) {
  const targetId = document.getElementById(el.dataset.reactTargetId);
  const targetDiv = targetId ? targetId : el;
  const reactProps = el.dataset.reactProps ? el.dataset.reactProps : "{}";
  const reactElement = React.createElement(
    eval(el.dataset.reactClass),
    Object.assign(JSON.parse(reactProps), { pushEvent: pushEvent })
  );
  ReactDOM.render(reactElement, targetDiv);
}

let Hooks = {};
Hooks.React = {
  mounted() {
    this.pushEvent("hello_from_react", "1234"); // THIS WORKS!
    renderReact(this.el, this.pushEvent);
  },
  updated() {
    renderReact(this.el, this.pushEvent);
  }
};

let liveSocket = new LiveSocket("/live", { hooks: Hooks });
liveSocket.connect();

Biggest issue is the use of the pushEvent callback… it works if I use it directly in the mounted function but I want to be able to pass the function as a prop to my React tree so the children components can easily push events to the server. However, when calling it in the React component I am getting Uncaught TypeError: Cannot read property 'pushWithReply' of undefined. I’m sure my lack of JS knowledge has me doing it wrong since I think it’s a method and maybe needs this context hanging around or something?

Second issue is I have to call duplicate renderReact in both the mounted and updated callbacks for everything to work… but the component is re-created and re-rendered every time any LV assigns update (not just props changes affecting this specific element). If I just call in mounted it won’t re-render when the server changes the props so I have to call it in both places. I was thinking updated would only be called on a specific hook when assigns change affecting that specific element? This part is working so far but seems like it will be slow when having to re-render many components.

Has anyone else successfully integrated React components into LV yet using the new hooks interop? I think this hybrid approach will work great and allow the best of both worlds once these issues are figured out.

Thanks!

Marked As Solved

tme_317

tme_317

In case anyone comes across this post… there is a new library that solves this which I just evaluated and it works great!

https://github.com/fidr/phoenix_live_react

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New

We're in Beta

About us Mission Statement