How to make handle action for disable option in react-select?

I want to make custom event and dispatch him, when user click on disabled option in react-select dropdown. But any events dont work in this case, because input is disabled. Any ideas how to make this? Maybe i can wrap option in div, if this option disabled?

<Select
  value={this.state.cityOptions}
  onChange={this.handleChange}
  options={this.state.cityList}
  styles={customStyles}
  placeholder="City"
  name="cityOptions"
  isSearchable={false}
  isOptionDisabled={(option) => option.disabled}
/>

Upvotes: 1

Views: 6133

Answers (2)

Laura
Laura

Reputation: 8650

With react-select I recommend you to use a custom Option component like this:

function App() {
  const handleClick = props => {
    console.log(props);
  };

  const Option = props => {
    return (
      <div
        onClick={() => {
          if (props.data.isDisabled) {
            handleClick(props);
          }
        }}
      >
        <components.Option {...props} />
      </div>
    );
  };

  return (
    <div className="App">
      <Select components={{ Option }} options={options} />
    </div>
  );
}

The options structure is the following one:

const options = [
  {
    label: "option 1",
    value: 1
  },
  {
    label: "option 2",
    value: 2
  },
  {
    label: "option 3",
    value: 3,
    isDisabled: true
  }
];

Here a live example.

Upvotes: 0

Sergio Belevskij
Sergio Belevskij

Reputation: 2957

Which lib of Select do you use?

Because it depends on your select library, this is not a full example. Try to convert your options and pass them to

  handleDisabledOptionClick = ({ event, option }) => {
    console.log('Option is disabled: ', { option })
  }

  const options = this.state.cityList.map((option) => {
    return (
      <option
        disabled={option.disabled}
        onClick={(event) => option.disabled && handleDisabledOptionClick({
          event,
          option,
        })}
      >
        {option.label}
      </option>
    )
  })

  <Select
    value={this.state.cityOptions}
    onChange={this.handleChange}
    styles={customStyles}
    placeholder="City"
    name="cityOptions"
    isSearchable={false}
    isOptionDisabled={(option) => option.disabled}
  >
    {options}
  </Select>

Upvotes: 1

Related Questions