Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท JSX and Control Flow

Refs and Custom Directives

Get DOM elements in SolidJS with ref, forward refs through components, and write reusable behavior with the use: directive pattern and cleanup.

Most of the time Solid updates the DOM for you. Occasionally you need the element itself: to focus an input, measure a box, attach a charting library or observe visibility. Solid gives you refs for that, and directives (use:) to package such element logic for reuse.

ref: grab the element

The simplest form is to declare a variable and pass it as ref. Solid assigns the real DOM element to it while it builds the node.

JSX
function Autofocus() {
  let input;
  onMount(() => input.focus());
  return <input ref={input} />;
}

The variable is declared with let and is undefined until Solid creates the element, which is why the focus call sits in onMount (see Component Lifecycle). With TypeScript you declare let input!: HTMLInputElement.

A callback ref is a function that receives the element. It runs as the element is created, before it is attached.

JSX
<canvas ref={(el) => draw(el)} />
Ref and onMount to measure and focus

Passing refs through components

A component cannot receive a ref as a special argument: it is just a prop named ref. If a child wants to expose its inner element, the parent passes a function (or an assigned variable) and the child forwards it.

JSX
function FancyInput(props) {
  return <input class="fancy" ref={props.ref} />;
}

function Form() {
  let el;
  onMount(() => el.focus());
  return <FancyInput ref={el} />;
}

When you write ref={el} on a component, the compiler passes a callback that assigns el. In the child, ref={props.ref} forwards it to the real element. If you need the element in the child as well, call both: ref={(e) => { mine = e; props.ref?.(e); }}.

Directives with use:

When a piece of element logic repeats, such as "close when clicking outside", "auto-resize this textarea" or "observe when visible", write a directive: a function that receives the element and an accessor for an optional value.

JSX
function clickOutside(el, accessor) {
  const onClick = (e) => { if (!el.contains(e.target)) accessor()?.(); };
  document.body.addEventListener("click", onClick);
  onCleanup(() => document.body.removeEventListener("click", onClick));
}

<div use:clickOutside={() => setOpen(false)}>Menu</div>
  • The directive is called once with (element, accessor); accessor() returns the current value of the attribute (here a callback).
  • It runs in the element's reactive owner, so onCleanup and effects work and are disposed with the element.
  • In TypeScript, declare the directive in the JSX.Directives interface so use:clickOutside type-checks. Also keep the import visible, as the compiler needs to see the name used.

Because use: needs the Solid compiler, the demo below uses the plain-function equivalent: call the directive from a ref callback, which is what the compiler generates.

A click-outside directive via ref

Refs and reactivity

A ref is not reactive: assigning it does not trigger anything. That is intentional, since you want the element at creation. If other code needs to react to the element appearing (for example inside Show), store it in a signal:

JSX
const [el, setEl] = createSignal();
<div ref={setEl} />
createEffect(() => { if (el()) observer.observe(el()); });

Passing a setter as the ref is a common way to make "the element" a reactive value, and works with the owner and cleanup rules from Ownership, Roots and Cleanup.

Common mistakes

  • Using the ref before it is set. In the component body the variable is still undefined; wait for onMount.
  • Forgetting to declare the variable with let (not const), because Solid assigns it later.
  • Setting DOM text with a ref when a reactive expression would do. Prefer declarative updates.
  • Not removing listeners in directives. Always pair setup with onCleanup.
  • Using use: in code that is not compiled, such as plain html templates.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is a ref variable assigned?

    The element is created during the component body; by onMount it is assigned and attached.
  2. 2. How does a parent get an inner element of a child component?

    ref is a normal prop on components; the child must put it on an element.
  3. 3. What arguments does a use: directive function receive?

    The compiler calls directive(element, () => value).
  4. 4. How do you make the element itself reactive?

    Passing a signal setter stores the element in a signal that effects can track.

Summary

  • ref gives you the DOM element; read it in onMount or a callback.
  • Forward refs to children by passing a ref prop and putting it on an element.
  • use: directives package reusable element behavior; they receive (el, accessor) and clean up with onCleanup.
  • Store the element in a signal when you need to react to it.

Next: Components and Props