Issue
I am using react-select
and I want to clear the selected value on button click without adding it to the options
property
I have tried
- Using state to manipulate the options property , but Apparently on calling
clearValue()
method, automatically pushes to the options array by default.
Problem
How do I tell react-select
to just clear the selected values and not add it in the options array anywhere ?
import React, { useRef } from "react";
import Select from "react-select";
export default function App() {
const selectInputRef = useRef();
const onClear = () => {
selectInputRef.current.select.clearValue();
};
return (
<div className="App">
<h1>Select Gender</h1>
<Select
isMulti
ref={selectInputRef}
options={[
{ value: "male", label: "Male" },
{ value: "female", label: "Female" }
]}
/>
<button onClick={onClear}>Clear Value</button>
</div>
);
}
Here is my CodeSandbox Link
Solution
You need to manage the state of the selected values and the options yourself and manipulate it accordingly:
export default function App() {
const [selected, setSelected] = useState([]);
const [options, setOptions] = useState([
{ value: "male", label: "Male" },
{ value: "female", label: "Female" }
]);
const handleClear = () => {
setOptions((currentOptions) => currentOptions.filter((currentOption) => !selected.includes(currentOption)));
setSelected([]);
};
return (
<div className="App">
<h1>Select Gender</h1>
<Select isMulti value={selected} options={options} onChange={setSelected} />
<button onClick={handleClear}>Clear Value</button>
</div>
);
}
Answered By - trixn
Answer Checked By - - Marie Seifert (ReactFix Admin)