Skip to content

Instantly share code, notes, and snippets.

@plusjade
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plusjade/cc7823d5c2dc03ee6fc0 to your computer and use it in GitHub Desktop.
Save plusjade/cc7823d5c2dc03ee6fc0 to your computer and use it in GitHub Desktop.
<div id="todo"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react.min.js"></script>
<script>
Todo = React.createClass({
displayName: 'Todo'
,
getInitialState : function() {
return { items: [] };
}
,
// render() contains all the view logic.
// When data changes, the entire render() function is re-run.
// This allows you to use the full extent of Javascript to render views based on various states of incoming data.
render: function() {
var itemNodes;
// Build the item list elements from incoming state data
itemNodes = this.state.items.map(function(item, i) {
return React.DOM.li(null
, item
, React.DOM.button({
// bind removeItem event handler
// pass the item index as unique identifier
onClick: this.removeItem.bind(this, i)
}
, 'remove'
)
);
}, this);
// render() needs to return a React.DOM element.
// This is the Virtual DOM -- HTML via Javascript!
return React.DOM.div(null
// Build the form and bind submit handler
, React.DOM.form({ onSubmit: this.submit }
, React.DOM.input({ ref: 'input', defaultValue: '' })
, React.DOM.button({ type: 'submit'}, 'Add Item')
)
// Build the unordered list with items we've generated above.
, React.DOM.ul({id: 'todo-items'}, itemNodes)
)
;
}
,
submit : function(event) {
event.preventDefault();
// get the input value
var input = this.refs.input.getDOMNode().value;
this.addItem(input);
}
,
addItem : function(item) {
if(item) {
// Add item to the data state
// This automatically triggers a re-render
this.setState({
items: this.state.items.concat(item)
});
}
}
,
removeItem : function(index) {
if(index >= 0) {
// clone the items
var items = this.state.items.slice(0);
// remove the item
items.splice(index, 1);
// Update the data state
// This automatically triggers a re-render
this.setState({ items: items });
}
}
});
Todo = React.createFactory(Todo);
var parsedUserData = {
"name" : "John Doe",
"items" : [
"Item 1",
"Item 2",
"Item 3"
]
}
// Render the View
var view = React.render(Todo(), document.getElementById('todo'));
// Set the todo items
view.setState({ items: parsedUserData.items });
view.state.items; // <-- holds the todo list state at any given time.
// This data may be easily persisted to your application's database.
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment