ref directive gives you access to a rendered DOM element. It can be used with a Ref object created by createRef(), or with a callback function. Place ref(...) in an element binding (not a child position) to receive the element when it is connected to the DOM.
Import
Functions and types
createRef
Ref container. The element is accessible via .value after the component renders.
ref
Types
Parameters
Either a
Ref object (created with createRef()) whose .value will be set to the element, or a callback function that will be called with the element when it is connected and with undefined when it is disconnected.Return type
DirectiveResult — an opaque value that renders as nothing in the DOM.
Lifecycle behavior
- When the element is connected to the DOM, the
Ref.valueis set or the callback is called with the element. - When the element is disconnected or removed,
Ref.valueis set toundefinedor the callback is called withundefined. - If a callback ref moves to a different element in a subsequent render, it is first called with
undefinedfor the old element, then called with the new element.
Example: using createRef()
Example: using a callback ref
When to use
- You need to call imperative DOM APIs (e.g.,
.focus(),.play(),.getContext()) on an element after it renders. - You need to measure an element’s dimensions after it is in the DOM.
When not to use
- To read element properties that are already reflected as attributes — use declarative bindings instead.
- As a replacement for reactive properties or state — refs do not trigger re-renders.