I try to make a todo list with React and Redux Toolkit. In handleSubmit function to add item on list, my setText somehow not set the value to empty string. Here are my full code on Stackblitz: https://stackblitz.com/edit/react-ts-bqmjz1?file=components%2FTodoForm.tsx
const TodoForm = (): JSX.Element => {
//Input value
const [text, setText] = useState('');
const dispatch = useDispatch();
//setText not working
const handleSubmit = (e: any) => {
e.preventDefault();
if (text.trim().length === 0) {
return;
}
dispatch(addItem({ title: text }));
setText('');
};
return (
<form className="container-fluid" onSubmit={handleSubmit}>
<div className="input-group">
<input
className="form-control"
placeholder="Enter the value..."
onChange={(e: { target: HTMLInputElement }) =>
setText(e.target.value)
}
/>
{/* Submit button */}
<button type="submit" className="btn btn-primary">
Add
</button>
</div>
</form>
);
};
You're very close! You just missed the value prop on the input:
value={text}
const TodoForm = (): JSX.Element => {
//Input value
const [text, setText] = useState('');
const dispatch = useDispatch();
//setText not working
const handleSubmit = (e: any) => {
e.preventDefault();
if (text.trim().length === 0) {
return;
}
dispatch(addItem({ title: text }));
setText('');
};
return (
<form className="container-fluid" onSubmit={handleSubmit}>
<div className="input-group">
<input
className="form-control"
placeholder="Enter the value..."
value={text}
onChange={(e: { target: HTMLInputElement }) =>
setText(e.target.value)
}
/>
{/* Submit button */}
<button type="submit" className="btn btn-primary">
Add
</button>
</div>
</form>
);
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments