Skip to content

Instantly share code, notes, and snippets.

@lijunle
Last active March 11, 2016 09:43
Show Gist options
  • Save lijunle/f43256eb3fe73e47be24 to your computer and use it in GitHub Desktop.
Save lijunle/f43256eb3fe73e47be24 to your computer and use it in GitHub Desktop.
React Cursor Demo
// jsfiddle: https://jsfiddle.net/lijunle/50jx1k2z/2/
let {Cursor} = ReactCursor;
const state1 = {
counters: [
{ id: 1, number: 1 },
{ id: 2, number: 2 },
{ id: 3, number: 3 },
{ id: 4, number: 4 },
{ id: 5, number: 5 },
]
};
const state2 = {
counters: [
{ id: 1, number: 1 },
{ id: 2, number: 2 },
{ id: 3, number: 3 },
{ id: 4, number: 4 },
{ id: 5, number: 5 },
{ id: 6, number: 6 },
{ id: 7, number: 7 },
]
};
class RequestButton extends React.Component {
shouldComponentUpdate (nextProps) { return this.props.cursor !== nextProps.cursor; }
render() {
console.log('rendering request button');
return (
<div>
<button onClick={this.request.bind(this)}>
Request More Data
</button>
</div>
);
}
request() {
console.log('start request');
setTimeout(() => {
console.log('finish request');
this.props.cursor.swap(() => state2);
}, 3000);
}
}
class Clicker extends React.Component {
shouldComponentUpdate (nextProps) { return this.props.cursor !== nextProps.cursor; }
render () {
console.log('rendering clicker');
let {cursor} = this.props;
return (
<div>
<input type="text" value={cursor.value().number} readOnly />
<button onClick={() => cursor.swap(v => ({ id: v.id, number: v.number + 1 }))}>
+1
</button>
{' '}
<span>
Clicker cursor: <code>{JSON.stringify(cursor.value(), null, 2)}</code>
</span>
</div>
);
}
}
class CounterList extends React.Component {
shouldComponentUpdate (nextProps) { return this.props.cursor !== nextProps.cursor; }
render () {
console.log('rendering counter list');
let {cursor} = this.props;
return (
<div>
<h2>CounterList cursor:</h2>
<p>
<code>
{JSON.stringify(cursor.value(), undefined, 2)}
</code>
</p>
{cursor.value().map((item, index) => <Clicker key={item.id} cursor={cursor.refine(index)} />)}
</div>
);
}
}
class App extends React.Component {
shouldComponentUpdate (nextProps) { return this.props.cursor !== nextProps.cursor; }
render () {
console.log('rendering app');
return (
<div>
<h1>App cursor:</h1>
<p>
<code>
{JSON.stringify(this.props.cursor.value(), undefined, 2)}
</code>
</p>
<CounterList cursor={this.props.cursor.refine('counters')} />
<RequestButton cursor={this.props.cursor} />
</div>
);
}
}
class AppStateContainer extends React.Component {
constructor (props) {
super(props);
this.state = state1;
}
render () {
let cursor = Cursor.build(this);
return <App cursor={cursor} />;
}
}
ReactDOM.render(<AppStateContainer />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment