Skip to content

Instantly share code, notes, and snippets.

@francisngo
Last active December 29, 2017 02:39
Show Gist options
  • Save francisngo/576848415b08d802ad7d7ea75742a825 to your computer and use it in GitHub Desktop.
Save francisngo/576848415b08d802ad7d7ea75742a825 to your computer and use it in GitHub Desktop.
A stateful React component to add todo
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
todo: '',
}
this.onTodoChange = this.onTodoChange.bind(this);
this.addTodo = this.addTodo.bind(this);
}
onTodoChange(e) {
this.setState({
todo: e.target.value,
});
};
addTodo(e) {
e.preventDefault();
this.setState({
todos: this.state.todos.concat(
this.state.todo
),
todo: '',
});
};
render() {
const submitDisabled = !this.state.todo;
return(
<div id='app'>
<table>
<thead>
<tr>
<th>Todos</th>
</tr>
</thead>
<tbody>
{this.state.todos.map((todo, index) => (
<tr key={index}>
<td>{todo}</td>
</tr>
))
}
</tbody>
<tfoot>
<tr>
<th>
<form onSubmit={this.addTodo}>
<div className='field'>
<input
className='prompt'
type='text'
placeholder='Add todo...'
value={this.state.todo}
onChange={this.onTodoChange}
/>
</div>
<button
type='submit'
disabled={submitDisabled}
>
Add todo
</button>
</form>
</th>
</tr>
</tfoot>
</table>
</div>
)
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment