How to collect multi-field data in React via form

vahidinline

Vahid Afshari

Posted on July 26, 2022

How to collect multi-field data in React via form

If you want to collect user data through a form from Front with React js, you may face to the this issue, How to store data in react and then send it to whatever, like your express abckend server.

The first solution is to use useState() hook. It's not perfect but may help you in variues situations. But if you want to take several fields like name, email, birth date and so on, are you creating multi state?

So, simply don't do that. the better solution is to use single hook to take user data as an object in react.

**

How?

**

look at this code:

  const [userAuth, setUserAuth] = useState({
    email: '',
    password: '',
  });
Enter fullscreen mode Exit fullscreen mode

this would help you to store everything. no matter you want to get 2 inputs or 10, you only need a single useState().

then you may ask you how to hanle input?
you need a block of code like this. this function will handle your inputs and recognise them by their name and set the value.

  const handleInput = (e) => {
    const { name, value } = e.target;
    setUserAuth({
      ...userAuth,
      [name]: value,
    });
  };
Enter fullscreen mode Exit fullscreen mode

the only left thing is to assign handleInput to the input as a onchange event like this:

<Input type="email name="email" onChange={handleInput}/>
<Input type="text name="name" onChange={handleInput}/>

that's it. You then have an object will all user data

💖 💪 🙅 🚩
vahidinline
Vahid Afshari

Posted on July 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related