An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
November 15, 2020 03:53 pm GMT
Original Link: https://dev.to/danim47c/the-best-way-of-handling-forms-in-react-with-hooks-27pj
The best way of handling forms in React with Hooks
Hello, there are several ways of handling forms with hooks in React. Some of us prefer having an state for each field and managing changes inline. Others, have an unique state object with all fields and manage changes in an external function.
What I most like doing and I think is the most clear and usable way is this:
const Form = () => { const [data, setData] = useState({ field1: "", field2: "" }) const handleChange = (key) => e => { setData(data => { data[key] = e.target.value }) } const handleSubmit = e => {...} return <form onSubmit={handleSubmit}> <input value={data.field1} onChange={handleChange("field1")} /> <input value={data.field2} onChange={handleChange("field2")} /> </form>}
Enter fullscreen mode Exit fullscreen mode
I have an only state with all fields and I handle all changes with the same function.
Hope you like my way.
How do you usually handle this?
Original Link: https://dev.to/danim47c/the-best-way-of-handling-forms-in-react-with-hooks-27pj
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To