Mobx + React simple todolist
by ramnathv
HTML
<script src="https://npmcdn.com/[email protected]/lib/mobx.umd.js"></script>
<script src="https://npmcdn.com/[email protected]/index.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div class="container-fluid" id="main">
<div class="row">
<div class="col-xs-12">
<div id="root"></div>
</div>
</div>
</div>
CSS
#main{margin-top: 20px;}
Babel + JSX
const {observable, computed} = mobx;
const {observer} = mobxReact;
const {Component} = React;
class Todo {
id = Math.random();
@observable title;
@observable finished = false;
constructor(title) {
this.title = title;
}
}
class TodoList {
@observable todos = [];
@computed get unfinishedTodoCount() {
return this.todos.filter(todo => !todo.finished).length;
}
}
@observer
class TodoListView extends Component {
render() {
return <div>
<ul>
{this.props.todoList.todos.map(todo =>
<TodoView todo={todo} key={todo.id} />
)}
</ul>
Tasks left: {this.props.todoList.unfinishedTodoCount}
</div>
}
}
@observer
class TodoListView2 extends Component {
render() {
return <div>
<ul className="list-group">
{this.props.todoList.todos.map(todo =>
<TodoView todo={todo} key={todo.id} />
)}
</ul>
<span className='badge'>
Tasks left:
{" " + this.props.todoList.unfinishedTodoCount}
</span>
</div>
}
}
const ListGroup = (props) => {
return(
<ul className="list-group">
{props.items.map((d, i) => {return(
<li className="list-group-item" key={i}>
<Item {...d} />
</li>
)})}
</ul>
)
}
const TodoView = observer(({todo}) =>
<li className='list-group-item'>
<input
className="pull-right"
type="checkbox"
checked={todo.finished}
onClick={() => todo.finished = !todo.finished}
/>{todo.title}
</li>
);
const store = new TodoList();
React.render(
<TodoListView2 todoList={store} />,
document.getElementById('root')
);
store.todos.push(
new Todo("Get Coffee"),
new Todo("Write simpler code"),
new Todo("Another Todo")
);
store.todos[0].finished = true;