How to use the media query syntax in React component?

Sometimes, we want to use the media query syntax in React component.

In this article, we’ll look at how to use the media query syntax in React component.

How to use the media query syntax in React component?

To use the media query syntax in React component, we can use the window.matchMedia method.

For instance, we write:

import React, { useState, useEffect } from "react";

export default function App() {
  const [isDesktop, setDesktop] = useState(
    window.matchMedia("(min-width: 650px)").matches
  );

  const updateMedia = () => {
    setDesktop(window.matchMedia("(min-width: 650px)").matches);
  };

  useEffect(() => {
    window.addEventListener("resize", updateMedia);
    return () => window.removeEventListener("resize", updateMedia);
  });

  return (
    <div>
      {isDesktop ? (
        <div>I show on 651px or higher</div>
      ) : (
        <div>I show on 650px or lower</div>
      )}
    </div>
  );
}

We create the isDesktop state which is set to window.matchMedia("(min-width: 650px)").matches initially.

We call window.matchMedia with a string that has CSS media queries to check if the screen’s width is 650px or wider.

Then we define the updateMedia function that calls setDesktop with window.matchMedia("(min-width: 650px)").matches.

Then we call useEffect with a callback that attaches the resize event listener to window with addEventListener.

We use updateMedia as the resize event listener.

In updateMedia, we call setDesktop with window.innerWidth > 650 to check if we’re in a desktop sized screen.

Also, we return a function to calls window.removeEventListener to clear the event listener.

Finally, we render the content we want based on the value of isDesktop.

Conclusion

To use the media query syntax in React component, we can use the window.matchMedia method.