score:29

Accepted answer

You can type the whole style object by using StyleConfig which removes the need to type every params manually. But before that you'll need to install @types/react-select package.

StyleConfig requires you to pass at least 2 generic type variables according to this declaration here.

  • OptionType: The option type of react-select. According to this, the default OptionType is { label: string; value: string }
  • IsMulti: a boolean value to determine if you can select multiple values.

Putting it all together, we'll have something like this:

import Select, { StylesConfig } from 'react-select';

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

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

const customControlStyles: CSSProperties = {
  color: "white",
  borderColor: "pink"
};

type IsMulti = false;

const selectStyle: StylesConfig<MyOptionType, IsMulti> = {
  control: (provided, state) => {
    // provided has CSSObject type
    // state has ControlProps type

    // return type is CSSObject which means this line will throw error if uncommented
    // return false;

    return {
      ...provided,
      ...customControlStyles
    };
  }
};
export function App() {
  return (
    <Select options={options} styles={selectStyle} />
  );
}

Live Demo

Edit 63696310/how-to-use-typescript-with-the-definition-of-custom-styles-for-a-select-using-re


Related Query

More Query from same tag