Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Last active September 27, 2021 12:21
Show Gist options
  • Save dead-claudia/fffd9535c203fb7ae06dd5b5b71f9ff9 to your computer and use it in GitHub Desktop.
Save dead-claudia/fffd9535c203fb7ae06dd5b5b71f9ff9 to your computer and use it in GitHub Desktop.
Mithril to React adapters
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) }
}
@dead-claudia
Copy link
Author

@DaniellMesquita This is mainly for migration, not simple porting. Also, all React components necessarily inherit from React.Component.

@danimesq
Copy link

@isiahmeadows

But there's a tutorial for porting ReactJS components?

@dead-claudia
Copy link
Author

Best to ask that in the Gitter channel. This gist was mostly just used to explain a concept at the time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment