Skip to content

Instantly share code, notes, and snippets.

@erspark2002
Last active August 30, 2016 03:28
Show Gist options
  • Save erspark2002/af5523f505393053b331db60cac41a4e to your computer and use it in GitHub Desktop.
Save erspark2002/af5523f505393053b331db60cac41a4e to your computer and use it in GitHub Desktop.
Simple React Todo Application using CDN resources for babel/ES6 - VERSION 3 - Using state instead of <input ref={}>
<!DOCTYPE html>
<!--
NOTES:
multiple components
no refs
uses state
The <input/> has it's ref removed, and 'value' and 'onChange' properties added.
The value is ALWAYS the value of this.state.description.
this.state.description is initialised to an empty string in the TodoItem's constructor using this.state = {...}
To change the input of the value when a key is pressed, you need to call this.setState({description: 'new value'}) and pass a new value.
The new value is contained with the 'event' object, which is created in the onClick event.
When this.setState({...}) is called, this causes render() to be called.
-->
<html>
<head>
<meta charset="utf-8">
<script src="https://fb.me/react-with-addons-15.0.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.4/redux.min.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<title>React Template with CDN Resources - JSX</title>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
console.log('start');
const Component = React.Component;
let count = 0;
let todos = [{desc: 'milk', id: count++}, {desc: 'eggs', id: count++}];
let todoList;
class Todo extends Component {
render() {
return (
<div>
<TodoItem todoList={todoList}/>
<TodoList todos={todos} ref={el=>{todoList=el}}/>
</div>
);
}
};
class TodoItem extends Component {
constructor() {
super();
this.state = {
description: ''
}
}
addItem(description) {
todos.push({
desc: description,
id: count++
});
todoList.forceUpdate();
}
onChange(event) {
this.setState({
description: event.target.value
});
}
render() {
let input;
return (
<div>
<input onChange={(event)=>{this.onChange(event)}} value={this.state.description}/>
<button onClick={()=>this.addItem(this.state.description)}>Add</button>
</div>
);
}
}
class TodoList extends Component {
render() {
console.log('--> TodoList todos:', todos);
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.desc}
</li>
))}
</ul>
);
}
}
ReactDOM.render(<Todo />, document.getElementById('app'));
console.log('done');
</script>
</body>
</html>
@erspark2002
Copy link
Author

Version 4 Uses Redux instead of internal state to keep track the todo items: https://gist.github.com/erspark2002/0ea49cc782049df5f3de271ba9ff41e1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment