Using Window.matchMedia() for Media Queries in Reactjs
The Magic..
We listed for this event, MediaQueryListEvent
and we get an object that looks something like this back.
MediaQueryListEvent : {
isTrusted: true,
media: "(min-width: 768px)",
matches: true,
...
}
We are looking to see if we get a match from the query and if so, then we want to take action.
Let’s set up our state variable mQuery
using useState
and initialized it by getting the current window innerWidth.
const [mQuery, setMQuery] = React.useState<any>({
matches: window.innerWidth > 768 ? true : false,
});
In our component we will listen for this event, from the window
object by calling window.matchMedia
useEffect(() => {
let mediaQuery = window.matchMedia("(min-width: 768px)");
mediaQuery.addListener(setMQuery); // this is the cleanup function to remove the listener
return () => mediaQuery.removeListener(setMQuery);
}, []);
the addListener
calls our setState function to hold the results, and the changing of the state variable will cause the component to rerender.
Based on the state variable we will render the hamburger menu or the list of buttons that correspond to the side menu…