Sub topic 4
Getting a handle on a DOM element
This chapter assumes you know React function components and JSX, useState, and basic DOM ideas such as elements and focus. You should also know that useRef returns an object that persists between renders.
Why you need a handle
React normally updates the DOM for you, so you describe the UI and React makes the browser match it. Some tasks have no declarative form. Examples are focusing an input, scrolling an element into view, or measuring its size. These tasks need the actual DOM node, and a ref gives you access to it.
Attaching a ref with the ref attribute
You create a ref with useRef(null) and pass it to a JSX element through the ref attribute. React then stores the DOM node in ref.current.
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>
</>
);
}Here inputRef starts as { current: null }. After React creates the <input> and adds it to the page, it sets inputRef.current to that HTMLInputElement. When you click the button, the handler calls the browser's own focus() method on the node.
When current is set
The ref is not filled in while your component function runs. React fills it in during the commit phase, after it updates the DOM.
This timing gives three rules:
- During the first render,
ref.currentisnull. Reading properties from it there throws an error. - Event handlers run after the commit, so the node is available in them.
useEffectcallbacks also run after the commit, so they can use the node too.
If you render the element conditionally, ref.current is null whenever the element is absent. React resets it to null when the element unmounts.
import { useRef, useState } from 'react';
export function Toggle() {
const boxRef = useRef(null);
const [show, setShow] = useState(false);
function logWidth() {
if (boxRef.current === null) {
console.log('Box is not on the page');
return;
}
console.log(boxRef.current.offsetWidth);
}
return (
<>
<button onClick={() => setShow(!show)}>Toggle</button>
<button onClick={logWidth}>Log width</button>
{show && <div ref={boxRef}>Hello</div>}
</>
);
}The null check in logWidth handles the case where the <div> is not rendered.
What you get back
The value depends on the element type. A <div> gives an HTMLDivElement, an <input> gives an HTMLInputElement, and so on. You can use any standard browser API on it. A ref on a component you wrote does not give you a DOM node by default. Passing refs to child components is covered in a later chapter.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Reading `ref.current.value` in the render body | Throws on the first render because `current` is `null` | Read it in an event handler or effect |
| Forgetting to pass `ref` to the element | `current` stays `null` | Add `ref={myRef}` to the JSX |
| Assuming the node always exists | Throws when the element is conditionally removed | Check for `null` first |
| Using a ref to change what is displayed | The screen does not update, because refs do not trigger renders | Use state for anything shown on screen |
Exercise
A component renders <input ref={inputRef} /> and also runs console.log(inputRef.current.value) directly in its function body. What goes wrong on the first render, and where should the read move to?
Show answer
On the first render the DOM node does not exist yet, so inputRef.current is null and reading .value throws a TypeError. React only sets the ref after it commits the DOM. Move the read into an event handler or a useEffect callback, which run after the commit.