Properly use NoOptionsMessage in react-select to change the "no options" text

Viewed 8478

I am trying to change the "No options" message in react-select? I was able to do this with the following code

<AsyncSelect 
    styles={customStyles} 
    components={{ DropdownIndicator: () => null, IndicatorSeparator: () => null, NoOptionsMessage: () => "test" }} 
    className="form-control firm-search"
    cacheOptions
    defaultOptions
    value={selectedValue}
    getOptionLabel={e => e.name}
    getOptionValue={e => e.path}
    loadOptions={loadOptions}
    onInputChange={handleInputChange}
    onChange={handleChange}
    placeholder='test ...'
/>

The problem is that the text is not styled anymore. Is it possible to change the text but keep the default style? If not, is it then possible to apply CSS to the new text?

3 Answers

There are two ways to style the custom component. You can pass a style object to styles prop or create a new custom component.

Following code shows both approaches.

import React from "react";
import "./style.css";
import Select, { components } from "react-select";

const msgStyles = {
  background: "skyblue",
  color: "white"
};

const NoOptionsMessage = props => {
  return (
    <components.NoOptionsMessage {...props}>
      <span className="custom-css-class">Text</span> 
    </components.NoOptionsMessage>
  );
};

const CustomNoOptionsMessage = () => {
  return (
    <Select
      isClearable
      components={{ NoOptionsMessage }}
      styles={{ noOptionsMessage: base => ({ ...base, ...msgStyles }) }}
      isSearchable
      name="color"
      options={[]}
    />
  );
};

export default function App() {
  return (
    <div>
      <CustomNoOptionsMessage />
    </div>
  );
}

Here you can find the working code:https://stackblitz.com/edit/react-lejn8c?file=src/App.js

Another way to do this:

<AsyncSelect
  isClearable
  defaultOptions
  cacheOptions
  defaultOptions
  value={selectedValue}
  getOptionLabel={e => e.name}
  getOptionValue={e => e.path}
  loadOptions={loadOptions}
  onInputChange={handleInputChange}
  onChange={handleChange}
  noOptionsMessage={({inputValue}) => !inputValue ? noOptionsText : "No results found"} 
/>

There is a documented way of doing this: https://react-select.com/components

You can define your own NoOptionMessage component:

import { components } from 'react-select';

const NoOptionsMessage = props => {
  return (
     <components.NoOptionsMessage {...props}>
        Test…
     </components.NoOptionsMessage>
  );
};

In the components module you can access every native implementation so you don't need to reinvent the wheel.

Related