It is a common scenario where we need to retrieve the value of the check box to know whether it is checked or unchecked. Unlike the traditional javascript in React, you cannot directly access the DOM element.
Using ref we can directly access the DOM element to access & modify the data and the underlying DOM node or React component instance. We can also use the react values and modify the style attribute using the refs.
Create the component:
Let us first start by creating the checkbox component.
In the below example, we created a simple checkbox component in React using the functional component called Checkbox
that accepts a label and onChange prop.
import React from 'react';
const Checkbox = ({ label, onChange }) => {
return (
<div>
<label>
<input type="checkbox" onChange={onChange} />
{label}
</label>
</div>
);
};
export default Checkbox;
Attach ref to the component
Now let us see how to add the ref to the checkbox component and get the value of a checkbox using Ref.
To achieve this, we will use the useRef
hook provided by React. The useRef
hook allows us to create a mutable variable that persists across re-renders.
Modify the checkbox component as shown below.
import React, { useRef } from 'react';
const Checkbox = ({ label }) => {
const checkboxRef = useRef(null);
const handleCheckboxChange = () => {
const isChecked = checkboxRef.current.checked;
console.log('Checkbox value:', isChecked);
};
return (
<div>
<label>
<input type="checkbox" onChange={handleCheckboxChange} ref={checkboxRef} />
{label}
</label>
</div>
);
};
export default Checkbox;
In the above-modified example, we create a ref called checkboxRef
using the useRef
hook and initialized it with null
. We access the checkbox value using the checkboxRef.current.checked
in the handleCheckboxChange
function.
The checkboxRef.current
gives us the reference to the DOM node of the checkbox and checked is the property which represents the current state of the checkbox.
By adding the ref={checkboxRef}
prop to the <input>
element, we establish a connection between the ref and the checkbox component. Using this we can access the checkbox value when the onChange
event occurs.