React-Select - clickable values with custom handler

Viewed 3001

Using react-select, I'd like to understand how I can get the events for when selected values (multi) are clicked.

I'm using react-select with the multi select functionality (https://react-select.com/home). Works as a charm but I'd like to make the values clickable/toggleable to change color/state (not add/remove). In the end showing them in grey/color to indicate a marked state and using the underlying state for subsequent code. Is there any way to achieve this and if so how?

1 Answers

You could pass in a custom MultiValueLabel or MultiValueContainer and add an onClick handler.

import React from "react";
import ReactDOM from "react-dom";
import Select, { components } from 'react-select';


const options = [
  {value: '1', label: 'Item 1', isToggled: true},
  {value: '2', label: 'Item 2', isToggled: false},
  {value: '3', label: 'Item 3', isToggled: false},
  {value: '4', label: 'Item 4', isToggled: false},
  {value: '5', label: 'Item 5', isToggled: false},
  {value: '6', label: 'Item 6', isToggled: false},
]

const ReactSelectStyles = () => ({
  multiValueLabel: (styles, {data: { isToggled }}) => ({
    ...styles,
    backgroundColor: isToggled ? 'hotpink' : null,
    color: isToggled ? 'white' : null
  }),
});

const handleMultiValueClick = (e, props) => {
  e.stopPropagation();
  e.preventDefault();


  console.log('A multi value has been clicked', props);

  const option = options.find(option => option.value === props.data.value);

  option.isToggled = !option.isToggled
}

const MultiValueLabel = props => {
  return (
    <div onClick={(e) => handleMultiValueClick(e, props)}>
      <components.MultiValueLabel {...props} />
    </div>
  );
};

function App() {
  return (
    <Select
    closeMenuOnSelect={false}
    components={{ MultiValueLabel }}
    defaultValue={[options[0], options[2], options[4]]}
    isMulti
    options={options}
    styles={ReactSelectStyles()}
  />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Working Example

Related