0

I have certain components in my React project which will render only for mobile devices.

I have set it up like this -

const LandingPage = (props) => {
  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    window.screen.width <= 760 ? setIsMobile(true) : setIsMobile(false);
  }, [window.screen.width]);

   **...Components render here**
}

The problem with this is that I get the desired results when I reduce the screen width only after I refresh the page. But I want it to do it automatically when the breakpoint reaches.

How do I achieve that?

Thanks in advance.

vaibhav deep
  • 655
  • 1
  • 8
  • 27
  • I had a similar issue and solved with the answers here: https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs – Ozgur Sar Nov 19 '20 at 07:26

2 Answers2

2

You can use window.onresize to detect the window size change and then compare the value with window.innerWidth

const LandingPage = (props) => {
    
    const [isMobile, setIsMobile] = useState(false);

    useEffect(() => {
      window.screen.width <= 760 ? setIsMobile(true) : setIsMobile(false);
    }, [window.screen.width]);

    function detectWindowSize() {
        window.innerWidth <= 760 ? setIsMobile(true) : setIsMobile(false);        
    }
    
    window.onresize = detectWindowSize;

    console.log(isMobile)

     return(
         <div>

         </div>
     )
}
Juha Kangas
  • 728
  • 5
  • 8
0

You'd wanna make that decision for the user on the page load by checking whether they're visiting from a mobile device or a desktop device.

loading in mobile components on the desktop when the screen resolution changes is not the best way, as it's a very limited use case. Not a lot of desktop users will ever pull their window that small when using your webapp. But you can absolutely account for it using CSS as a fallback while serving up mobile views and components to mobile users only.