-->

How do I create new option if there are no left wh

2019-09-20 06:18发布

问题:

I need to create new option with label "Ostatni" while filtering if there are no options left. I tried to do it by customising MenuList and NoOptionsMessage, but nothing works. Is there any way?

NoOptionsMessage = props => (
    <components.NoOptionsMessage
        {...props}
        children={<components.Option {...components.Option.defaultProps} data={{ value: 37, label: 'Ostatni' }} />}
    />
)

回答1:

You can achieve your goal using filterOption function like the following code:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasExtraValue: false,
      options: [
        { label: "Label 1", value: 1 },
        { label: "Label 2", value: 2 },
        { label: "Label 3", value: 3 },
        { label: "Label 4", value: 4 },
        { label: "Label 5", value: 5 },
        { label: "Label 6", value: 6 },
        { label: "Label 7", value: 7 },
        { label: "Label 8", value: 8 },
        {label: 'Ostatni', value: 'other'}
      ]
    };
  }
  filterOption = (option, inputValue) => {
    // tweak the filterOption to render Ostatni only if there's no other option matching + set hasExtraValue to true in case you want to display an message
    if (option.label === "Ostatni"){
      const {options} = this.state
      const result = options.filter(opt => opt.label.includes(inputValue))
      this.setState({ hasExtraValue: !result.length})
       return !result.length
       };

    return option.label.includes(inputValue);
  };

  render() {
    return (
      <div>
        <Select
          isMulti
          filterOption={this.filterOption}
          noOptionsMessage={() => "No more options"}
          options={this.state.options}
        />
        // Displays a user friendly message to explain the situation
        {this.state.hasExtraValue && <p>Please select 'Ostatni' option if you don't find your option !</p>}
        </div>
    );
  }
}

The idea is to trigger when the user is typing something. If there's no options available you add a new one the desired label to offer the user a new option.

In filterOption you set this special option to be always true so it will always displayed if it exists.

Here a live example.