Borislav Hadzhiev
Sat Apr 30 2022·2 min read
Photo by Dane Wetton
Use the target.checked
property on the event
object to check if a checkbox
is checked in React, e.g. if (event.target.checked) {}
. Alternatively, store
the checked value in a state variable or access the ref.current.checked
property for uncontrolled checkboxes.
import {useState} from 'react'; export default function App() { const [isSubscribed, setIsSubscribed] = useState(false); const handleChange = event => { if (event.target.checked) { console.log('✅ Checkbox is checked'); } else { console.log('⛔️ Checkbox is NOT checked'); } setIsSubscribed(current => !current); }; return ( <div> <label htmlFor="subscribe"> <input type="checkbox" value={isSubscribed} onChange={handleChange} id="subscribe" name="subscribe" /> Subscribe </label> </div> ); }
The target
property on the event
object refers to the input element, so we
can access its checked
value as event.target.checked
.
setIsSubscribed
because the function is guaranteed to be called with the current (most up to date) value for the isSubscribed
boolean.This is useful when we need to calculate the next state based on the current state.
To check if an uncontrolled checkbox is checked access the current.checked
property on the ref
object.
import {useRef} from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { if (ref.current.checked) { console.log('✅ Checkbox is checked'); } else { console.log('⛔️ Checkbox is NOT checked'); } }; return ( <div> <label htmlFor="subscribe"> <input ref={ref} type="checkbox" id="subscribe" name="subscribe" /> Subscribe </label> <br /> <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 handleClick
function is invoked and
checks if the checkbox is checked.
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.