How to clear the selected value in React?
To clear the value of a checkbox in React, you can use any of the following methods:
- Set the state.
import React, { useState } from "react";
function MyComponent() {
const [selectedValue, setSelectedValue] = useState("");
const handleClearSelection = () => {
setSelectedValue("");
};
return (
<div>
<select value={selectedValue} onChange={(e) => setSelectedValue(e.target.value)}>
<option value="">-- Select --</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<button onClick={handleClearSelection}>Clear Selection</button>
</div>
);
}
- reference
- the value of the element
import React, { useRef } from "react";
function MyComponent() {
const selectRef = useRef(null);
const handleClearSelection = () => {
selectRef.current.value = "";
};
return (
<div>
<select ref={selectRef}>
<option value="">-- Select --</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<button onClick={handleClearSelection}>Clear Selection</button>
</div>
);
}
No matter which method you choose, you can clear the value in the checkbox by clicking the clear button.