BattlefyBlogHistoryOpen menu
Close menuHistory

Using media queries in react

Jack BlissApril 1st 2022

Sometimes, you want to render a different React tree depending on the viewport. You can just apply media queries to the divs and use display: none;, but this will still render to the DOM and mount any required components. Using hooks and the window.matchMedia method, we can dictate whether or not the components are rendered using standard CSS media query syntax.

/**
 * Determine if a media query condition is true or false.
 * @param {String} mediaQuery The media query to check for, e.g. '(min-width: 450px)'
 * @returns A Boolean representing the media query condition.
 */
export const useMediaQuery = (mediaQuery) => {
  const [match, setMatch] = useState(Boolean(window.matchMedia(mediaQuery).matches));

  useEffect(() => {
    const mediaQueryList = window.matchMedia(mediaQuery);
    const handler = () => setMatch(Boolean(mediaQueryList.matches));
    mediaQueryList.addEventListener('change', handler);
    handler();
    return () => mediaQueryList.removeEventListener('change', handler);
  }, [mediaQuery]);

  return match;
};

This hook takes a CSS media query string and returns a boolean value depending on whether or not the media query currently applies. The value will be automatically updated as the user resizes their browser window.

2022

Powered by
BATTLEFY