Listing 4-18: A typical class component
import React from 'react';
class ToDoClass extends React.Component{
constructor(props){
super(props);
this.state = {
item: '',
todolist: []
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(e){
e.preventDefault();
const list = [...this.state.todolist, this.state.item];
this.setState({
todolist:list
})
}
handleChange(e){
this.setState({item:e.target.value});
}
render(){
const currentTodos = this.state.todolist.map(
(todo,index)=><p key={index}>{todo}</p>);
return (
<form onSubmit={this.handleSubmit}>
<input type="text"
id="todoitem"
value={this.state.item}
onChange={this.handleChange}
placeholder="what to do?" />
<button type="submit">
Add
</button>
{currentTodos}
</form>
);
}
}
export default ToDoClass;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.