Ref as a prop

ref를 prop으로 전달

In React 19, a function component can receive ref as a normal prop and attach it to a child node.

···
html
<div class="scene"><div class="chain"><span class="pill" id="parent">parent ref</span><span>→</span><span class="pill" id="child">child prop</span><span>→</span><span class="pill" id="dom">input DOM</span></div><div class="input" id="input">focus target <i></i></div><div class="label" id="note">ref.current.focus()</div></div>
css
.scene{width:min(94vw,800px);height:min(86vh,320px);position:relative;overflow:hidden;display:flex;flex-direction:column;justify-content:space-between;border:1px solid var(--line);border-radius:14px;background:var(--surface);padding:clamp(9px,2.4vmin,20px);font:500 clamp(15px,4vmin,18px)/1.3 var(--font-sans,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}.scene b,.scene strong{font-weight:700}.label{color:var(--muted)}.code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.pill{border:1px solid var(--line);border-radius:8px;padding:.4em .65em;background:var(--bg)}.active{border-color:var(--accent)!important;color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 10%,var(--surface))!important}.chain{display:flex;align-items:center;justify-content:space-between;gap:3px;margin:clamp(16px,6vmin,42px) 0}.chain .pill{text-align:center;min-width:25%;font-size:.85em}.input{margin:auto;border:1px solid var(--line);border-radius:7px;width:75%;padding:.7em;font-family:ui-monospace,monospace}.input i{display:none;width:2px;height:1em;background:var(--accent);vertical-align:-.16em;animation:blink .7s steps(1) infinite}@keyframes blink{50%{opacity:0}}.input.focus{border-color:var(--accent)}.input.focus i{display:inline-block}.label{text-align:center;margin-top:10px}
js
const ids=["parent","child","dom"];let n=0;function tick(){const s=n%3;ids.forEach((id,i)=>document.getElementById(id).classList.toggle("active",i===s));document.getElementById("input").classList.toggle("focus",s===2);document.getElementById("note").textContent=s===2?"input receives focus":"ref travels through props";n++}tick();setInterval(tick,850)

A parent ref can pass through a function component as a prop and attach to a real DOM node. Simple forwarding no longer needs a forwardRef wrapper.

The demo traces a ref through a child component to an input, where focus places the cursor. If the child does not pass the ref to the DOM, the parent cannot access that node.

When to use

Use it when a parent needs to focus or measure a child DOM node.

Open as page ↗