Sub topic 5
Focusing, scrolling, and measuring
This chapter assumes you know useState, basic useEffect, JSX, and DOM ideas such as focus, scroll position, and element size.
Why these actions need a ref
React describes what the screen should look like. Some browser actions have no prop, though. You can't write focused={true} or scrolledIntoView. These actions are methods on the DOM node itself, such as focus() and scrollIntoView(). A ref gives you that node.
Focusing an input
import { useRef } from 'react';
export function SearchBox() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} placeholder="Search" />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</>
);
}The ref starts as null. After React puts the <input> on the screen, it sets inputRef.current to that node. The click handler runs later, so current is already set.
Scrolling an element into view
Use scrollIntoView on a node you hold a ref to. The block: 'nearest' option scrolls only as far as needed.
import { useRef } from 'react';
export function Notes() {
const endRef = useRef(null);
return (
<>
<button
onClick={() =>
endRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}
>
Jump to the end
</button>
<ul style={{ height: 80, overflow: 'auto' }}>
{Array.from({ length: 20 }, (_, i) => (
<li key={i}>Note {i + 1}</li>
))}
<li ref={endRef}>The end</li>
</ul>
</>
);
}Measuring an element
Layout values such as width and height exist only in the browser. Read them from the node with getBoundingClientRect().
import { useRef, useState } from 'react';
export function MeasuredBox() {
const boxRef = useRef(null);
const [width, setWidth] = useState(null);
function measure() {
const rect = boxRef.current.getBoundingClientRect();
setWidth(Math.round(rect.width));
}
return (
<>
<div ref={boxRef} style={{ width: '50%', background: '#eef' }}>
Resize the window, then measure me.
</div>
<button onClick={measure}>Measure</button>
<p>Width: {width === null ? 'not measured' : `${width}px`}</p>
</>
);
}The node lives in a ref, but the measured width is shown on screen, so it goes in state. The ref lets you read the number, and state lets React display it.
Where it is safe to use the node
- Event handlers and effects run after the commit, so
ref.currentis set. - Rendering runs before the commit. On the first render
ref.currentisnull, soinputRef.current.focus()in the component body throws an error. - To act when a component appears, such as focusing an input on mount, use
useEffect(() => { inputRef.current.focus(); }, []). - If you need a measurement before the browser paints, for example to position a tooltip without flicker, read it in
useLayoutEffect.
Common mistakes
- Calling
ref.current.focus()during render. Move it into a handler or effect. - Forgetting that
currentcan benull, for example when the element is conditionally rendered. Useref.current?.focus()when the element may be absent. - Using a stale measurement. A size read once does not update when the window resizes. Measure again when you need it, or in an effect that responds to changes.
- Changing the DOM by hand, such as editing
textContent, on nodes React manages. Limit refs to actions like focus, scroll, and measurement, and leave the content to React.
Exercise
A component calls listRef.current.scrollIntoView() directly in its function body and crashes on the first render with "Cannot read properties of null". Why does it crash, and where should the call go?
Show answer
During the first render React has not yet created the DOM node, so listRef.current is still null. Move the call into an event handler or into a useEffect (or useLayoutEffect if it must run before paint), because those run after React has set the ref.
Exercise
In MeasuredBox, why is the width stored in state instead of in another ref?
Show answer
The width is displayed on screen. Changing a ref does not trigger a re-render, so the paragraph would keep showing the old value. State makes React re-render with the new width.