Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-select and typescript: Type 'string' is not assignable to type 'ValueType<OptionTypeBase>'

I am trying to create an example component that uses react-select with typescript.

For this, I created a functional component and added the default example from react-select docs:

const options = [
    {value: 'chocolate', label: 'Chocolate'},
    {value: 'strawberry', label: 'Strawberry'},
    {value: 'vanilla', label: 'Vanilla'},
];

const MyComponent = () => {

    const [selectedOption, setSelectedOption] = useState('chocolate');

    const handleChange = (option: string) => {
        setSelectedOption(option);
    };

    return (
        <Select
            value={selectedOption}
            onChange={(option) => handleChange(option)}
            options={options}
        />
    );

};

However, this gives me an error:

 Overload 1 of 2, '(props: Readonly<Pick<Props<OptionTypeBase>, string | number> & Props<OptionTypeBase> & Props<OptionTypeBase>>): StateManager<...>', gave the following error.
    Type 'string' is not assignable to type 'ValueType<OptionTypeBase>'.
  Overload 2 of 2, '(props: Pick<Props<OptionTypeBase>, string | number> & Props<OptionTypeBase> & Props<OptionTypeBase>, context?: any): StateManager<...>', gave the following error.
    Type 'string' is not assignable to type 'ValueType<OptionTypeBase>'.

what am I doing wrong?

My packages are:

    "@types/react": "^16.9.19",
    "@types/react-dom": "^16.9.5",
    "@types/react-select": "^3.0.10",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-select": "^3.0.8",
    "typescript": "^3.7.5"

like image 361
kurtgn Avatar asked Feb 11 '20 18:02

kurtgn


1 Answers

You need to set a value from your options array as the current value of Select component.

This however is not the only problem because the type signature of the onChange function is somewhat confusing. You'll need to define a type for the options and use `ValueType´ in the onChange function signature.

Here's a working example

type OptionType = {
  value: string;
  label: string;
};

const options: OptionType[] = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

const MyComponent = () => {
  const [selectedOption, setSelectedOption] = useState<ValueType<OptionType>>(options[0]);

  const handleChange = (option: ValueType<OptionType>) => {
    setSelectedOption(option);
  };

  return (
    <Select
      value={selectedOption}
      onChange={option => handleChange(option)}
      options={options}
    />
  );
};

More information about the issue https://github.com/JedWatson/react-select/issues/2902

Sandbox with the code above https://codesandbox.io/s/angry-frost-5bh1o

like image 121
brandfilt Avatar answered Nov 05 '22 06:11

brandfilt