Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the values from form using React?

Tags:

reactjs

I have set an initial state to store all of the values from my form. However, in order to tell the program that I'm targetting a checkbox I need to specify the type:

e.target.type === 'checkbox'

Even though it works I feel like I shouldn't need to specify the type in order to pull it's value. Can anyone tell me if this is the correct way to do it or if I'm missing something, please?

My STATE prints username, lastname and accept fields when interacting with the form, example:

{username: "Mike", lastname: "Brown", accept: true}

and here's a working DEMO:

like image 404
Devmix Avatar asked Oct 20 '25 00:10

Devmix


1 Answers

If you don't want to use a conditional in your handleChange, you can pass the value directly to the function like this:

const handleChange = (attribute, value) =>
  setInitialState((prev) => ({
    ...prev,
    [attribute]: value
  }));

And in your form use it like this:

return (
  <form>
    <input
      type="text"
      value={username}
      onChange={(e) => handleChange("name", e.target.value)}
    />
    <input
      type="checkbox"
      checked={accept}
      onChange={(e) => handleChange("accept", e.target.checked)}
    />
  </form>
);

Hope it helps.

like image 191
Toshio Minei Avatar answered Oct 22 '25 19:10

Toshio Minei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!