Skip to content

Instantly share code, notes, and snippets.

@yelouafi
Last active July 19, 2017 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yelouafi/250209fa600f6f37c771119ef706680d to your computer and use it in GitHub Desktop.
Save yelouafi/250209fa600f6f37c771119ef706680d to your computer and use it in GitHub Desktop.
put your react component in a closure
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);
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);
import React from 'react';
import { render } from 'react-dom';
import App from './App';
render(<App />, document.getElementById('root'));
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