- Home
- /
- Tutorials
- /
- React Tutorial
- /
- forwardRef, Portals and Lazy Loading
Data and Errors
forwardRef, Portals and Lazy Loading
Three escape hatches for problems the normal tree cannot solve: reaching a child's DOM node, rendering outside your parent, and not shipping code until it is needed.
forwardRef: a ref into your own component
ref is not a prop. Putting one on your own component does nothing useful by default, because there is no DOM node for React to attach - the component has to say which node it means.
Focusing a child's input
jsx
const TextField = React.forwardRef(function TextField({ label }, ref) {
return (
<label>
{label}{" "}
<input ref={ref} placeholder="focus me from the parent" />
</label>
)
})
function Form() {
const inputRef = React.useRef(null)
return (
<div>
<TextField label="Name" ref={inputRef} />
<div style={{ marginTop: 8 }}>
<button onClick={() => inputRef.current.focus()}>Focus the field</button>
</div>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Form />)