cbdeveloper
cbdeveloper

Reputation: 31485

How to get the same window.innerWidth regardless of the zoom level so my responsive layout won't change while zooming?

I've built my app using reactand styled-components. It's all client-side rendered and routed.

All my responsive layout is based on the window.innerWidth value and I do lots of:

const MyComponent_DIV = styled.div`
  width: ${props => props.isMobile ? "200px" : "400px"};
`;

const [windowWidth,setWindowWidth] = useState(window.innerWidth);

... some code

return (
  <MyComponent_DIV
    isMobile={windowWidth <= 768}
  />
);

NOTE: I also attach a resize event listener, so my app is responsive to resize events. So far so good.

function handleResize() {
  console.log("FROM RESIZE: " + window.innerWidth);  // I CAN SEE THIS VALUE CHANGING WHEN ZOOMING IN AND OUT
  setWindowWidth(window.innerWidth);
}

But the weird thing, at least to me, is when I found out that changing the browser ZOOM level (on desktop and mobile) affects the window.innerWidth value. And it also fires the resize event.

What I'm trying to accomplish:

EXTRA:

This is my meta viewport tag:

<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, shrink-to-fit=no">

QUESTION

Does it make sense for the zoom event to change the window.innerWidth property? I mean, isn't that completely counter intuitive?

How can I avoid it, or at least, do some workaround for my app to behave the way I need?

Upvotes: 4

Views: 1666

Answers (0)

Related Questions