Search code examples
reactjstestingcomponentsreact-select

Add custom data- attribute to Option component react-select


I am creating a test for my dropdown searchable component using react-select library.
I am not able to add data-testid attribute to the Option component when customizing that component as it is defined in react-select documentation.

The data-testid attribute does not show in the DOM for Option element.

Option component

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

const CustomOption = (props: OptionProps<SearchDropdownOption, false>) => (
  <components.Option {...props} data-testid="test-id" />
);

For example i had a success with the Input component for search version of the dropdown and data-testid attribute shows in the DOM:

Input component

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

const CustomInput = (props: InputProps<SearchDropdownOption, false>) => (
  <components.Input {...props} data-testid="test-id" />
);

And than using it in Select component:

<Select<SearchDropdownOption, false>
  components={{
    Input: CustomInput,
    Option: CustomOption,
  }}
  isSearchable={isSearchable}
/>

Solution

  • It is impossible to add custom attribute data-testid directly to the Option component as i did for Input component. I need to extend this component with an HTML span element, or any other, and add this attribute to that element directly:

    const CustomOption = (props: OptionProps<SearchDropdownOption, false>) => {
      return (
        <components.Option {...props}>
          <span data-testid="test-id" key={props.innerProps.key}>
            {props.data.label}
          </span>
        </components.Option>
      );
    };
    

    NOTE This key prop is important as it gives the regular React uniqueness to the element and value for that can be used from the react-select's innerProps property:

    key={props.innerProps.key}