ResizeController
A ResizeObserver on elements, attached and disconnected with the host.
Reach for it to react to an element changing size.
Import
import { ResizeController, createResizeController } from '@ecopages/radiant-ui/controllers';Try it
The box is observed. Change width toggles its inline width and the callback reports the new content width. The observer also reports the size at the moment it starts.
Box
<div data-example="resize">
<div data-box style="width: 6rem">Box</div>
<button type="button">Change width</button>
<p data-status></p>
</div>import { ResizeController } from '@ecopages/radiant-ui/controllers';
export function mount(root: HTMLElement): () => void {
const box = root.querySelector<HTMLElement>('[data-box]')!;
const status = root.querySelector('[data-status]')!;
const resize = new ResizeController({
getTargets: () => [box],
onResize: ([entry]) => (status.textContent = `Width ${Math.round(entry.contentRect.width)}px`),
});
resize.attach();
root.querySelector('button')!.addEventListener('click', () => {
box.style.width = box.style.width === '12rem' ? '6rem' : '12rem';
});
return () => resize.destroy();
}mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run.
Config
| Option | Description |
|---|---|
getTargets | Resolved on every attach(). null entries are skipped. |
onResize | Receives the ResizeObserverEntry[]. |
options | Optional ResizeObserverOptions, such as { box: "border-box" }. |
Lifecycle
attach() observes every target; attaching while attached changes nothing. destroy() disconnects the observer.
With a host, createResizeController(host, config) does the same on connect and disconnect; see bindController.
Protected hooks
None. Change behavior through the config callbacks.