useMediaQuery
useMediaQuery
is a custom hook used to help detect whether a single media
query or multiple media queries individually match.
Learn more about the API and its backgrounds.
Import
import { useMediaQuery } from '@hover/blueprint';
API Reference
The useMediaQuery
hook accepts a single media query or an array of media
queries, and optionally an object that contains an ssr
boolean and a
fallback
string.
import { useMediaQuery } from '@hover/blueprint';import { breakpoints } from '@hover/blueprint/foundation';// single media query with no optionsconst [isLargerThanTablet] = useMediaQuery( `(min-width: ${breakpoints.tablet})`,);// ssr-friendly media query with fallbackconst [isLargerThanTablet] = useMediaQuery( `(min-width: ${breakpoints.tablet})`, { ssr: true, fallback: false, // return false on the server, and re-evaluate on the client side },);
If we're on the server, the ssr
option will determine whether to return the
fallback
value or execute the query directly. The fallback
property is
what's going to be returned if ssr
is set to true
and we're in a server
context.
Return value
The useMediaQuery
hook returns an array of booleans, indicating whether the
given query matches or queries match.
Why an array? useMediaQuery
accepts both a string and an array of strings, but
will always return an array. This way, you can combine multiple media queries
which will be individually matched in a single call.
Usage
import { useMediaQuery } from '@hover/blueprint';import { breakpoints } from '@hover/blueprint/foundation';function Example() { const [isLargerThan350] = useMediaQuery( `(min-width: ${breakpoints.width350})`, ); return ( <Text> {isLargerThan350 ? 'larger than `width250`' : 'smaller than `width350`'} </Text> );}
import { useMediaQuery } from '@hover/blueprint';import { breakpoints } from '@hover/blueprint/foundation';function Example() { const [isLargerThanDesktop, isDisplayingInBrowser] = useMediaQuery([ `(min-width: ${breakpoints.desktop})`, '(display-mode: browser)', ]); function determineText() { if (isLargerThanDesktop) { return `high resolution you got there ${ isDisplayingInBrowser ? 'in your browser' : 'on your screen' }`; } return isDisplayingInBrowser ? 'rendering in a browser' : 'rendering on something else, e.g. PWA'; } return <Text>{determineText()}</Text>;}