Skip to content

Instantly share code, notes, and snippets.

@quicksnap
Last active October 1, 2015 22:18
Show Gist options
  • Save quicksnap/46049728bc3aa700c520 to your computer and use it in GitHub Desktop.
Save quicksnap/46049728bc3aa700c520 to your computer and use it in GitHub Desktop.
simple react example
var React = require('react');
var TodoBox = React.createClass({
render: function() {
return (
<div className="todoBox">
<h1>Todos</h1>
<TodoList data={this.props.data} />
<TodoForm />
</div>
);
}
});
var TodoList = React.createClass({
getInitialState: function() {
return {
data: this.props.data,
titleValue: "",
detailValue: ""
};
},
changeTitle: function(e) {
this.setState({titleValue: e.target.value});
},
changeDetail: function(e) {
this.setState({detailValue: e.target.value});
},
addTodo: function() {
this.setState({
data: this.state.data.concat({
title: this.state.titleValue,
detail: this.state.detailValue
})
});
this.setState({ titleValue: "" });
this.setState({ detailValue: "" });
},
deleteTodo: function(index) {
var newData = this.state.data.slice();
newData.splice(index, 1);
this.setState({data: newData});
},
render: function() {
var todo = this.state.data.map((obj) => {
return <Todo title={obj.title} key={obj.title} onDelete={this.deleteTodo}>{obj.detail}</Todo>
}, this);
return (
<div className="todoList">
<div>
Title:<input type="text" value={this.state.titleValue} onChange={this.changeTitle} />
Detail:<input type="text" value={this.state.detailValue} onChange={this.changeDetail} />
<button onClick={this.addTodo}>Add</button>
</div>
<table style={style.list}>
<tbody>
{todo}
</tbody>
</table>
</div>
);
}
});
var Todo = React.createClass({
propTypes: {
title: React.PropTypes.string.isRequired,
onDelete: React.PropTypes.func.isRequired
},
render: function() {
return (
<tr style={this.state.checked ? style.checkedTodo : style.notCheckedTodo}>
<td style={style.tableContent}>
<button onClick={this._onDelete}>X</button>
</td>
<td style={style.tableContent}>
<input type="checkbox" checked={this.state.checked} onChange={this.handleChange} />
</td>
<td style={style.tableContent}>{this.props.title}</td>
<td style={style.tableContent}>{this.props.children}</td>
</tr>
);
},
handleChange: function(e) {
this.setState({checked: e.target.checked});
},
_onDelete: function() {
this.props.onDelete(this.props.title);
},
getInitialState: function() {
return {
checked: false
};
}
});
var TodoForm = React.createClass({
render: function() {
return (
<div className="todoForm">
I am a TodoForm.
</div>
);
}
});
var style = {
checkedTodo: {
textDecoration: "line-through"
},
notCheckedTodo: {
textDecoration: "none"
},
tableContent: {
border: "1px solid black"
},
list: {
border: "2px solid black"
}
};
module.exports = TodoBox;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment