Clue Mediator

Implement custom search with custom label using react-select

๐Ÿ“…December 23, 2022
๐Ÿ—ReactJS

Today, we will show you how to implement custom search with custom label using react-select. In the past article, we have added an icon in the react-select dropdown. But when you search for the label then you canโ€™t search the item. So we have to implement the custom search using different key.

Demo Application

Output - Implement custom search with custom label using react-select - Clue Mediator

Output - Implement custom search with custom label using react-select - Clue Mediator

Custom search with custom label using react-select

  1. Add custom label in react-select dropdown
  2. Implement custom search
  3. Output

1. Add custom label in react-select dropdown

Refer to the following article to implement react-select dropdown in React Application.

How to add an icon in the react-select dropdown

2. Implement custom search

To implement custom search, we have to use `filterOption` property of the react-select React Package">package where you can write your custom logic to filter the dropdown items.

function App() {
  ...
  ...

  const filterOption = (option, inputValue) => {
    return option.data.text.toLowerCase().includes(inputValue.toLowerCase());
  }

  return (
    <select ...="" filteroption={filterOption}>
  );
}

3. Output
Let's combine all the code together and see how it looks.App.js
import React, { useState } from 'react';
import Select from 'react-select';function App() {
  const data = [
    {
      value: 1,
      text: 'Up Arrow',
      icon:


    },
    {
      value: 2,
      text: 'Down Arrow',
      icon:


    },
    {
      value: 3,
      text: 'Left Arrow',
      icon:


    },
    {
      value: 4,
      text: 'Right Arrow',
      icon:


    }
  ];  const [selectedOption, setSelectedOption] = useState(null);  // handle onChange event of the dropdown
  const handleChange = e => {
    setSelectedOption(e);
  }  // handle custom filter
  const filterOption = (option, inputValue) => {
    return option.data.text.toLowerCase().includes(inputValue.toLowerCase());
  }  return (

      Custom search in react-select dropdown - Clue Mediator      </select> (
          <div style={{ display: 'flex', alignitems: 'center' }}>
            {e.icon}
            <span 5="" style={{ marginleft: }}>{e.text}</span>
          </div>
        )}
        filterOption={filterOption}
      />

      {selectedOption && <div style={{ margintop: 20, lineheight: '25px' }}>
        <b>Selected Option:</b> {selectedOption.value}
      </div>}

  );
}

export default App;

Run the project and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚

Demo & Source Code

GitHub Repository StackBlitz Project