Home > database >  Respond to media queries in React js?
Respond to media queries in React js?

Time:04-16

So I solved this problem with using useEffect and innerwidth. However i dont know if it is reliable way. Sometimes it is off by couple of pixels. This is my code:

const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
});

useEffect(() => {
    // Handler to call on window resize
    function handleResize() {
        // Set window width/height to state
        setWindowSize({
            width: window.innerWidth,
            height: window.innerHeight,
        });
    }
    // Add event listener
    window.addEventListener("resize", handleResize);
    // Call handler right away so state gets updated with initial window size
    handleResize();
    // Remove event listener on cleanup
    return () => window.removeEventListener("resize", handleResize);
}, []);

  return (
    // some code
      {windowSize.width < 768 && <div>Hi There</div>}
    // some code
  )

Or is it better to solve it like this using react-responsive: How do I get React to respond to media queries?

CodePudding user response:

There are several premade React hooks for this.

Two good examples:

Essentially what you want to do is use window.matchMedia instead of comparing the width and height of the window.

To be clear, only use this when you need the information in your JavaScript if you're simply hiding or showing something, use CSS media queries instead as they have much better performance.

  • Related