Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we remove one of selected option in react-select programmatically?

Tags:

react-select

In react-select https://github.com/jedwatson/react-select , can we remove one of selected option in react-select programmatically?

E.g in the below screenshot I would like to unselectred programmatically?

enter image description here

Many thanks!

like image 946
iwan Avatar asked Nov 07 '25 22:11

iwan


1 Answers

You can save selected options in state and remove selected one by update new state, you can check here codeSandBox

import React, { useState } from "react";
import "./styles.css";
import Select from "react-select";

const options = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

export default function App() {
  const [selectedOption, setSelect] = useState(null);
  const handleChange = selectedOption => {
    setSelect(selectedOption);
  };
  const removeOption = e => {
    const newSelect = selectedOption.filter(
      item => item.value !== e.target.name
    );
    setSelect(newSelect);
  };
  return (
    <>
      <Select
        isMulti
        value={selectedOption}
        onChange={handleChange}
        options={options}
      />
      <button name="chocolate" onClick={removeOption}>
        Remove Chocolate
      </button>
      <button name="vanilla" onClick={removeOption}>
        Remove Vanilla
      </button>
      <button name="strawberry" onClick={removeOption}>
        Remove Strawberry
      </button>
    </>
  );
}
like image 200
iamhuynq Avatar answered Nov 09 '25 22:11

iamhuynq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!