How do you access the DOM element in React?
Learn how to access and manipulate DOM elements in React using useRef or callback refs.
intermediateAdvanced hooks and patternsreactuseRefdom manipulation
Published: 10/26/2025
Updated: 10/26/2025
Question
How do you access the DOM element in React?
Answer
Use refs. React provides the useRef() hook to directly reference DOM elements.
import { useRef, useEffect } from 'react';
function InputFocus() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} placeholder='Focus me on mount' />;
}
Here’s what happens:
useRef()creates a reference objectref={inputRef}binds it to an element- You can access it via
inputRef.current
Real-World Example
- Focusing input fields
- Controlling scroll
- Accessing canvas/video
- Integrating with third-party libraries
Quick Practice
Make an input field auto-focus on mount, and add a button to clear its value using useRef.
Summary
Refs give you a safe way to reach into the DOM — no need for query selectors.
Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions
Can I use document.querySelector?
You technically can, but it’s not the React way. Always prefer refs.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.