I created a simple to do list wherein the add and delete works. My problem is, after submitting a todo, the input box won't clear.
This is my app.js
const App = () => {
const [toDoList, setToDoList] = useState([]);
const [toDo, setToDo] = useState("");
const handleToDo = (event) => {
const { value } = event.target;
setToDo(value);
};
const submit = () => {
//const list = toDoList;
const newItem = {
id: 1 + Math.random(),
value: toDo,
};
if (newItem.value && !toDoList.includes(newItem.value)) {
toDoList.push(newItem);
setToDoList([...toDoList]);
}
};
return (
<div className="container">
Add an Item
<br />
<input
type="text"
placeholder="Type item here..."
onChange={handleToDo}
/>
<button className="add-btn btn-floating" onClick={submit}>
<i class="material-icons"> + </i>
</button>
<br />
<ul>
...display of todos here
</ul>
</div>
);
//}
};
export default App;
I'm confused as to where I should insert the useState so that the input would be reset.
The value of the input box must also be governed by the state. So the input should be like:
<input
value={toDo}
type="text"
placeholder="Type item here..."
onChange={handleToDo}
/>
Once You click on submit, reset the toDo to empty
const submit = () => {
//const list = toDoList;
const newItem = {
id: 1 + Math.random(),
value: toDo,
};
if (newItem.value && !toDoList.includes(newItem.value)) {
toDoList.push(newItem);
setToDoList([...toDoList]);
}
setToDo("");
};
Your input seems to be half-controlled. You should also give the input a value property as such:
<input
type="text"
placeholder="Type item here..."
onChange={handleToDo}
value={toDo}
/>
And now you can clear out the input when a task is submitted:
const submit = () => {
//rest of the code here...
setToDo('') //this'll clear out the value of your input
};
You can add a value to input element. And after submit, set it to an empty string. So:
const App = () => {
const [toDoList, setToDoList] = useState([]);
const [toDo, setToDo] = useState("");
const handleToDo = (event) => {
const { value } = event.target;
setToDo(value);
};
const submit = () => {
//const list = toDoList;
const newItem = {
id: 1 + Math.random(),
value: toDo,
};
if (newItem.value && !toDoList.includes(newItem.value)) {
toDoList.push(newItem);
setToDoList([...toDoList]);
setToDo("");
}
};
return (
<div className="container">
Add an Item
<br />
<input
type="text"
value={toDo}
placeholder="Type item here..."
onChange={handleToDo}
/>
<button className="add-btn btn-floating" onClick={submit}>
<i class="material-icons"> + </i>
</button>
<br />
<ul>
{toDoList.map((todoLi) => (
<li>{todoLi}</li>
))}
</ul>
</div>
);
//}
};
export default App;