Search code examples
reactjsheaderwidth

How to listen to width of page - React


I have 2 headers. I want to render the first one when width > 768px, and second one when < 768.

I tried this :

const [isMobileResponsive, setIsMobileResponsive] = useState(false);

  useEffect(() => {
    setIsMobileResponsive(window.innerWidth < 768);
  } , [window.innerWidth]);

return (
    !isMobileResponsive ?
       <p>header1</p>
         :
       <p>header2</p>
)

The problem with this : when I go to chrome responsive feature, and resize the size of the screen, React does not re-render and don't change the header. I have to reload the page to get the new Header.

How can I do this ?

Thank you very much.


Solution

  • To track the window's width in react you can make a custom hook to handle window resizing such as it is done here.
    But in this concrete case I think you would be better off using CSS media queries with a mobile first approach.

    .navbar-desktop {
      display: none;
    }
    
    @media only screen and (min-width: 768px) {
      /* For desktop: */
      .navbar-desktop {
        display: block;
      }
      .navbar-mobile {
        display: none;
      }
    }
    

    The code above hides the .navbar-desktop by default only showing it if the width of the viewport is greater than 768. Doing the exact opposite for the .navbar-mobile.