Last active
November 19, 2018 02:27
-
-
Save wking-io/9998a5b0a1b7298f5cb066433db461f3 to your computer and use it in GitHub Desktop.
Elm Handler for React
This file contains hidden or 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 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 |
This file contains hidden or 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
| /** | |
| * 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