Listing 4-20: Further simplifying a function component
import {useState} from 'react';
export const ToDoFunctionSimple = (props)=>{
const [item,setItem] = useState('');
const [todolist,setTodoList] = useState([]);
const handleSubmit = (e)=>{
e.preventDefault();
const list = [...todolist, item];
setTodoList(list)
}
const currentTodos = todolist.map((todo,index)=><p key={index}>{todo}</p>);
return (
<form onSubmit={handleSubmit}>
<input type="text"
id="todoitem"
value={item}
onChange={(e)=>{setItem(e.target.value)}}
placeholder="what to do?" />
<button type="submit">
Add
</button>
{currentTodos}
</form>
);
}
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.