Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use React Components within Elm?

Tags:

reactjs

elm

I know that using Elm components ("modules"? still learning parlance) within React is an established pattern with libraries like react-elm-components, but is there a way to do the inverse?

e.g., something like this is possible:

Top-level React App
 -> React layout/component
    -> Elm components

But what about this:

Top-level Elm App
  -> Elm layout/components
     -> React components

If it is possible, is the 'elm-at-the-bottom' pattern superior? Trying to reason why there doesn't seem to be literature on it & that's a possible explanation.

like image 637
Brandon Avatar asked Dec 28 '16 18:12

Brandon


Video Answer


1 Answers

Don't do that. The whole point of Elm is hexagonal design. Elm is intended to function as a closed system, one in which the evils of JS cannot penetrate. This is why embedding Elm in JS is first class, and you are having such trouble finding the inverse. The idea of embedding React into Elm is to hand over the value of Elm's determinism and assurances. You might as well not use Elm at all.

If you really just want to do functional programming in the browser and use React components with the Elm architecture, check out PureScript PUX. PUX is designed for that use-case and is going to give you better results than hacking Elm to do things Elm was specifically designed to prevent.

If my comments are a non-starter for you I can offer the following advice for being evil in this way, without being toooo evil.

First, you can accomplish this with ports. Write your Elm application to fire events on a port to JavaScript when you want to render your react component. Then render the react component inside of the Elm Dom space, in the standard way with JavaScript.

Second (this is the closest to doing it properly you are going to get), you can write this using Elm Native modules. This will require you to learn Elm's undocumented runtime, and write code that interacts with it. What you will do is write a custom Html element in Elm's low level system, that rendered React inside itself and manages re-rendering.

Good luck!

like image 133
Fresheyeball Avatar answered Sep 18 '22 09:09

Fresheyeball