'How to apply media query in nextjs [closed]
Media Query in nextJs Application -
I want to apply media query in my website so that that i can make it responsive how can i do it?
I want to apply next js globally so that i can make it responsive for all devices.
Solution 1:[1]
If you are willing to use a third-party library, MUI has exactly what you need in useMediaQuery:
import * as React from 'react'
import useMediaQuery from '@mui/material/useMediaQuery'
export default function SimpleMediaQuery()
{
const matches = useMediaQuery('(min-width:600px)')
return <span>{`(min-width:600px) matches: ${matches}`}</span>
}
See the docs linked above for more examples of how to use it.
If you want to avoid another library, here's a simple custom hook:
export const useMediaQuery = (width) =>
{
const [targetReached, setTargetReached] = useState(false)
const updateTarget = useCallback((e) =>
{
if (e.matches) setTargetReached(true)
else setTargetReached(false)
}, [])
useEffect(() =>
{
const media = window.matchMedia(`(max-width: ${width}px)`)
media.addEventListener('change', updateTarget)
// Check on mount (callback is not called until a change occurs)
if (media.matches) setTargetReached(true)
return () => media.removeEventListener('change', updateTarget)
}, [])
return targetReached
}
Usage:
// 600px
const matches = useMediaQuery(600)
Solution 2:[2]
Just create a file with any name of your choice. Like "globals.css" under the styles folder. Then write your media queries in that file.
Then import the "globals.css" file into your "_app.js" file.
All your CSS and media queries will start working.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Rahul Dev |