liveBook · Manning

Ref

As explained in Web Component Development with Modern Libraries and Tooling

A template directive function or attribute that captures a reference to a rendered DOM node in a property.

A ref gives component code access to a rendered DOM element. Use one when a custom element exposes a property that you need to read or change, such as a selected value or a display color. section 9.7 section 9.5

Set a custom element’s color in Vue

Declare `const helloWorldElement = ref(null)`, then render `<hello-world ref="helloWorldElement"></hello-world>`. After rendering, an `onMounted` callback can set `helloWorldElement.value.color = "red"` when the reference has a value. The template’s `ref` attribute connects the rendered element to the variable. section 9.7

The access pattern varies by framework:

  • React uses `useRef`; the element is available through the ref object’s `current` property. An effect reads a radio-group’s initial value and uses it to update another custom element. section 9.4
  • Solid assigns a rendered element to a ref variable. `onMount` reads the radio-group’s value; an event handler responds to later changes. section 9.5
  • In wrec, a `ref` attribute can capture a rendered element in a property named by the attribute’s value. section 8.13

When using custom elements in React or Solid JSX, declare `ref` as an optional attribute in each element’s JSX type. Capture the element first, then read or update its properties after rendering. section 9.4 section 9.5

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Shows reference declarations and post-render access in component examples, but only briefly mentions wrec’s ref attribute.
Examples
Pairs a greeting custom element with a radio-group whose selected color updates the greeting.
What it assumes
Assumes familiarity with component markup and TypeScript or JavaScript; supplies JSX declarations where React and Solid require them.
What you can do after
Apply it via React, Solid, or Vue to access rendered custom elements and update their properties.
How it connects
Links refs to custom elements, JSX type declarations, lifecycle hooks, properties, and custom events.

Also explained in

Compare how 4 books explain ref →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.