0

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.

Johan
  • 2,088
  • 2
  • 9
  • 37

3 Answers3

0

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.

David Machado
  • 430
  • 2
  • 10
  • I don't know why I wanted to set a state. CSS is perfect. Thank you very much and sorry for the dumb question ! – Johan Aug 03 '22 at 10:21
0

Simply add resize Event Listener

const App = () => {

  useEffect(() => {
    window.addEventListener('resize', handleResize);
  }, []);

  const handleResize = (e) => {}
  
  return <div>Test</div>;
};
MM2021
  • 150
  • 6
0

You can do it by creating a class somewhere and writing display: none; inside of it. After doing so you can get the screen width with screen.width.

    const viewerFunc = (yourContainerId) => {
        const overview = document.getElementById(yourContainerId);
        overview.classList.toggle('d-none');
    }
document.getElementById("demo").innerHTML = 
"Screen width is " + screen.width;

or you can do it as @David Machado suggested with CSS.

display-desktop{
  // your codes
  display: none;
}

display-mobile{
  // your codes
  display: flex;
}


  // Mobile version of your app
@media only screen and (min-width: 768px) {
  
  display-desktop{
    display: flex;  
  }
  display-mobile{
    display: none;
  }
  
  }
moldere
  • 1
  • 1