Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding element to array in react useState object

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use spread syntax for an array.

setAddVendor({...addVendor, vendorArea: [...addVendor.vendorArea, newItem1, newItem2]})
setAddVendor({...addVendor, vendorArea: [...addVendor.vendorArea, ...newItems]})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading