Skip to content

Instantly share code, notes, and snippets.

@mnishiguchi
Last active August 29, 2015 14:23
Show Gist options
  • Save mnishiguchi/65f97e0a0d6f4fcb9b6b to your computer and use it in GitHub Desktop.
Save mnishiguchi/65f97e0a0d6f4fcb9b6b to your computer and use it in GitHub Desktop.
A brief introduction to React.js ref: http://qiita.com/mnishiguchi/items/82426e89726c70e54e51
// Renders the component to the mount node.
var mountNode = document.getElementById("todoapp"));
React.render(<TodoApp />, mountNode);
// Definition of <Header />
...
<!-- HTML template -->
<div id="todoapp"><!-- the mount node --></div>
var LikeButton = React.createClass({
getInitialState: function() {
return { liked: false };
},
handleClick: function(event) {
this.setState({ liked: !this.state.liked });
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={ this.handleClick }>
You { text } this. Click to toggle.
</p>
);
}
});
React.render(
<LikeButton />,
document.getElementById('example')
);
// Definition of <MainSection />
...
// <TodoApp />
var TodoApp = React.createClass({
getInitialState: function() {
return { items: [], text: '' };
},
onChange: function(e) {
this.setState({ text: e.target.value });
},
handleSubmit: function(e) {
e.preventDefault();
var nextItems = this.state.items.concat([this.state.text]);
var nextText = '';
this.setState({ items: nextItems, text: nextText });
},
render: function() {
return (
<div>
<h3>TODO</h3>
<TodoList items={ this.state.items } />
<form onSubmit={ this.handleSubmit }>
<input onChange={ this.onChange } value={ this.state.text } />
<button>{ 'Add #' + (this.state.items.length + 1) }</button>
</form>
</div>
);
}
});
// <TodoList />
var TodoList = React.createClass({
render: function() {
var createItem = function(itemText, index) {
return <li key={ index + itemText }>{ itemText }</li>;
};
return <ul>{ this.props.items.map(createItem) }</ul>;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment