Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 15, 2020 03:53 pm GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To