0

I have this enum:

const SPORTS = {
    FOOTBALL: 0,
    GOLF: 1,
    TENNIS: 2
};

I'm trying to use those values in a react select dropdown using lodash's forIn

<select onChange={(event) => this.update(event, sport.id)}>
  {_.forIn(SPORTS, (key, value) => {
    {
      <option value={key}>{value}</option>;
    }
  })}
</select>;

But am getting the error:

Invariant Violation: Objects are not valid as a React child

EDIT:

Changing to _.map works but am now seeing another issue.

Before I was manually adding all the options like which worked fine:

<option value={0}>FOOTBALL</option>;
<option value={1}>GOLF</option>;
<option value={2}>TENNIS</option>;

Now using the map I get this error:

Each child in an array or iterator should have a unique "key" prop

Now when my select boxes render they are empty but I'm not sure why.

3
  • forIn returns an object, not a component. Commented May 12, 2021 at 9:50
  • You are returning object literal instead of JSX element. Use _.forIn(SPORTS, (key, value) => (<option value={key}>{value}</option>)) Commented May 12, 2021 at 9:50
  • @nbokmans forIn returns the object that it was given. It just iterates over it, doesn't perform a mapping. Commented May 12, 2021 at 9:52

1 Answer 1

3

The _.forIn() function returns the iterated object, use _.map() instead:

<select onChange={(event) => this.update(event, sport.id)}>
  {_.map(SPORTS, (value, key) => (
    <option value={key} key={key}>{value}</option>;
  ))}
</select>;
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I just added an edit as I'm still having an issue doing it this way
It was missing the key property. See edit.
Thanks, the exception about the key has gone but now my select boxes are empty and when I click the dropdown there are no options there. Is there any reason you can think of why that is?
You need to return the component as well. Updated.
did you figure this out ?- I'm trying to do this with chakra-react-select

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.