Skip to main content

useContainerBreakpoint

useContainerBreakpoint is a hook used to determine if the document matches a media query string (or media query list) by comparing it to a container. It will listen to the breakpoints specified and will return a boolean value indicating if this media query is met or not. It internally relies on the useContainerSize hook to determine the width and height of the container based on its ref.

Import

import { useContainerBreakpoint } from '@dynatrace/strato-components-preview/core';

Use cases

The media query syntax is similar to the CSS one, which can be checked here. However, only width and height-related queries are currently supported (not orientation queries like orientation, prefers-color-scheme, etc.).

Single media query

The simplest way to use it is as follows:

const above500 = useContainerBreakpoint('(min-width: 500px)', containerRef);

The result, above500, is a boolean indicating whether the media query matches successfully, so whether the minimum width of the container is 500px.

CodeSandbox

Multiple media queries

An array of media queries can also be passed in as follows:

const [above500, above1000] = useContainerBreakpoint([ '(min-width: 500px)', '(min-width: 1000px)' ], containerRef);

The result is an array, in which the first item above500, is a boolean indicating whether the first media query matches successfully, so whether or not the minimum width of the window is 500px, and the second item, above1000, is a boolean indicating whether the second media query matches successfully, so whether the minimum width of the container is 1000px.

CodeSandbox

Caveats

Do not overuse this query, since it still has a high performance impact in combination with a very large number of containers and resizing events. Also, avoid styling the container's width/height depending on the result of this query or do it sensibly, since it might run into an endless render cycle.

Example: Don't add style={{ width: restrictedWidth ? '900px' : '300px') }} on the container, where the media query used is '(min-width: 130px) and (max-width: 800px)'.

Moreover, since only width and height-related queries can be supported and wrong usages can lead to endless render cycles, this is a temporary solution until the native CSS container queries are available.

Still have questions?
Find answers in the Dynatrace Community