Home > front end >  Add to an array using spread operators - React/JS
Add to an array using spread operators - React/JS

Time:09-22

I have a dropdown in which I would like to use to add items to an array. Currently it functions that if you click, it will add to the array, however I want to ADD to the array, using the ...prevState NEW item. This will result in an array like

[
 option: "Additional leave",
option: "Pay",
option: "Holidays",

]

As you add more items.

How would you write this to {...spread} the state, and then ADD?

Currently i'm holding the state in two ways, I think this is wrong: first is what's been selected, second holding final list (IS GOAL)

    const [selectedBenefits1, setselectedBenefits1] = useState('')
    const [finalBenefits, setFinalBenefits] = useState([])

My component is:

 <Dropdown_Content>

                {interviewStageSelection.map((option, prev) => (
                    <Dropdown_Item 
                        key={option}
                        onClick={(e) => {
                        setselectedBenefits1(option)
                        setisActive(!isActive)
                        setFinalBenefits(prev=>({...finalBenefits, option}))
                        // setisActive(false)
                        // updateInterview1(dispatch, option)
                    }}
                    >
                      <Typography variant="subtitle5" color="black" sx={{ "&:hover": { color: "white" } }}>{option}</Typography>
                    </Dropdown_Item>
                ))}
            </Dropdown_Content>
```


I believe the main issue is:

```
setFinalBenefits(prev=>({...finalBenefits, option}))
```

How would you write this?

CodePudding user response:

Assume option is a string,

setFinalBenefits(prevFinalBenefits => [ // note that this is a square bracket (array), instead of a curly bracket (object)
    ...prevFinalBenefits, // why not using the prev value
    { option } // shorthand of { option: option }
]);
  • Related