Home > Software engineering >  Adding element to array in react useState object
Adding element to array in react useState object

Time:03-10

I am new to JavaScript, I want to push an element into an array that is in an object which is a react state.

const [addVendor, setAddVendor] = React.useState({
    vendorName: "",
    vendorPhone: "",
    vendorWhatsApp: "",
    vendorClass: "",
    vendorArea: []
});
const handleChecked = (e, areaName) => {
    if (e.target.checked === true) {
        setAddVendor({ ...addVendor, vendorArea: })
    }
} //I am confused here because I want to push multiple elements here as user selects the items
//I want to push areaName here

CodePudding user response:

You can use spread syntax for an array.

setAddVendor({...addVendor, vendorArea: [...addVendor.vendorArea, newItem1, newItem2]})
setAddVendor({...addVendor, vendorArea: [...addVendor.vendorArea, ...newItems]})
  • Related