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 '@chakra-ui/react'
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.
// single media query with no optionsconst [isLargerThan800] = useMediaQuery('(min-width: 800px)')// ssr-friendly media query with fallbackconst [isLargerThan800] = useMediaQuery('(min-width: 800px)', {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.
Keep in mind this API relies on the users browser support of
window.matchMediaand will always returnfalseif it is not supported or does not exist (e.g. during serverside rendering).
Usage#
function Example() {const [isLargerThan1280] = useMediaQuery('(min-width: 1280px)')return (<Text>{isLargerThan1280 ? 'larger than 1280px' : 'smaller than 1280px'}</Text>)}
function Example() {const [isLargerThanHD, isDisplayingInBrowser] = useMediaQuery(['(min-width: 1920px)','(display-mode: browser)',])function determineText() {if (isLargerThanHD) {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>}