1

I have ENUMS as listed below

export declare enum UserStatus {
    NEW = "NEW",
    REGISTERED = "REGISTERED"
}

How do i ensure that i can use this dynamic way as dropdown items of select tag. I searched online at several sites and didnt find a suitable answer. Can someone please help.

Currently i am hardcoding this way.

<select value={selectedUserStatus} onChange={onUserStatusSelect}>
      <option
        aria-selected="true"
        key={UserStatus.NEW}
        value={UserStatus.NEW}
      >
        {UserStatus.NEW}
      </option>
      <option
        aria-selected="true"
        key={UserStatus.REGISTERED}
        value={UserStatus.REGISTERED}
      >
        {UserStatus.REGISTERED}
      </option>
    </select>

2 Answers 2

2

You can also use:

<select value={selectedUserStatus} onChange={onUserStatusSelect}>
    Object.values(UserStatus).map(value =>
        <option
            aria-selected="true"
            key={value]}
            value={value}
        >
            {value}
        </option>
    )
</select>
Sign up to request clarification or add additional context in comments.

3 Comments

I believe you need parentheses surrounding markup in JSX like that, or else you'll get a syntax error about a bad LHS argument.
No, in this particular case I do not
I'd recommend validating your JS
1

If it's JSX syntax you should be able to replace the mark-up inside of the element with an array of JSX elements like so:

<select value={selectedUserStatus} onChange={onUserStatusSelect}>
    Object.keys(UserStatus).map(key => (
        <option
            aria-selected="true"
            key={UserStatus[key]}
            value={UserStatus[key]}
        >
            {UserStatus[key]}
        </option>
        )
    )
</select>

1 Comment

Did this solution work for you? I typically use jsx in the context of Vue.js so I'm not totally sure this will work in React

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.