Manipulating the DOM with Refs
React automatically updates the DOM to match your render output, so your components wonât often need to manipulate it. However, sometimes you might need access to the DOM elements managed by Reactâfor example, to focus a node, scroll to it, or measure its size and position. There is no built-in way to do those things in React, so you will need a ref to the DOM node.
You will learn
- How to access a DOM node managed by React with the
ref
attribute - How the
ref
JSX attribute relates to theuseRef
Hook - How to access another componentâs DOM node
- In which cases itâs safe to modify the DOM managed by React
Getting a ref to the node
To access a DOM node managed by React, first, import the useRef
Hook:
import { useRef } from 'react';
Then, use it to declare a ref inside your component:
const myRef = useRef(null);
Finally, pass it to the DOM node as the ref
attribute:
<div ref={myRef}>
The useRef
Hook returns an object with a single property called current
. Initially, myRef.current
will be null
. When React creates a DOM node for this <div>
, React will put a reference to this node into myRef.current
. You can then access this DOM node from your event handlers and use the built-in browser APIs defined on it.
// You can use any browser APIs, for example:
myRef.current.scrollIntoView();
Example: Focusing a text input
In this example, clicking the button will focus the input:
import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }
To implement this:
- Declare
inputRef
with theuseRef
Hook. - Pass it as
<input ref={inputRef}>
. This tells React to put this<input>
âs DOM node intoinputRef.current
. - In the
handleClick
function, read the input DOM node frominputRef.current
and callfocus()
on it withinputRef.current.focus()
. - Pass the
handleClick
event handler to<button>
withonClick
.
While DOM manipulation is the most common use case for refs, the useRef
Hook can be used for storing other things outside React, like timer IDs. Similarly to state, refs remain between renders. Refs are like state variables that donât trigger re-renders when you set them. For an introduction to refs, see Referencing Values with Refs.
Example: Scrolling to an element
You can have more than a single ref in a component. In this example, there is a carousel of three images. Each button centers an image by calling the browser scrollIntoView()
method the corresponding DOM node:
import { useRef } from 'react'; export default function CatFriends() { const firstCatRef = useRef(null); const secondCatRef = useRef(null); const thirdCatRef = useRef(null); function handleScrollToFirstCat() { firstCatRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' }); } function handleScrollToSecondCat() { secondCatRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' }); } function handleScrollToThirdCat() { thirdCatRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' }); } return ( <> <nav> <button onClick={handleScrollToFirstCat}> Tom </button> <button onClick={handleScrollToSecondCat}> Maru </button> <button onClick={handleScrollToThirdCat}> Jellylorum </button> </nav> <div> <ul> <li> <img src="https://placekitten.com/g/200/200" alt="Tom" ref={firstCatRef} /> </li> <li> <img src="https://placekitten.com/g/300/200" alt="Maru" ref={secondCatRef} /> </li> <li> <img src="https://placekitten.com/g/250/200" alt="Jellylorum" ref={thirdCatRef} /> </li> </ul> </div> </> ); }
Deep Dive
How to manage a list of refs using a ref callback
How to manage a list of refs using a ref callback
In the above examples, there is a predefined number of refs. However, sometimes you might need a ref to each item in the list, and you donât know how many you will have. Something like this wouldnât work:
<ul>
{items.map((item) => {
// Doesn't work!
const ref = useRef(null);
return <li ref={ref} />;
})}
</ul>
This is because Hooks must only be called at the top-level of your component. You canât call useRef
in a loop, in a condition, or inside a map()
call.
One possible way around this is to get a single ref to their parent element, and then use DOM manipulation methods like querySelectorAll
to âfindâ the individual child nodes from it. However, this is brittle and can break if your DOM structure changes.
Another solution is to pass a function to the ref
attribute. This is called a âref callbackâ. React will call your ref callback with the DOM node when itâs time to set the ref, and with null
when itâs time to clear it. This lets you maintain your own array or a Map, and access any ref by its index or some kind of ID.
This example shows how you can use this approach to scroll to an arbitrary node in a long list:
import { useRef } from 'react'; export default function CatFriends() { const itemsRef = useRef(null); function scrollToId(itemId) { const map = getMap(); const node = map.get(itemId); node.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' }); } function getMap() { if (!itemsRef.current) { // Initialize the Map on first usage. itemsRef.current = new Map(); } return itemsRef.current; } return ( <> <nav> <button onClick={() => scrollToId(0)}> Tom </button> <button onClick={() => scrollToId(5)}> Maru </button> <button onClick={() => scrollToId(9)}> Jellylorum </button> </nav> <div> <ul> {catList.map(cat => ( <li key={cat.id} ref={(node) => { const map = getMap(); if (node) { map.set(cat.id, node); } else { map.delete(cat.id); } }} > <img src={cat.imageUrl} alt={'Cat #' + cat.id} /> </li> ))} </ul> </div> </> ); } const catList = []; for (let i = 0; i < 10; i++) { catList.push({ id: i, imageUrl: 'https://placekitten.com/250/200?image=' + i }); }
In this example, itemsRef
doesnât hold a single DOM node. Instead, it holds a Map from item ID to a DOM node. (Refs can hold any values!) The ref
callback on every list item takes care to update the Map:
<li
key={cat.id}
ref={node => {
const map = getMap();
if (node) {
// Add to the Map
map.set(cat.id, node);
} else {
// Remove from the Map
map.delete(cat.id);
}
}}
>
This lets you read individual DOM nodes from the Map later.
Accessing another componentâs DOM nodes
When you put a ref on a built-in component that outputs a browser element like <input />
, React will set that refâs current
property to the corresponding DOM node (such as the actual <input />
in the browser).
However, if you try to put a ref on your own component, like <MyInput />
, by default you will get null
. Here is an example demonstrating it. Notice how clicking the button does not focus the input:
import { useRef } from 'react'; function MyInput(props) { return <input {...props} />; } export default function MyForm() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <MyInput ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }
To help you notice the issue, React also prints an error to the console:
This happens because by default React does not let a component access the DOM nodes of other components. Not even for its own children! This is intentional. Refs are an escape hatch that should be used sparingly. Manually manipulating another componentâs DOM nodes makes your code even more fragile.
Instead, components that want to expose their DOM nodes have to opt in to that behavior. A component can specify that it âforwardsâ its ref to one of its children. Hereâs how MyInput
can use the forwardRef
API:
const MyInput = forwardRef((props, ref) => {
return <input {...props} ref={ref} />;
});
This is how it works:
<MyInput ref={inputRef} />
tells React to put the corresponding DOM node intoinputRef.current
. However, itâs up to theMyInput
component to opt into thatâby default, it doesnât.- The
MyInput
component is declared usingforwardRef
. This opts it into receiving theinputRef
from above as the secondref
argument which is declared afterprops
. MyInput
itself passes theref
it received to the<input>
inside of it.
Now clicking the button to focus the input works:
import { forwardRef, useRef } from 'react'; const MyInput = forwardRef((props, ref) => { return <input {...props} ref={ref} />; }); export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <MyInput ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }
In design systems, it is a common pattern for low-level components like buttons, inputs, and so on, to forward their refs to their DOM nodes. On the other hand, high-level components like forms, lists, or page sections usually wonât expose their DOM nodes to avoid accidental dependencies on the DOM structure.
Deep Dive
Exposing a subset of the API with an imperative handle
Exposing a subset of the API with an imperative handle
In the above example, MyInput
exposes the original DOM input element. This lets the parent component call focus()
on it. However, this also lets the parent component do something elseâfor example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with useImperativeHandle
:
import { forwardRef, useRef, useImperativeHandle } from 'react'; const MyInput = forwardRef((props, ref) => { const realInputRef = useRef(null); useImperativeHandle(ref, () => ({ // Only expose focus and nothing else focus() { realInputRef.current.focus(); }, })); return <input {...props} ref={realInputRef} />; }); export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <MyInput ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }
Here, realInputRef
inside MyInput
holds the actual input DOM node. However, useImperativeHandle
instructs React to provide your own special object as the value of a ref to the parent component. So inputRef.current
inside the Form
component will only have the focus
method. In this case, the ref âhandleâ is not the DOM node, but the custom object you create inside useImperativeHandle
call.
When React attaches the refs
In React, every update is split in two phases:
- During render, React calls your components to figure out what should be on the screen.
- During commit, React applies changes to the DOM.
In general, you donât want to access refs during rendering. That goes for refs holding DOM nodes as well. During the first render, the DOM nodes have not yet been created, so ref.current
will be null
. And during the rendering of updates, the DOM nodes havenât been updated yet. So itâs too early to read them.
React sets ref.current
during the commit. Before updating the DOM, React sets the affected ref.current
values to null
. After updating the DOM, React immediately sets them to the corresponding DOM nodes.
Usually, you will access refs from event handlers. If you want to do something with a ref, but there is no particular event to do it in, you might need an Effect. We will discuss effects on the next pages.
Deep Dive
Flushing state updates synchronously with flushSync
Flushing state updates synchronously with flushSync
Consider code like this, which adds a new todo and scrolls the screen down to the last child of the list. Notice how, for some reason, it always scrolls to the todo that was just before the last added one:
import { useState, useRef } from 'react'; export default function TodoList() { const listRef = useRef(null); const [text, setText] = useState(''); const [todos, setTodos] = useState( initialTodos ); function handleAdd() { const newTodo = { id: nextId++, text: text }; setText(''); setTodos([ ...todos, newTodo]); listRef.current.lastChild.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } return ( <> <button onClick={handleAdd}> Add </button> <input value={text} onChange={e => setText(e.target.value)} /> <ul ref={listRef}> {todos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> </> ); } let nextId = 0; let initialTodos = []; for (let i = 0; i < 20; i++) { initialTodos.push({ id: nextId++, text: 'Todo #' + (i + 1) }); }
The issue is with these two lines:
setTodos([ ...todos, newTodo]);
listRef.current.lastChild.scrollIntoView();
In React, state updates are queued. Usually, this is what you want. However, here it causes a problem because setTodos
does not immediately update the DOM. So the time you scroll the list to its last element, the todo has not yet been added. This is why scrolling always âlags behindâ by one item.
To fix this issue, you can force React to update (âflushâ) the DOM synchronously. To do this, import flushSync
from react-dom
and wrap the state update into a flushSync
call:
flushSync(() => {
setTodos([ ...todos, newTodo]);
});
listRef.current.lastChild.scrollIntoView();
This will instruct React to update the DOM synchronously right after the code wrapped in flushSync
executes. As a result, the last todo will already be in the DOM by the time you try to scroll to it:
import { useState, useRef } from 'react'; import { flushSync } from 'react-dom'; export default function TodoList() { const listRef = useRef(null); const [text, setText] = useState(''); const [todos, setTodos] = useState( initialTodos ); function handleAdd() { const newTodo = { id: nextId++, text: text }; flushSync(() => { setText(''); setTodos([ ...todos, newTodo]); }); listRef.current.lastChild.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } return ( <> <button onClick={handleAdd}> Add </button> <input value={text} onChange={e => setText(e.target.value)} /> <ul ref={listRef}> {todos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> </> ); } let nextId = 0; let initialTodos = []; for (let i = 0; i < 20; i++) { initialTodos.push({ id: nextId++, text: 'Todo #' + (i + 1) }); }
Best practices for DOM manipulation with refs
Refs are an escape hatch. You should only use them when you have to âstep outside Reactâ. Common examples of this include managing focus, scroll position, or calling browser APIs that React does not expose.
If you stick to non-destructive actions like focusing and scrolling, you shouldnât encounter any problems. However, if you try to modify the DOM manually, you can risk conflicting with the changes React is making.
To illustrate this problem, this example includes a welcome message and two buttons. The first button toggles its presence using conditional rendering and state, as you would usually do in React. The second button uses the remove()
DOM API to forcefully remove it from the DOM outside of Reactâs control.
Try pressing âToggle with setStateâ a few times. The message should disappear and appear again. Then press âRemove from the DOMâ. This will forcefully remove it. Finally, press âToggle with setStateâ:
import {useState, useRef} from 'react'; export default function Counter() { const [show, setShow] = useState(true); const ref = useRef(null); return ( <div> <button onClick={() => { setShow(!show); }}> Toggle with setState </button> <button onClick={() => { ref.current.remove(); }}> Remove from the DOM </button> {show && <p ref={ref}>Hello world</p>} </div> ); }
After youâve manually removed the DOM element, trying to use setState
to show it again will lead to a crash. This is because youâve changed the DOM, and React doesnât know how to continue managing it correctly.
Avoid changing DOM nodes managed by React. Modifying, adding children to, or removing children from elements that are managed by React can lead to inconsistent visual results or crashes like above.
However, this doesnât mean that you canât do it at all. It requires caution. You can safely modify parts of the DOM that React has no reason to update. For example, if some <div>
is always empty in the JSX, React wonât have a reason to touch its children list. Therefore, it is safe to manually add or remove elements there.
Recap
- Refs are a generic concept, but most often youâll use them to hold DOM elements.
- You instruct React to put a DOM node into
myRef.current
by passing<div ref={myRef}>
. - Usually, you will use refs for non-destructive actions like focusing, scrolling, or measuring DOM elements.
- A component doesnât expose its DOM nodes by default. You can opt into exposing a DOM node by using
forwardRef
and passing the secondref
argument down to a specific node. - Avoid changing DOM nodes managed by React.
- If you do modify DOM nodes managed by React, modify parts that React has no reason to update.
Challenge 1 of 4: Play and pause the video
In this example, the button toggles a state variable to switch between a playing and a paused state. However, in order to actually play or pause the video, toggling state is not enough. You also need to call play()
and pause()
on the DOM element for the <video>
. Add a ref to it, and make the button work.
import { useState, useRef } from 'react'; export default function VideoPlayer() { const [isPlaying, setIsPlaying] = useState(false); function handleClick() { const nextIsPlaying = !isPlaying; setIsPlaying(nextIsPlaying); } return ( <> <button onClick={handleClick}> {isPlaying ? 'Pause' : 'Play'} </button> <video width="250"> <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" type="video/mp4" /> </video> </> ) }
For an extra challenge, keep the âPlayâ button in sync with whether the video is playing even if the user right-clicks the video and plays it using the built-in browser media controls. You might want to listen to onPlay
and onPause
on the video to do that.