useResize
useResize(target?: Element): Service<ResizeProps>The size of one element. With no target it is the document element, which reports the viewport.
Props
interface ResizeProps {
readonly width: number;
readonly height: number;
readonly ratio: number;
readonly orientation: 'square' | 'landscape' | 'portrait';
}breakpoints and activeBreakpoints are removed — useBreakpoint() is their own source now.
Usage
import { Base, useResize } from '@studiometa/js-toolkit';
class Grid extends Base {
static config = { name: 'Grid' };
mounted() {
return useResize(this.$el).subscribe(({ width, orientation }) => {
this.$el.classList.toggle('is-narrow', width < 480);
});
}
}A ResizeObserver does not see the viewport
It reports the box of the observed element, which is what catches a zoom or a scrollbar. For the root element, clientWidth and clientHeight report the viewport and are decoupled from the observed box — so the viewport service keeps a resize listener as well.
That is why useResize() with no target and useResize(someElement) are not the same kind of measurement, even though they share a props shape.
{ immediate: true } works here
An element has a current size between deliveries.
Mixin
class Grid extends withResize(Base) {
resized({ width }) {}
}withResize defaults to the page-wide source, as withScroll does. Scope it with { target: (instance) => instance.$el }.
See also
useWindowSize() — the named default case.