Skip to content

Instantly share code, notes, and snippets.

@wayneashleyberry
Last active August 29, 2015 14:10
Show Gist options
  • Save wayneashleyberry/0c785c5bb2f01f91268a to your computer and use it in GitHub Desktop.
Save wayneashleyberry/0c785c5bb2f01f91268a to your computer and use it in GitHub Desktop.
React cross component communications test
var Item = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired,
active: React.PropTypes.bool.isRequired,
toggleActive: React.PropTypes.func.isRequired
},
getDefaultProps: function() {
return {
active: false
}
},
handleClick: function(e) {
e.preventDefault();
this.props.toggleActive();
},
render: function() {
var text = this.props.name;
if (this.props.active) {
text = '→ '+this.props.name;
}
return <p onClick={this.handleClick}>{text}</p>;
}
});
var List = React.createClass({
getInitialState: function() {
return {
active: null
}
},
toggleActive: function(key) {
key = (this.state.active == key) ? null : key;
this.setState({active: key});
},
render: function() {
var items = this.props.items.map(function(item, key) {
return <Item
key={key}
name={item}
active={this.state.active == key}
toggleActive={this.toggleActive.bind(this, key)}
/>;
}, this);
return <div className="container">{items}</div>;
}
});
var App = React.createClass({
render: function() {
return (
<div className="container">
<br />
<List items={this.props.items} />
</div>
);
}
});
var items = ['Cyan', 'Magenta', 'Yellow', 'Black'];
React.render(
<App items={items} />,
document.getElementById('content')
);
<!doctype html>
<meta charset="utf-8">
<title>…</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<div id="content"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/react/0.12.1/react-with-addons.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/react/0.12.1/JSXTransformer.js"></script>
<script src="app.js" type="text/jsx"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment