React Select Creatable "no options" instead of "create"

Viewed 8122

I am trying to create a select element with react-select and I use the Creatable component for that.

With my current implementation, it won't prompt the user for "create" option on typing, as shown on the documentation It will show instead the default "No options".

I am also using redux-form library but I don't think that the problem comes from there.

Here is my code so far :


import Select from "react-select/creatable";
import React from "react";

const customFilter = (option, searchText) => {
  return option.data.searchfield.toLowerCase().includes(searchText.toLowerCase());
};

export default (props) => {
  const { input, options, placeholder } = props;

  const renderValue = (value) => {
    const val =
      value === "" ? null : options.find((obj) => obj.value === input.value);
    return val || "";
  };

  return (
    <Select
      value={renderValue(input.value)}
      name={input.name}
      onFocus={() => input.onFocus(input.value)}
      onChange={(value) => input.onChange(value.value)}
      onBlur={() => input.onBlur(input.value)}
      options={options}
      isRtl={true}
      placeholder={placeholder}
      filterOption={customFilter}
    />
  );
};

EDIT :

I also tried from the docs to import the makeCreatableSelect but it did not help:

    import Creatable, { makeCreatableSelect } from 'react-select/creatable';
<Creatable 
  //here goes props
/>
1 Answers

I think your problem here comes from your custom filter implementation

This a little bit tricky, because from the docs there is no example of the CreatableSelect with an implementation of custom filter.

To solve this, your custom filters must retrun "undefined" in order to "tell" to the <CreatableSelect /> component that there is no such option.

So here is one option to achieve this :

       const customFilter = (option, searchText) => {
          return option.data.searchfield !== undefined ? option.data.searchfield.toLowerCase().includes(searchText.toLowerCase())
: "undefined"
        };

In this way your CreatableSelect will known if the value was found

Another problem that I noticed in your code is that your renderValue method will return an empty string when it does not find a matching option...not good : if you want the users to create option you have to render it when it will be created...not an empty string.

So replace this by something like :

    const renderValue = (value) => {
      const val = value === "" ? 
                  null : 
                  options.find((obj) => obj.value === input.value);
      return val || {value : value, label: value};
  };

That will create your new option. Of course you can change the label by your own logic.

Related