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'

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.matchMedia and will always return false if 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>
}
Edit this page on GitHub

Proudly made inNigeria by Segun Adebayo

Deployed by â–² Vercel