How can you set an enum value from a form field string?

Viewed 1178

I'm working with a field that should have a value that matches a value from an enum. However, TypeScript complains when I try to set the field value to state due to the incompatibility between the field value (a string) and the enum.

Here's an example of what I'm trying to do:

import * as React from "react";

enum ValidValues {
  foo = "foo",
  bar = "bar"
}

export default function App() {
  const [fieldValue, setFieldValue] = React.useState(ValidValues.foo);

  return (
    <input
      value={fieldValue}
      onChange={(e) => setFieldValue(e.currentTarget.value)}
    />
  );
}

I understand why I get the Argument of type 'string' is not assignable to parameter of type 'SetStateAction<ValidValues>' error, but I'm unsure how to make these compatible, if it is possible.

2 Answers

You should use a drop down menu or a checkbox when using enums. Then, change the value to match the enum.

<select onChange={e => 
setFieldValue(ValidValues[e.target.value as keyof 
typeof ValidValues])}>

<option value={ValidValues.foo}>{ValidValues.foo} 
<option/>

<option value={ValidValues.bar}>{ValidValues.bar} 
<option/>

</select>

I think you should be fine if you explicitly set the type of useState

const [fieldValue, setFieldValue] = React.useState<string>(ValidValues.foo);
Related