ref
Edit this pageRefs provide access to underlying DOM elements in your JSX. While you could assign an element to a variable directly, it is more optimal to leave components in the flow of JSX. Refs are assigned at render time but before the elements are connected to the DOM. They come in two flavors.
// variable assigned directly by reflet myDiv;
// use onSettled or createEffect to read after connected to the DOMonSettled(() => console.log(myDiv));
<div ref={myDiv} />
// Or, callback function (called before connected to the DOM)<div ref={el => console.log(el)} />Refs can also be used on Components. They still need to be attached on the other side.
function MyComp(props) { return <div ref={props.ref} />}
function App() { let myDiv onSettled(() => console.log(myDiv.clientWidth)) return <MyComp ref={myDiv} />}Ref directive factories
In Solid 2.0, ref replaces the removed use:* directive syntax. A ref directive factory is a function that accepts options and returns a callback that receives the element. This follows a two-phase pattern:
- Owned setup phase: The factory function runs inside the component's reactive owner context. Create signals, effects, and register cleanup here.
- Unowned apply phase: The returned callback receives the DOM element and applies the behavior.
function tooltip(text: string) { // Phase 1: Owned setup - runs in component's reactive context onCleanup(() => { /* cleanup logic */ });
// Phase 2: Unowned apply - receives the DOM element return (el: HTMLElement) => { // attach tooltip to el };}
<div ref={tooltip("Hello world")} />Array composition
You can compose multiple ref callbacks and directive factories on a single element using an array:
function draggable(opts: { axis: "x" | "y" | "both" }) { return (el: HTMLElement) => { // make el draggable };}
function tooltip(text: string) { return (el: HTMLElement) => { // attach tooltip to el };}
// Combine a variable ref with multiple directive factorieslet myDiv;<div ref={[myDiv, tooltip("Drag me"), draggable({ axis: "x" })]} />Each entry in the array is called in order with the DOM element. You can mix variable assignments, callbacks, and directive factory results.
Migration from use:*
If you previously used use: directives, convert them to ref directive factories:
// Solid 1.x<div use:tooltip={"Hello"} use:draggable={{ axis: "x" }} />
// Solid 2.0<div ref={[tooltip("Hello"), draggable({ axis: "x" })]} />See the use:* page for more migration details.