Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  69] [ 4]  / answers: 1 / hits: 8895  / 3 Years ago, thu, february 18, 2021, 12:00:00

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



  1. 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


More From » reactjs

 Answers
12

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>
);
}

Edit


[#1772] Saturday, February 13, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
Tue, Jan 28, 20, 00:00, 4 Years ago
;