Home > database >  React-select: How to add created items to options list
React-select: How to add created items to options list

Time:10-02

So I'm using the Creatable component of the react-select library. I want to be able to add the created option into my options array on keyDown. Adding custom tag

Result of creating tag

Result of creating tag

CodePudding user response:

So I was way over-complicating this. And thanks to the answer above, i was able to approach it better. I needed to be able to add the tags via keyboard, have them be added into the dropdown list, and then be able to get deleted. Here's the full answer

  const [inputValue, setInputValue] = useState('');
  const [selectedValues, setselectedValues] = useState({ selected: [] });

  const [selection, setSelection] = useState(statusOptions);

  const handleInputChange = (value) => {
    setInputValue(value);
  };

  const handleOnChange = () => {
    const newOption = { label: inputValue, inputValue };

    inputValue !== '' && setSelection([...selection, newOption]);

    setInputValue('');

    setselectedValues(selection);
  };

  return (
    <div>
      <CreatableSelect
        options={selection}
        isMulti
        onChange={handleOnChange}
        onInputChange={handleInputChange}
        inputValue={inputValue}
        value={selectedValues.selected}
        inputValue={inputValue}
        controlShouldRenderValue={true}
      />
    </div>
  • Related