How to Access DOM Element Using useRef in React
In React, you can access a DOM element by creating a
ref using useRef and attaching it to the element with the ref attribute. Then, access the DOM node via ref.current inside your component.Syntax
To access a DOM element, first create a reference with const ref = useRef(null). Attach this ref to a JSX element using the ref attribute. The actual DOM element is available as ref.current.
- useRef(null): Initializes the ref with
null. - ref attribute: Connects the ref to the DOM element.
- ref.current: Holds the DOM element after rendering.
jsx
import React, { useRef } from 'react'; function MyComponent() { const myElementRef = useRef(null); // Access DOM element with myElementRef.current return <div ref={myElementRef}>Hello</div>; }
Example
This example shows a button that focuses an input field when clicked. The input is accessed using useRef and ref.current.focus().
jsx
import React, { useRef } from 'react'; export default function FocusInput() { const inputRef = useRef(null); const handleFocus = () => { if (inputRef.current) { inputRef.current.focus(); } }; return ( <div> <input ref={inputRef} type="text" placeholder="Click button to focus" /> <button onClick={handleFocus}>Focus Input</button> </div> ); }
Output
An input box and a button labeled 'Focus Input'. Clicking the button moves the cursor focus inside the input box.
Common Pitfalls
Common mistakes when using useRef to access DOM elements include:
- Not attaching the
refto a DOM element, soref.currentstaysnull. - Trying to access
ref.currentbefore the component has rendered. - Mutating DOM directly instead of using React state for UI changes.
Always check if ref.current is not null before using it.
jsx
import React, { useRef, useEffect } from 'react'; function WrongExample() { const ref = useRef(null); // This will cause error because ref.current is null initially // console.log(ref.current.value); return <div>Missing ref on input</div>; } function CorrectExample() { const ref = useRef(null); useEffect(() => { if (ref.current) { console.log(ref.current.value); // Safe to access } }, []); return <input ref={ref} defaultValue="Hello" />; }
Quick Reference
- useRef(null): Create a ref object.
- ref attribute: Attach ref to JSX element.
- ref.current: Access the DOM element.
- Check
ref.currentis not null before use. - Use refs for direct DOM access, not for UI state.
Key Takeaways
Create a ref with useRef(null) and attach it to a DOM element using the ref attribute.
Access the DOM element via ref.current after the component renders.
Always check if ref.current is not null before using it to avoid errors.
Use refs for direct DOM manipulation only when necessary, not for managing UI state.
Calling methods like focus() on ref.current lets you control the element programmatically.