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

13,128

Solution 1

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

Solution 2

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)
      }
    }
  }
Share:
13,128
Zorig
Author by

Zorig

Linux, Python, Django, Reactjs, Emberjs, Android, Redis, MongoDB, PostgreSQL

Updated on June 17, 2022

Comments

  • Zorig
    Zorig almost 2 years

    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

  • Zorig
    Zorig about 6 years
    whoa, thanks didn't think that it would work this way.
  • Zorig
    Zorig about 6 years
    is it possible to give argument for loadOptions ? Let's say i got 4 react-select components and each of them has a different endpoint. Currently, I put 4 different loadOptions function to them. Is it possible?
  • Matheus Ribeiro
    Matheus Ribeiro almost 4 years
    thanks, for me I wanted the array without the difference, not the difference itself, so I just removed the !, like this -> let difference = this.state.selected.filter(x => value.includes(x));