Skip to content

Refs to DOM Elements

The Course
•
20 min study

React builds the DOM for you, so you rarely touch it. A few things can only be done on the real element, though: focusing a field, scrolling to something, measuring its size, playing a video. For those, put a ref on the element:

JSX
const inputRef = useRef(null);
// ...
<input ref={inputRef} />

After React creates the <input>, it sets inputRef.current to that DOM element. When the element is removed, React sets it back to null.

Focus a field React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useRef, useState } from "react"; import TextInput from "./TextInput.jsx"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards); const [title, setTitle] = useState(""); const inputRef = useRef(null); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; setCards([...cards, { id: Date.now(), title: title.trim(), column: "todo", minutes: 15 }]); setTitle(""); } return ( <main> <h1>Study Board</h1> <form className="toolbar" onSubmit={handleSubmit}> <TextInput ref={inputRef} label="New card" value={title} onChange={setTitle} /> <button type="submit">Add</button> <button type="button" onClick={() => inputRef.current.focus()}>Focus the field</button> </form> <ul className="cards"> {cards.map((card) => ( <li key={card.id} className="card">{card.title}</li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; // In React 19, ref is an ordinary prop: pass it on to the element. export default function TextInput({ ref, label, value, onChange }) { return ( <input ref={ref} aria-label={label} placeholder={label} value={value} onChange={(e) => onChange(e.target.value)} /> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Press Focus the field. Its handler calls inputRef.current.focus(), the browser's own focus() method on the real <input>.

Refs through your own components

The input here is inside TextInput, a component of your own. In React 19, ref is an ordinary prop for function components: App passes ref={inputRef}, and TextInput hands it on to the <input>:

JSX
export default function TextInput({ ref, label, value, onChange }) {
  return (
    <input ref={ref} aria-label={label} placeholder={label} value={value}
      onChange={(e) => onChange(e.target.value)} />
  );
}

Before React 19, a component had to be wrapped in forwardRef to receive a ref. You'll see that in older code and libraries; it does the same job.

Predict: focus after adding

Type a title and press Add with the mouse. Where is the keyboard focus afterwards?

Check your prediction

On the Add button, because that's what you clicked. To add another card, you have to click back into the field first. Adding several cards in a row is much smoother if focus returns to the field.

Don't fight React over the DOM

Refs let you call the DOM's methods, but React still owns the DOM's contents. Focusing, scrolling and measuring are safe. Changing an element's text, removing it, or adding children yourself is not: React doesn't know you did it, and its next update can undo your change or crash. If you want something different on screen, change state.

Your turn

Exercise

Back to the field

After a card is added, put the focus back in the New card field, so you can type the next one straight away.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useRef, useState } from "react"; import TextInput from "./TextInput.jsx"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards); const [title, setTitle] = useState(""); const inputRef = useRef(null); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; setCards([...cards, { id: Date.now(), title: title.trim(), column: "todo", minutes: 15 }]); setTitle(""); } return ( <main> <h1>Study Board</h1> <form className="toolbar" onSubmit={handleSubmit}> <TextInput ref={inputRef} label="New card" value={title} onChange={setTitle} /> <button type="submit">Add</button> <button type="button" onClick={() => inputRef.current.focus()}>Focus the field</button> </form> <ul className="cards"> {cards.map((card) => ( <li key={card.id} className="card">{card.title}</li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; // In React 19, ref is an ordinary prop: pass it on to the element. export default function TextInput({ ref, label, value, onChange }) { return ( <input ref={ref} aria-label={label} placeholder={label} value={value} onChange={(e) => onChange(e.target.value)} /> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Focus is an imperative DOM action. The input already exists, so the submit handler can focus it directly.

Hint 2: a first step

At the end of handleSubmit, after the state updates, call the same method the Focus the field button calls.

Show one solution
JavaScript
function handleSubmit(event) {
  event.preventDefault();
  if (title.trim() === "") return;
  setCards([...cards, { id: Date.now(), title: title.trim(), column: "todo", minutes: 15 }]);
  setTitle("");
  inputRef.current.focus();
}

Pressing Enter in the field also submits the form. Now you can type a title, press Enter, and type the next one, without touching the mouse.

Was this article helpful?

Your response is saved on this device.