Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
You can get the value of a checkbox using a ref by accessing its
current.checked
property, e.g. ref.current.checked
. The current
property
on the ref stores a reference to the checkbox element, so to access it's value
we have to access current.checked
.
import {useRef} from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { // 👇️ get checkbox value with ref console.log(ref.current.checked); }; return ( <div> <input ref={ref} type="checkbox" id="subscribe" name="subscribe" /> <button onClick={handleClick}>Click</button> </div> ); }
The useRef() hook can be
passed an initial value as an argument. The hook returns a mutable ref object
whose .current
property is initialized to the passed argument.
current
property on the ref object to get access to the checkbox element on which we set the ref
prop.When we pass a ref prop to an element, e.g. <input ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
Every time you click on the button, the checked value of the checkbox will be logged to the console.
useRef
hook creates a plain JavaScript object, but gives you the same ref object on every render. In other words, it's pretty much a memoized object value with a .current
property.You can access any attribute on the checkbox element via ref.current
. If you
log the current
property on the ref
object, it's simply a reference to the
input
element.
If you need to set a default value for the checked
property on the checkbox,
use the defaultChecked
prop.
import {useRef} from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { // 👇️ get checkbox value with ref console.log(ref.current.checked); }; return ( <div> <input ref={ref} type="checkbox" id="subscribe" name="subscribe" defaultChecked={true} /> <button onClick={handleClick}>Click</button> </div> ); }
You can also use a controlled checkbox element by setting an onChange
prop on
the input
field and handling the event.
import {useState} from 'react'; export default function App() { const [isSubscribed, setIsSubscribed] = useState(false); const handleChange = event => { setIsSubscribed(event.target.checked); // 👇️ this is the checkbox itself console.log(event.target); // 👇️ this is the checked value of the field console.log(event.target.checked); }; return ( <div> <label htmlFor="subscribe">Subscribe</label> <input type="checkbox" id="subscribe" name="subscribe" onChange={handleChange} checked={isSubscribed} /> </div> ); }
The first thing we did is store the checked
input value in a state variable
called isSubscribed
.
onChange
prop on the checkbox, so every time its value is changed, the handleChange
function is invoked.We can access the checkbox via the target
property on the event
object.
Similarly, we can access its value via event.target.checked
.