Last active
September 27, 2021 12:21
-
-
Save dead-claudia/fffd9535c203fb7ae06dd5b5b71f9ff9 to your computer and use it in GitHub Desktop.
Mithril to React adapters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import m from "mithril" | |
import React, {useLayoutEffect, Component} from "react" | |
import ReactDOM from "react-dom" | |
// Bottom-up to Mithril, top-down to React | |
export function useMithril(ref, view) { | |
useLayoutEffect(() => { m.render(ref.current, view()) }) | |
useLayoutEffect(() => () => { m.render(ref.current, null) }, []) | |
} | |
export class FromMithril { | |
constructor(props) { | |
super(props) | |
this.ref = React.createRef() | |
} | |
render() { | |
return this.props.wrapper != null | |
? this.props.wrapper(this.ref) | |
: React.createElement("div", {ref: this.ref}) | |
} | |
componentDidMount() { | |
m.render(this.ref, this.props.children()) | |
} | |
shouldComponentUpdate(newProps) { | |
m.render(this.ref, newProps.children()) | |
// Try not to patch on React's side where possible. | |
return false | |
} | |
} | |
// In case React decides it's still worth re-rendering even with `shouldComponentUpdate` | |
// returning `false`, as their docs imply is possible in the future. | |
Object.defineProperty(FromMithril, "componentDidUpdate", | |
Object.getOwnPropertyDescriptor(FromMithril, "componentDidMount") | |
) | |
function mithrilUpdate(v) { | |
ReactDOM.render(v.attrs.view(), v.dom) | |
} | |
export const FromReact = { | |
view: v => v.attrs.wrapper != null ? v.attrs.wrapper() : m("div"), | |
oncreate: mithrilUpdate, | |
onupdate: mithrilUpdate, | |
onremove: v => { ReactDOM.render(null, v.dom) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Best to ask that in the Gitter channel. This gist was mostly just used to explain a concept at the time.