Last active
July 19, 2017 17:16
-
-
Save yelouafi/250209fa600f6f37c771119ef706680d to your computer and use it in GitHub Desktop.
put your react component in a closure
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 React from 'react'; | |
import reclass from './reclass'; | |
import Greeter from './Greeter'; | |
function App(ctx) { | |
ctx.state = { civility: 'Mr.' }; | |
function changeCivility(e) { | |
ctx.setState({ civility: e.target.value }); | |
} | |
function render(_, { civility }) { | |
return ( | |
<div> | |
<p> | |
<label>Civility </label> | |
<input value={civility} onChange={changeCivility} /> | |
</p> | |
<Greeter civility={civility} /> | |
</div> | |
); | |
} | |
return { render }; | |
} | |
export default reclass(App); |
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 React from 'react'; | |
import reclass from './reclass'; | |
function Greeter(ctx) { | |
ctx.state = { name: 'Smith' }; | |
function changeName(e) { | |
ctx.setState({ name: e.target.value }); | |
} | |
function componentWillReceiveProps(newProps) { | |
console.log('got new props', newProps); | |
} | |
function render({ civility }, { name }) { | |
return ( | |
<div> | |
<label>Name </label> | |
<input | |
placeholder="Type your name" | |
value={ctx.state.name} | |
onChange={changeName} | |
/> | |
<h3> | |
Hello {civility} {name} | |
</h3> | |
</div> | |
); | |
} | |
return { render, componentWillReceiveProps }; | |
} | |
export default reclass(Greeter); |
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 React from 'react'; | |
import { render } from 'react-dom'; | |
import App from './App'; | |
render(<App />, document.getElementById('root')); |
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 React from 'react'; | |
export default function reclass(factory) { | |
return class extends React.Component { | |
static displayName = factory.name; | |
constructor(props) { | |
super(props); | |
Object.assign(this, factory(this)); | |
const render = this.render; | |
this.render = () => { | |
return render(this.props, this.state); | |
}; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment