Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch remove event in react-select when removing item from selected?

first of all, thanks for awesome work. It makes a lot easier for me. Then here i want to catch remove event, how can I do that? I read the documentation and could not find remove event

like image 829
Zorig Avatar asked Mar 27 '18 04:03

Zorig


People also ask

How do you remove selected value from dropdown in React?

By clicking on the clear icon which is shown in DropDownList element, you can clear the selected item in DropDownList through interaction.

How do I unselect the selected option in React?

const [selectedOptions, setSelectedOptions] = useState([]); return ( <> <Select options={options} isMulti hideSelectedOptions={false} controlShouldRenderValue={false} onChange={(e) => setSelectedOptions(e)} /> {selectedOptions.

How do I delete onClick in React?

Remove stand-alone element onclick in ReactAttach an event handler to the onClick event of the element. In the event handler, negate the value of the visibility state to remove the element from the DOM.


2 Answers

I don't think they have an event for that. They just have the onChange.

So, to detect if some option was removed, you would have to compare the current state with the new values the onChange emitted.

Example:

handleOnChange(value) {
  let difference = this.state.selected.filter(x => !value.includes(x)); // calculates diff
  console.log('Removed: ', difference);                         // prints array of removed

  this.setState({ selected: value });
}
render() {
  return (
    <div>
      <Select
        multi={this.state.multi}
        options={this.state.options}
        onChange={this.handleOnChange.bind(this)}
        value={this.state.selected}
        showNewOptionAtTop={false}
      />
    </div>
  );
}

Demo: https://codesandbox.io/s/7ymwokxoyq

like image 132
acdcjunior Avatar answered Oct 03 '22 02:10

acdcjunior


They don't have any event for that. I was facing the same problem but in my case, I was needing both the added and removed item. In case someone wants the both values

import 'difference' from 'lodash/difference'
this.currentTags = []
handleChange = (options) => {
    const optionsValue = options.map(({ value }) => value)
    if (this.currentTags.length < options.length) {
      const addedElement = difference(optionsValue, this.currentTags)[0]
      this.currentTags.push(addedElement)
      console.log("addedElement",addedElement)
      //call custom add event here
    }
    else {
      let removedElement = difference(this.currentTags, optionsValue)[0]
      console.log("removedElement", removedElement)
      // call custom removed event here
      let index = this.currentTags.indexOf(removedElement)
      if (index !== -1) {
        this.currentTags.splice(index, 1)
      }
    }
  }
like image 28
vijayscode Avatar answered Oct 03 '22 01:10

vijayscode