vaibhav deep
vaibhav deep

Reputation: 835

How to get React App change content on the screen when screen width changes

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.

Upvotes: 0

Views: 2466

Answers (2)

Juha Kangas
Juha Kangas

Reputation: 788

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>
     )
}

Upvotes: 2

user2364819
user2364819

Reputation:

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.

Upvotes: 0

Related Questions