Skip to content
Advertisement

Dropdown with multiple selection limit

I relatively new to React and Semantic UI as well. There is a component called Dropdown with a props multiple and selection, which allows to select multiple items.

On the output my state looks like this:

const selectedItems = [
   {key: 1, value: 1, text: 'Item 1'},
   {key: 2, value: 2, text: 'Item 2'},
   {key: 3, value: 3, text: 'Item 3'},
];

How can I do setup limit of N amount of elements?

Many thanks

Advertisement

Answer

Well according to https://react.semantic-ui.com/modules/dropdown#dropdown-example-multiple-selection you need to create controlled component, which means you will bind value={this.state.selectedItems} then you will bind onChange={(e,data) => { this.handleChange(e,data )} and in your code

onChange (e, data) {
  const currentItems = this.state.selectedItems

  if (currentItems.length <= MAX_SELECTION ) {
    currentItems.push(data)

    this.setState({
      selectedItems: currentItems
    })
  }
}

this will crate controlled component which will allows you to control state by yourself, and you will limit changing state, probably you will need to also handle removing items from state inside this onChange event.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement