This content originally appeared on DEV Community and was authored by Karl Castillo
In these modern times, your web applications can be viewed in a variety of screen sizes -- from small screen phones to large 4k monitors. Luckily CSS allows us to add certain stylings depending on many variables using media queries. Sometimes using media queries isn't enough to achieve the goal. This is where matchMedia
could help.
matchMedia
is a method provided by window
that can determine whether the given media query matches the current state of the browser.
matchMedia
matchMedia
accepts a media query as a string and returns a MediaQueryList
which can be used to check if the current state of the browser matches the given media query.
const mediaQueryList = window.matchMedia("only screen and (max-width: 600px)");
if (mediaQueryList.matches) {
console.log("Matches");
} else {
console.log("Does not match");
}
Keeping track of changes
We can keep track of these changes by listening for a change event.
const callback = (event) => {
if (event.matches) {
console.log("Matches");
} else {
console.log("Does not match");
}
}
mediaQueryList.addEventListener("change", callback);
mediaQueryList.removeEventListener("change", callback);
If you need to support older browsers, you can use addListener
and removeListener
respectively but do remember that those methods are deprecated.
mediaQueryList.addListener("change", callback);
mediaQueryList.removeListener("change", callback);
useMediaQuery
This technology can also be transferred to a reusable React hook. The hook will accept a media query and a callback function for when changes occur.
const useMediaQuery = (query, callback) => {
const [isMatchingQuery, setIsMatchingQuery] = useState(false);
useEffect(() => {
const mediaQueryList = window.matchMedia(query);
const onMediaQueryUpdate = (e) => {
setIsMatching(e.matches);
if(callback) {
callback(e);
}
};
// Set whether the browser initially matches the query
setIsMatchingQuery(mediaQueryList.matches);
mediaQueryList.addEventListener("change", onMediaQueryUpdate);
return () => {
mediaQueryList.removeEventListener("change", onMediaQueryUpdate);
}
});
return { isMatchingQuery };
}
If you're already using matchMedia
in your project, how are you using it? If you're using a different framework, how would you incorporate matchMedia
into that framework?
This content originally appeared on DEV Community and was authored by Karl Castillo

Karl Castillo | Sciencx (2021-08-29T17:39:57+00:00) Media Queries in JS. Retrieved from https://www.scien.cx/2021/08/29/media-queries-in-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.