Last active
March 2, 2018 16:51
-
-
Save danott/4aea1e94d5a8042bf0337d53a61dd374 to your computer and use it in GitHub Desktop.
Someone will probably want this.
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 { Controller } from "stimulus" | |
import ReactDOM from "react-dom" | |
import React from "react" | |
/* HTML | |
<div controller="react" | |
data-react-component="HelloWorld" | |
data-react-props="{ \"name\": \"Daniel\" }" | |
/> | |
*/ | |
export default class ReactController extends Controller { | |
connect() { | |
ReactDOM.render( | |
React.createElement(this.reactComponent, this.reactProps), | |
this.element | |
) | |
} | |
disconnect() { | |
ReactDOM.unmountComponentAtNode(this.element) | |
} | |
get reactComponent() { | |
const component = window.eval(this.data.react.component) | |
if (!component) { | |
throw "Component not available on window" | |
} | |
return component | |
} | |
get reactProps() { | |
return JSON.parse(this.data.react.props) | |
} | |
} |
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 ReactDOM from "react-dom" | |
import React from "react" | |
import PropTypes from "prop-types" | |
/* JSX | |
<StimulusComponent controller="hello.name"> | |
<input data-target="hello.name" type="text" /> | |
</StimulusComponent> | |
*/ | |
export default class StimlusComponent extends React.Component { | |
static propTypes = { | |
controller: PropTypes.string.isRequired, | |
} | |
render() { | |
return ( | |
<div data-controller={this.props.controller}> | |
{this.props.children} | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment