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)
    ]}
/>
1
  • well, I guess if your ternary operator results in undefined it cannot be spread. Try wrapping undefined in brackets: [undefined] or using [] instead Commented Feb 4, 2019 at 12:59

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

 [...undefined] // doesnt work
 [...[]] // works

Comments

0

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

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.