Reputation: 7569
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?
Many thanks!
Upvotes: 4
Views: 11463
Reputation: 5529
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>
</>
);
}
Upvotes: 6