React Setter Method
Starting point for creating JSFiddles with React. This uses React with Addons.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://fb.me/react-with-addons-0.14.0.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="app">
<!-- This element's contents will be replaced with your component. -->
</div>
JavaScript 1.7
var FriendsContainer = React.createClass({
getInitialState: function(){
return {
name: 'Commander LaForge',
friends: ['Data', 'Number 1', 'Jean Luc Picard'],
}
},
// Function below adds friend to the array
addFriend: function(friend){
this.state.friends.push(friend);
this.setState({
friends: this.state.friends
});
},
render: function(){
return (
<div>
<h3> Name: {this.state.name} </h3>
<AddFriend addNew={this.addFriend} />
<ShowList names={this.state.friends} />
</div>
)
}
});
var AddFriend = React.createClass({
getInitialState: function(){
return {
newFriend: ''
}
},
updateNewFriend: function(e){
this.setState({
newFriend: e.target.value
});
},
handleAddNew: function(){
this.props.addNew(this.state.newFriend);
this.setState({
newFriend: ''
});
},
render: function(){
return (
<div>
<input type="text" value={this.state.newFriend} onChange={this.updateNewFriend} />
<button onClick={this.handleAddNew}> Add Friend </button>
</div>
);
}
});
var ShowList = React.createClass({
render: function(){
//below var listItem becomes proptype listItem
var listItems = this.props.names.map(function(friend){
return <li> {friend} </li>;
});
return (
<div>
<h3> Friends </h3>
<ul>
{listItems}
</ul>
</div>
)
}
});
ReactDOM.render(
<FriendsContainer />,
document.getElementById('app')
);