Point to an element in the DOM with useRefs Helper
The useRefs helper creates typed, lazy references to elements within your component’s template using a standard CSS selector.
It’s a convenient alternative to manually calling getElement() for each element.
Instead of writing multiple getters, useRefs lets you define all your element references in one place, using a simple mapping function.
useRefs() uses getElement() behind the hood, providing an >>> operator that gets elements through a child's shadow DOM.
Signature
this.useRefs(<mapFn>): Readonly<ElementMap>Parameters
mapFn: callback function that receives a specialref()function.
You callref(selector)for each element you want to reference, anduseRefsreturns an object with lazy getters for those elements.
Each getter internally calls getElement(), ensuring the element exists and automatically traversing shadow DOM boundaries if needed.
Return value
- An object
ElementMapwhere each key corresponds to an element reference, and each property is a getter that returns the correspondingHTMLElement(or subtype).
Example
import { html, Jadis, createSelector } from '@jadis/core';
class FormComponent extends Jadis {
static selector = createSelector('form-component');
templateHtml() {
return html`
<form>
<input class="my-input" />
<button>Submit</button>
</form>
`;
}
refs = this.useRefs((ref) => ({
input: ref('input.my-input'),
button: ref('button'),
}));
connectedCallback() {
this.refs.button.addEventListener('click', () => {
console.log('Input value:', this.refs.input.value);
});
}
}import { html, Jadis } from '@jadis/core';
class FormComponent extends Jadis {
static readonly selector = 'form-component';
templateHtml() {
return html`
<form>
<input class="my-input" />
<button>Submit</button>
</form>
`;
}
readonly refs = this.useRefs((ref) => ({
input: ref<HTMLInputElement>('input.my-input'),
button: ref('button'),
}));
connectedCallback() {
this.refs.button.addEventListener('click', () => {
console.log('Input value:', this.refs.input.value);
});
}
}// @ts-check
import { html, Jadis, createSelector } from '@jadis/core';
class FormComponent extends Jadis {
static selector = createSelector('form-component');
templateHtml() {
return html`
<form>
<input class="my-input" />
<button>Submit</button>
</form>
`;
}
refs = this.useRefs((ref) => ({
/** @type HTMLInputElement */
input: ref('input.my-input'),
button: ref('button'),
}));
connectedCallback() {
this.refs.button.addEventListener('click', () => {
console.log('Input value:', this.refs.input.value);
});
}
}Advanced Example: Nested Components
You can also traverse into a child component’s shadow DOM using the >>> operator (same as getElement()).
this.useRefs((ref) => ({
childButton: ref('child-component >>> button'),
}));This retrieves the <button> inside the child-component’s shadow root.
TIP
Check out the related helper getElement() used internally by useRefs to perform element lookups.