Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 be collapsed when the user enters mobile mode and that is controlled with a boolean stored in the state within the component.

like image 517
Embedded_Mugs Avatar asked Jun 11 '17 03:06

Embedded_Mugs


People also ask

How do I know my screen size React?

To get the width and height of the window in React:Use the innerWidth and innerHeight properties on the window object. Add an event listener for the resize event in the useEffect hook. Keep changes to the width and height of the window in a state variable.


1 Answers

What I did is adding an event listener after component mount:

componentDidMount() {     window.addEventListener("resize", this.resize.bind(this));     this.resize(); }  resize() {     this.setState({hideNav: window.innerWidth <= 760}); }  componentWillUnmount() {     window.removeEventListener("resize", this.resize.bind(this)); } 

EDIT: To save state updates, I changed the "resize" a bit, just to be updated only when there is a change in the window width.

resize() {     let currentHideNav = (window.innerWidth <= 760);     if (currentHideNav !== this.state.hideNav) {         this.setState({hideNav: currentHideNav});     } } 

UPDATE: Time to use hooks! If you're component is functional, and you use hooks - then you can use the useMediaQuery hook, from react-responsive package.

import { useMediaQuery } from 'react-responsive';  ...  const isMobile = useMediaQuery({ query: `(max-width: 760px)` }); 

After using this hook, "isMobile" will be update upon screen resize, and will re-render the component. Much nicer!

like image 152
Ben Cohen Avatar answered Sep 29 '22 16:09

Ben Cohen