hc-oss / react-multi-select-component

Lightweight (~5KB gzipped) multiple selection dropdown component
https://codesandbox.io/s/react-multi-select-example-uqtgs
MIT License
386 stars 89 forks source link

Optional Checkbox and single select #417

Open BillPackard007 opened 3 years ago

BillPackard007 commented 3 years ago

Hi there, You did a good job on this package. Some time 'single select' selection option need, so I worked in my code to remove/pop the old selected array values and push the single select value. If single select option is available by default by adding multiSelect={false} attribute like this, would be helpful.

And one more, option check box too on single select. https://prnt.sc/19ok8b1 - direct link singleSelect_checkBox

Thank you

harshzalavadiya commented 3 years ago

@BillPackard007

as of now it's only designed for multiple selection, you can use react-select / html5 select as it works best for single selection

govindsartaj commented 3 years ago

Kind of a hacky way to do single selection, but you can use useEffect to ensure that there is only one option selected. I did it like this:


// assuming your selected options are stored in the 'selected' state
const [selected, setSelected] = useState([])

useEffect(() => {
    if (selected.length > 1) {
      setSelected([selected[selected.length - 1]])
    }
}, [selected])
pandevim commented 2 years ago

@govindsartaj a less hacky way 😃

const [selected, setSelected] = useState([])

const onChange = values =>
  setSelected(
    values.length < 1
      ? values
      : [values[values.length - 1]]
  )

return (
  <MultiSelect
    value={selected}
    onChange={onChange}
  />
)