React · Lesson 44 of 120
Refs to Elements
Focus an input.
Refs have another job. They can point at a real element on the page. Then you can call browser methods on it, like focus, or scroll into view.
- Point at an element
- Browser methods
- focus()
Focusing the search box
Input ref starts as null. Passing it to the input's ref prop makes React fill it in with the real input element. The button calls focus on it, and we type straight away. Run it.
App.jsxjsx
import { useRef } from "react";
export default function App() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} placeholder="Search bikes" />
<button id="f" onClick={() => inputRef.current.focus()}>Search</button>
</div>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#f"}, {"text": "trail"}]Use them sparingly
Refs to elements are an escape hatch. Use them for focus, scrolling, measuring, or third party widgets. For everything else, let state and JSX control the page.
| key | value |
|---|---|
| Focus | input.focus() |
| Scroll | scrollIntoView() |
| Measure | getBoundingClientRect() |
| Else | use state |
Summary
A ref on an element lets you call browser methods on it. Next, the effects quiz.
Key takeaways- ref={inputRef}
- inputRef.current
- focus()
Next up: Effects Quiz — test yourself