Search code examples
javascriptreactjsfrontenddropdownsemantic-ui-react

How to see values in Semantic-UI-React with multiple attribute?


This is a really straight forward question. Notice I have the multiple attribute. When I select a value it just pushes a value into an array. Hence, if I have multiple values it will give me an array with multiple values but not the specific option I'm choosing.

Now my question is how do I get that specific value when I remove it from the Dropdown? I've searched google for an hour and haven't found an answer.

<Dropdown 
    options={options} 
    onChange={this.onChange.bind(this)}
    search fluid multiple selection/>

onChange(e,  { value } ) {
        e.preventDefault();     
       // e.target.value DOESN'T WORK???!!!

    }

Solution

  • So Dropdown from Semantic UI doesn't seem to provide this functionality out of the box. However, there's a decent way of achieving this. First, create a state like:

    this.state = {
      selected: [],
    }
    

    Then, bind a function to the Dropdown component like so:

    <Dropdown
      placeholder="Skills"
      fluid
      multiple
      selection
      options={options}
      onChange={this.handleChange}/>
    

    Once that's done, write the handleChange function to compare array lengths on every change. If state array is longer than whatever array you get from the dropdown, the item has been removed and you can check which one. Otherwise, dump the array into the state.

    handleChange = (e, { value }) => {
        if (this.state.selected.length > value.length) { // an item has been removed
            const difference = this.state.selected.filter(
                x => !value.includes(x),
            );
            console.log(difference); // this is the item
            return false;
        }
        return this.setState({ selected: value });
    };
    

    You'll need a polyfill to run in IE8 and below though.