Making a React App and need to have different functionality for Desktop and Mobile. So far I did this:
const [width, setWidth] = useState(window.innerWidth);
const [mobile, setMobile] = useState(false);
const handleWindowSizeChange = () => {
setWidth(window.innerWidth);
if(width <= 500) {
setMobile(true);
} else setMobile(false);
}
useEffect(() => {
window.addEventListener('resize', handleWindowSizeChange);
return () => {
window.removeEventListener('resize', handleWindowSizeChange);
}
}, []);
But it's not working. I console logged the "mobile" state and it always logs "false" even tho i change the screen size in my browser. Especially if i reload my page while still being in mobile view. How do I make it work?
CodePudding user response:
It looks like there are two issues preventing this from working.
- You're not setting
isMobile
to the correct value on initial page load. The handler looks reasonable for updating isMobile on resize, but if the window isn't resized, it won't be set correctly. - Within
handleWindowSizeChange
, you're usingwidth
, which hasn't been set towindow.innerWidth
yet.
My recommendation would be to get rid of the width
state (unless you need it outside of getting isMobile
). Your code could look something like:
const [mobile, setMobile] = useState(window.innerWidth <= 500);
const handleWindowSizeChange = () => {
setMobile(window.innerWidth <= 500);
}
useEffect(() => {
window.addEventListener('resize', handleWindowSizeChange);
return () => {
window.removeEventListener('resize', handleWindowSizeChange);
}
}, []);