Mobx + React simple todolist
by lasha
HTML
<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/mobx@3/lib/mobx.umd.js"></script>
<script src="https://unpkg.com/mobx-react@4"></script>
<script src="https://unpkg.com/mobx-react-devtools@4"></script>
<body>
<div id="mount">
</div>
</body>
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 {
constructor() {
super();
this.onChange = this.onChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
text: null
}
}
onChange(e) {
this.setState({text: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
store.todos.push(new Todo(this.state.text))
var clearTextField = '';
this.setState({text: clearTextField});
}
render() {
return <div>
<ul>
{this.props.todoList.todos.map(todo =>
<TodoView todo={todo} key={todo.id} />
)}
</ul>
<form onSubmit={this.handleSubmit}>
<input onChange={this.onChange} value={this.state.text} />
<button>Submit Input/Form</button>
</form>
<button onClick={() =>store.todos.push(new Todo(window.prompt('Enter todo text')))}>Add Item Via Prompt</button>
<br/>
Tasks left: {this.props.todoList.unfinishedTodoCount}<br/>
Total Tasks: {store.todos.length}
<mobxDevtools.default />
</div>
}
}
const TodoView = observer(({todo}) =>
<li>
<input
type="checkbox"
checked={todo.finished}
onClick={() => todo.finished = !todo.finished}
/>{todo.title}
</li>
);
const store = new TodoList();
ReactDOM.render(<TodoListView todoList={store} />,...