Categories
React Answers

How to implement media queries with React?

Spread the love

Sometimes, we want to implement media queries with React.

In this article, we’ll look at how to implement media queries with React.

How to implement media queries with React?

To implement media queries with React, we create our own hook.

For instance, we write

const useMediaQuery = (query) => {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => setMatches(media.matches);
    window.addEventListener("resize", listener);
    return () => window.removeEventListener("resize", listener);
  }, [matches, query]);

  return matches;
};

export default useMediaQuery;

to create the useMediaQuery hook.

In it we check if the media query matches the screen size with window.matchMedia.

Then we call setMatches if media.matches is different from matches.

We then call addEventListener to listen to the resize event with listener.

And we call removeEventListener if matches or query changes.

Then we call useMediaQuery in our component to see if our screen matches the media query string.

Conclusion

To implement media queries with React, we create our own hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *