0
votes

I am using react-select and the creatable function that allows you to create a new select option - just type in the select/input field on example.

I want to put a check in that only allows one creatable option to be made at one time, the next created option removes and supersedes the previous. At the moment yo can create an infinite amount.

This is the part that handles the created option so guess I need to add some sort of rule to only allow one option here.

Any help appreciated.

  handleCreate = input => (inputValue: any) => {
    this.setState({ isLoading: true });
    setTimeout(() => {
      const { options } = this.state;
      const newOption = createOption(inputValue);
      this.setState({
        isLoading: false,
        options: [...options, newOption],
        value: newOption
      });
      input.onChange(newOption);
    }, 1000);
  };

https://codesandbox.io/s/o49kjl09j9

1

1 Answers

1
votes

What you could do is storing the index of the new option, check if there is an index stored and if so replace this value by the new one like the following code:

state = {
    value: this.props.options[0],
    options: this.props.options,
    hasCreatedOption: false
  };
  handleCreate = input => (inputValue: any) => {
    this.setState({ isLoading: true });
    setTimeout(() => {
      const { options } = this.state;
      const newOption = createOption(inputValue);
      let hasCreatedOption = false;

      if (this.state.hasCreatedOption) {
        options[this.state.hasCreatedOption] = newOption;
      } else {
        options.push(newOption);
      }
      hasCreatedOption = options.length - 1;

      this.setState({
        hasCreatedOption,
        isLoading: false,
        options: [...options],
        value: newOption
      });
      input.onChange(newOption);
    }, 1000);
  };

Here a live example.