Felipe Pinheiro
Felipe Pinheiro

Reputation: 333

How to use react-select types when creating custom components?

I am trying to create custom components for DropdownIndicator and use on react-select with Typescript, but I am having some issues with the type of the component because I am new to typescript.

How can I use types defined on @types/react-select on my component?

I've installed @types/react-select and there is already a type for DropdownIndicator, but I've found no way to reference it.

This is my index.tsx:

import React from 'react';
import Select from 'react-select';

import DropdownIndicator from './dropdown-indicator';

const components = {
  DropdownIndicator,
};

const SelectFilter: React.FC = () => {
  return <Select components={components} />;
};

export default React.memo(SelectFilter);

This is my dropdown-indicator.tsx:

import React from 'react';

import DropdownIcon from './dropdown-icon';

const DropdownIndicator: React.FC = props => {
  const {
    selectProps: { isMenuOpen },
  } = props;

  return <DropdownIcon isUp={isMenuOpen} />;
};

export default React.memo(DropdownIndicator);

Since I didn't defined any prop types, the error is:

/Users/felipepinheiro/Workspace/test/src/components/select-filter/dropdown-indicator.tsx
TypeScript error in /Users/felipepinheiro/Workspace/test/src/components/select-filter/dropdown-indicator.tsx(7,5):
Property 'selectProps' does not exist on type '{ children?: ReactNode; }'.  TS2339

     5 | const DropdownIndicator: React.FC = props => {
     6 |   const {
  >  7 |     selectProps: { isMenuOpen },
       |     ^
     8 |   } = props;
     9 | 
    10 |   return <DropdownIcon isUp={isMenuOpen} />;

Upvotes: 12

Views: 9353

Answers (1)

Emma
Emma

Reputation: 834

I left a comment but putting this in an answer since it'll be more legible with proper formatting

You can directly import the IndicatorProps type from react-select package and then pass your props to the component directly from within your select component

import { IndicatorProps, OptionType } from 'react-select';


const SelectFilter: React.FC = () => {
  return <Select components={{
    Indicator: (indicatorProps: IndicatorProps<OptionType>) => (
      <components.DropdownIndicator {...indicatorProps} />
    ),
  }} />;
};

Upvotes: 8

Related Questions