I want to show a dropdown in React using the following enumeration. The idea is to prevent using random strings as keys in my <select>. Keys should be constrained to Stooges.larry, Stooges.curly and Stooges.moe:
const Stooges = {
larry: "Larry Fine",
curly: "Curly Howard",
moe: "Moe Howard"
};
Here's the code for my select, which works just fine:
<select value={stooge} onChange={handleChange}>
{Object.keys(Stooges).map(key => (
<option key={key} value={key}>
{Stooges[key]}
</option>
))}
</select>
The problem comes in when I am trying to set the initial value of the dropdown - I have to use a hard coded key:
const [stooge, setStooge] = React.useState('larry');
I can soften this a bit by picking the first key:
const keys = Object.keys(Stooges);
const [stooge, setStooge] = React.useState(keys[0]);
However, this still feels wrong. I can't tell from key[0] who am I picking.
Is there a better way to deal with enumerations in this use case? I have tried string enums in TypeScript, but they have the same issue:
enum Stooges {
larry = "Larry Fine",
curly = "Curly Howard",
moe = "Moe Howard"
}
Please see my CodeSandbox here.
keyof Stoogeswould only work fortype Stooges = {...}, so I deleted my answer :(