Topic 31 of 54
Accessing DOM
Overview
React's declarative model means you rarely need to touch the DOM directly. However, there are 'escape hatches' for when you must interact with a raw HTML element (like focusing an input, playing an HTML5 video, or integrating with a non-React 3rd party library). `useRef` allows you to create a persistent reference to a DOM node.
Syntax
The `ref` prop is a special reserved prop in React. When the component mounts, React automatically assigns the physical DOM node to `inputRef.current`.
Focusing an Input on Mount
jsx
import { useRef, useEffect } from 'react';
function AutoFocusInput() {
// 1. Create the ref with an initial value of null
const inputRef = useRef(null);
useEffect(() => {
// 3. Access the raw DOM node via the .current property
// We do this inside useEffect because the node doesn't exist during the first render!
inputRef.current.focus();
}, []);
return (
<div>
{/* 2. Attach the ref to the JSX element */}
<input ref={inputRef} type="text" placeholder="I focus instantly!" />
</div>
);
}Common Pitfalls
- Trying to access `ref.current` during the render phase. It will be `null` because the JSX hasn't been turned into actual DOM yet. Always access it inside `useEffect` or an event handler.
Interview Tips
- Interviewers might ask how to integrate a vanilla JS charting library (like D3 or Chart.js) into React. The answer is always `useRef` to get the DOM node, and `useEffect` to initialize the library on that node.
Real-World Example
Controlling HTML5 Media elements which have imperative APIs (.play(), .pause()).
example
jsx
function VideoPlayer() {
const videoRef = useRef(null);
const handlePlay = () => videoRef.current.play();
const handlePause = () => videoRef.current.pause();
return (
<div>
<video ref={videoRef} src="/cat-video.mp4" width="400" />
<div>
<button onClick={handlePlay}>Play</button>
<button onClick={handlePause}>Pause</button>
</div>
</div>
);
}