Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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} />;
like image 403
Felipe Pinheiro Avatar asked Aug 17 '19 19:08

Felipe Pinheiro


People also ask

How do I use the Select option in react?

To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element.


1 Answers

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} />
    ),
  }} />;
};
like image 78
Emma Avatar answered Nov 04 '22 04:11

Emma