Home > OS >  Changing a single property of an object inside of array
Changing a single property of an object inside of array

Time:11-02

I have such state in my React project:

  const [information, setInformation] = React.useState([
    {
      Email: "",
      TellNo: "",
      Username: "",
      NationalityType: "",
      pIDCheck: "",
      VerificationCode: "",
      Password: "",
    },
  ]);

I want to update "TellNo" value when input values changes. I tried many approaches like this:

     onChange={(e) =>
            setInformation((prev) => [{...prev, TellNo: e.target.value }])
          }

but as you can see. it will add an additional object. how can I change my TellNo without adding an object

CodePudding user response:

Just do the below code:

  const [information, setInformation] = React.useState({
      Email: "",
      TellNo: "",
      Username: "",
      NationalityType: "",
      pIDCheck: "",
      VerificationCode: "",
      Password: "",
    });

onChange={(e) =>
            setInformation({...information, TellNo: e.target.value})
          }

and when you wanna send your information you can pass it in an array:

[information]

CodePudding user response:

With your current structure, you can try as below ...

onChange={(e) =>
   setInformation([{...information[0], TellNo: e.target.value }])
}
  • Related