ref
Edit this pageref captures a rendered element or forwarded component ref.
Syntax
<div ref={value} />Value
- Type: variable binding or callback function
For DOM elements, variable refs are assigned during render and callback refs receive the element.
Behavior
- Refs are assigned during rendering before the element is connected to the DOM.
- A variable ref assigns the rendered element to the referenced variable.
- A callback ref is called with the rendered element. When
refcomes through a spread, functional refs are invoked from the spread handling path instead. - Component refs work only when the component uses or forwards the
refprop to an underlying element or child component.
Examples
Variable ref
let myDiv;
onMount(() => console.log(myDiv));
<div ref={myDiv} />;Callback ref
<div ref={(el) => console.log(el)} />Component ref
function MyComp(props) { return <div ref={props.ref} />;}
function App() { let myDiv; onMount(() => console.log(myDiv.clientWidth)); return <MyComp ref={myDiv} />;}