0

I am trying to achieve the following:
In React, I have a component where a prop takes an array with objects, whereafter that component displays these objects in a dropdown menu item.
I would like to make some of thesedropdown menu items conditionally. In other words: some users may see a dropdown item, where others won't.

What is the correct way to achieve this? I tried using the spread operator (according to this Answer, but I keep getting the error

TypeError: Invalid attempt to spread non-iterable instance

What am I doing wrong?

My code:

<Dropdown
    type="link"
    itemsObject={
       [...states.all.map(state => ({
           value: state.name,
           onClick: () => {
               this.updateCandidate(candidate, {state_id: state.id})
           }
        })),
        {
            isDivider: true
        },
        {
            value: "Notities bewerken",
            onClick: () => {
                this.openCandidateModel(candidate)
            }
        },
        ...(candidate.state.id === 2 ? [{
                value: "Afspraak beheren",
                onClick: () => {
                    this.openCandidateModel(candidate)
                }
           }] : undefined)
    ]}
/>
Eran Machiels
  • 729
  • 2
  • 8
  • 17
  • well, I guess if your ternary operator results in `undefined` it cannot be spread. Try wrapping undefined in brackets: `[undefined]` or using `[]` instead – Nick Parsons Feb 04 '19 at 12:59

4 Answers4

1

You're trying to spread undefined when candidate.state.id !== 2. Change it to:

...(candidate.state.id === 2 ? [{
                value: "Afspraak beheren",
                onClick: () => {
                    this.openCandidateModel(candidate)
                }
           }] : [])

Also, it's probably worth mentioning that {...undefined} is valid but [...undefined] isn't: Spreading undefined in array vs object

adiga
  • 34,372
  • 9
  • 61
  • 83
0

You cannot spread undefined, but you can spread an empty array:

 [...undefined] // doesnt work
 [...[]] // works
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You are trying to spread undefined that is causing the error. Use ? [{}] : []

Niall
  • 804
  • 10
  • 27
0
   ...(candidate.state.id === 2 ? [{
            value: "Afspraak beheren",
            onClick: () => {
                this.openCandidateModel(candidate)
            }
       }] : undefined)

I believe the problem should be in this part as you can't spread undefined you can use empty array instead [ ].

Thanks!

Shraddha Goel
  • 869
  • 7
  • 18