How to detect if screen size has changed to mobile in React?

前端 未结 5 1665
南方客
南方客 2021-01-30 17:25

I am developing a web app with React and need to detect when the screen size has entered the mobile break-point in order to change the state. Specifically I need my sidenav to b

5条回答
  •  情书的邮戳
    2021-01-30 18:02

    Using hooks in React(16.8.0+) refering to: https://stackoverflow.com/a/36862446/1075499

    import { useState, useEffect } from 'react';
    
    function getWindowDimensions() {
      const { innerWidth: width, innerHeight: height } = window;
      return {
        width,
        height
      };
    }
    
    export default function useWindowDimensions() {
      const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
    
      useEffect(() => {
        function handleResize() {
          setWindowDimensions(getWindowDimensions());
        }
    
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
      }, []);
    
      return windowDimensions;
    }
    

提交回复
热议问题