use-container-queries
Version:
A react hook that tracks a containers size and the range that width falls into within a list of breakpoints. This allows better responsive styling, where the user can style DOM elements based on their container, rather than the browser viewport.
34 lines (33 loc) • 2.05 kB
TypeScript
import { RefCallback } from 'react';
export declare type QueryBreakpoints = {
/** the values should be consisted of a min and max number, except for your largest breakpoint where it would be the min value and anything above */
[key: string]: [number, number?];
};
export declare type ContainerQueryProps = {
/** Explicit key/value map of the predefined breakpoints you wish to use. Each value should have a min and max range (Eg { small: [0, 300], med: [301, 600]} ) */
breakpoints: QueryBreakpoints;
/** Flag to ignore width updates if you are only interested in when a breakpoint changes. App will forego updating state for the width */
ignoreDimensions?: boolean;
};
export declare type ContainerQueryResult<T> = {
/** Callback ref to be assigned to the containing DOM node the user wishes to observe for changes. */
ref: RefCallback<T>;
/** The current 'active' breakpoint. This key will match one of the key/value pairs from the breakpoints supplied to the hook */
active: string;
/** Current width of the observed element */
width: number;
};
/**
* useContainerQueries.
*
* A react hook utilizing the Resize Observer API that observes a containing elements width.
* It matches that width with the users predefined breakpoint ranges and determines the containers size.
* The main purpose of this is to allow web developers to style DOM elements based on
* the size of a containing element rather than the size of the browser viewport.
*
* @param {QueryBreakpoints} breakpoints A key/value mapping of explicit breakpoint ranges to be
* tested against the current observed elements width to find a match.
* @param {boolean} ignoreDimensions Flag stating the user doesn't care about the changing container width,
* and only the breakpoint changes. The app will only update state on these changes.
*/
export declare function useContainerQueries<T extends HTMLElement>({ breakpoints, ignoreDimensions, }: ContainerQueryProps): ContainerQueryResult<T>;