Skip to content

Instantly share code, notes, and snippets.

@saitoxu
Last active Mar 30, 2017
Embed
What would you like to do?
2017-03-30
import React, { Component } from 'react';
import Form from './Form';
import TodoList from './TodoList';
export default class App extends Component {
constructor() {
super();
this.state = {
todos: []
};
}
handleSubmit(e) {
e.preventDefault();
const title = e.target.elements[0].value;
if (!title) {
return;
}
const desc = e.target.elements[1].value;
const todos = this.state.todos.slice()
todos.push({
title: title,
desc: desc,
done: false
});
this.setState({ todos: todos });
}
render() {
return (
<div>
<Form onSubmit={this.handleSubmit.bind(this)} />
<TodoList todos={this.state.todos} />
</div>
);
}
}
import React, { Component } from 'react';
export default class Form extends Component {
render() {
return (
<div>
<form onSubmit={this.props.onSubmit}>
<input type="text" placeholder="title"/><br/>
<textarea placeholder="description" rows="8"></textarea><br/>
<button type="submit">Create</button>
</form>
</div>
);
}
}
import React, { Component } from 'react';
export default class Todo extends Component {
constructor(props) {
super(props);
this.state = {
title: props.title,
desc: props.desc,
done: props.done
};
}
handleClick(e) {
e.preventDefault();
this.setState({
done: !this.state.done
});
}
render() {
const link = this.state.done? 'Undone' : 'Done';
const className = this.state.done? 'done' : null;
return (
<li>
<span className={className}>{this.state.title}</span>
&nbsp;
<a href="#" onClick={this.handleClick.bind(this)}>{link}</a>
</li>
);
}
}
import React, { Component } from 'react';
import Todo from './Todo';
export default class TodoList extends Component {
render() {
const todos = [];
for (let i = 0; i < this.props.todos.length; i++) {
todos.push(
<Todo
key={i}
title={this.props.todos[i].title}
desc={this.props.todos[i].desc}
done={this.props.todos[i].done}
/>
);
}
return (
<ol>
{todos}
</ol>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment