'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.
- How to access a DOM node managed by React with the
refattribute - How the
refJSX attribute relates to theuseRefHook - 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 your ref as the ref attribute to the JSX tag for which you want to get the DOM node:
<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
inputRefwith theuseRefHook. - Pass it as
<input ref={inputRef}>. This tells React to put this<input>'s DOM node intoinputRef.current. - In the
handleClickfunction, read the input DOM node frominputRef.currentand callfocus()on it withinputRef.current.focus(). - Pass the
handleClickevent 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. Read about refs in 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 on 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}>
Neo
</button>
<button onClick={handleScrollToSecondCat}>
Millie
</button>
<button onClick={handleScrollToThirdCat}>
Bella
</button>
</nav>
<div>
<ul>
<li>
<img
src="/uploads/projects/react-dev-guide/202611/18e72a8930b6502b.png"
alt="Neo"
ref={firstCatRef}
/>
</li>
<li>
<img
src="/uploads/projects/react-dev-guide/202611/18e72a89928d68de.png"
alt="Millie"
ref={secondCatRef}
/>
</li>
<li>
<img
src="/uploads/projects/react-dev-guide/202611/18e72a89f509bfdb.png"
alt="Bella"
ref={thirdCatRef}
/>
</li>
</ul>
</div>
</>
);
}
div {
width: 100%;
overflow: hidden;
}
nav {
text-align: center;
}
button {
margin: .25rem;
}
ul,
li {
list-style: none;
white-space: nowrap;
}
li {
display: inline;
padding: 0.5rem;
}
[!INFO]
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
useRefin a loop, in a condition, or inside amap()call.One possible way around this is to get a single ref to their parent element, and then use DOM manipulation methods like
querySelectorAllto "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
refattribute. This is called arefcallback. React will call your ref callback with the DOM node when it's time to set the ref, and call the cleanup function returned from the callback 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, useState } from "react";
export default function CatFriends() {
const itemsRef = useRef(null);
const [catList, setCatList] = useState(setupCatList);
function scrollToCat(cat) {
const map = getMap();
const node = map.get(cat);
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={() => scrollToCat(catList[0])}>Neo</button>
<button onClick={() => scrollToCat(catList[5])}>Millie</button>
<button onClick={() => scrollToCat(catList[8])}>Bella</button>
</nav>
<div>
<ul>
{catList.map((cat) => (
<li
key={cat.id}
ref={(node) => {
const map = getMap();
map.set(cat, node);
return () => {
map.delete(cat);
};
}}
>
<img src={cat.imageUrl} />
</li>
))}
</ul>
</div>
</>
);
}
function setupCatList() {
const catCount = 10;
const catList = new Array(catCount)
for (let i = 0; i < catCount; i++) {
let imageUrl = '';
if (i < 5) {
imageUrl = "https://placecats.com/neo/320/240";
} else if (i < 8) {
imageUrl = "https://placecats.com/millie/320/240";
} else {
imageUrl = "https://placecats.com/bella/320/240";
}
catList[i] = {
id: i,
imageUrl,
};
}
return catList;
}
div {
width: 100%;
overflow: hidden;
}
nav {
text-align: center;
}
button {
margin: .25rem;
}
ul,
li {
list-style: none;
white-space: nowrap;
}
li {
display: inline;
padding: 0.5rem;
}
In this example,
itemsRefdoesn't hold a single DOM node. Instead, it holds a Map from item ID to a DOM node. (Refs can hold any values!) Therefcallback on every list item takes care to update the Map:
<li
key={cat.id}
ref={node => {
const map = getMap();
// Add to the Map
map.set(cat, node);
return () => {
// Remove from the Map
map.delete(cat);
};
}}
>
This lets you read individual DOM nodes from the Map later.
[!NOTE]
When Strict Mode is enabled, ref callbacks will run twice in development.
Read more about how this helps find bugs in callback refs.
Accessing another component's DOM nodes
[!WARNING] Refs are an escape hatch. Manually manipulating another component's DOM nodes can make your code fragile.
You can pass refs from parent component to child components just like any other prop.
```js {3-4,9} import { useRef } from 'react';
function MyInput({ ref }) { return ; }
function MyForm() {
const inputRef = useRef(null);
return
In the above example, a ref is created in the parent component, `MyForm`, and is passed to the child component, `MyInput`. `MyInput` then passes the ref to `<input>`. Because `<input>` is a [built-in component](/reference/react-dom/components/common) React sets the `.current` property of the ref to the `<input>` DOM element.
The `inputRef` created in `MyForm` now points to the `<input>` DOM element returned by `MyInput`. A click handler created in `MyForm` can access `inputRef` and call `focus()` to set the focus on `<input>`.
```js
import { useRef } from 'react';
function MyInput({ ref }) {
return <input ref={ref} />;
}
export default function MyForm() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<>
<MyInput ref={inputRef} />
<button onClick={handleClick}>
Focus the input
</button>
</>
);
}
[!INFO]
Exposing a subset of the API with an imperative handle
In the above example, the ref passed to
MyInputis passed on to the original DOM input element. This lets the parent component callfocus()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 withuseImperativeHandle:
import { useRef, useImperativeHandle } from "react";
function MyInput({ ref }) {
const realInputRef = useRef(null);
useImperativeHandle(ref, () => ({
// Only expose focus and nothing else
focus() {
realInputRef.current.focus();
},
}));
return <input 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,
realInputRefinsideMyInputholds the actual input DOM node. However,useImperativeHandleinstructs React to provide your own special object as the value of a ref to the parent component. SoinputRef.currentinside theFormcomponent will only have thefocusmethod. In this case, the ref "handle" is not the DOM node, but the custom object you create insideuseImperativeHandlecall.
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.
[!INFO]
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
setTodosdoes 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
flushSyncfromreact-domand wrap the state update into aflushSynccall:
flushSync(() => {
setTodos([ ...todos, newTodo]);
});
listRef.current.lastChild.scrollIntoView();
This will instruct React to update the DOM synchronously right after the code wrapped in
flushSyncexecutes. As a result, the last todo will already be in the DOM by the time you try to scroll to it:
