Sometimes, we want to get the value of checkbox using a ref in React.
In this article, we’ll look at how to get the value of checkbox using a ref in React.
How to get the value of checkbox using a ref in React?
To get the value of checkbox using a ref in React, we can use the checked
property of the checkbox.
For instance, we write:
import React, { useRef } from "react";
export default function App() {
const checkboxRef = useRef();
const save = () => {
console.log(checkboxRef.current.checked);
};
return (
<div>
<div>
<label>
<input type="checkbox" ref={checkboxRef} /> Check me out
</label>
</div>
<button onClick={save}>Submit</button>
</div>
);
}
We create the checkboxRef
with the useRef
hook.
Then we assign the ref
prop to checkboxRef
to assign the checkbox as the value of checkboxRef.current
.
Next, we define the save
function to logged the checked value of the checkbox, which is stored in checkboxRef.current.checked
.
Finally, we assign the onClick
prop of the button to the save
function to run it when we click it.
Therefore, when we check or uncheck the checkbox and click Submit, we should see the checked value logged.
Conclusion
To get the value of checkbox using a ref in React, we can use the checked
property of the checkbox.