Skip to content

Instantly share code, notes, and snippets.

@wking-io
Last active November 19, 2018 02:27
Show Gist options
  • Select an option

  • Save wking-io/9998a5b0a1b7298f5cb066433db461f3 to your computer and use it in GitHub Desktop.

Select an option

Save wking-io/9998a5b0a1b7298f5cb066433db461f3 to your computer and use it in GitHub Desktop.
Elm Handler for React
import React from 'react'
import PropTypes from 'prop-types'
class ElmHandler extends React.Component {
node = React.createRef()
/**
* Setup the Elm app using the ref for this components node
* using the flags passed in as props. Connect the port handler
* function passed in from props to the ports established in the
* initialized Elm app for use during component update.
*
*/
componentDidMount () {
const { src, flags, ports } = this.props
this.app = src.init({
node: this.node.current,
flags
})
if (ports) {
this.ports = ports(this.app.ports)
}
}
/**
* Passes new props into the port handler so we can capture
* updates that we want and send them from JS -> Elm, but
* it always returns false. Since Elm handles all DOM managemant
* for this node and its children, we do not want React to
* re-render this component once Elm is initialized.
*
*/
shouldComponentUpdate (nextProps) {
if (this.ports) {
this.ports(nextProps)
}
return false
}
render () {
return (
<div ref={this.node} />
)
}
}
ElmHandler.propTypes = {
flags: PropTypes.object,
ports: PropTypes.func,
src: PropTypes.object.isRequired
}
export default ElmHandler
/**
* Higher order function that takes in the ports
* from your Elm app and returns a function that
* will be passed the props from the Elm Handler
* component when its props change.
*
*/
export function portFunction (ports) {
return function handleUpdate (props) {
return ports.myPort.send(pros.value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment