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

前端 未结 5 1577
南方客
南方客 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:17

    There are multiple ways to archive this first way is with CSS using this class

    @media screen and (max-width: 576px) {}
    

    any class inside this tag will only be visible when the screen is equal or less than 576px

    the second way is to use the event listener

    something like this

     constructor(props)
        {
            super(props);
    
            this.state = {
                isToggle: null
            }
    
            this.resizeScreen = this.resizeScreen.bind(this); 
        }
        
        
         componentDidMount() {
    
            window.addEventListener("resize", this.resizeScreen());
    
        }
        
        
        resizeScreen() {
            if(window.innerWidth === 576)
            {
                this.setState({isToggle:'I was resized'});
            }
            
        }

    even with the event listener I still prefer the CSS way since we can use multiple screen sizes without further js coding.

    I hope this helps!

提交回复
热议问题