Search code examples
javascriptcssreactjstypescripttoggle

react js toggle problem when I visit from mobile


I am trying to responsive my design. My logic is when the div style will be display:"block" it will show a basket and when the user will browse on mobile the div display will be none and the user need to click on the button to open the basket.

Now the problem is my default state is true that is why when a mobile user visits the website he will see first a basket that I don't want. I want when the user will first visit he will not see the basket he needs to click on the button. I can't set the default state to false because the desktop user can't see the basket.

// MY STATE
  const [toggle, setToggle] = useState(true);

<button onClick={() => setToggle(!toggle)}>Open</button>
<div
  className="box_order mobile_fixed"
  style={{ display: `${toggle ? "block" : "none"}` }}
  >
// BASKET CODE
</div>

Solution

  • You could use window.matchMedia to set the initial value of the state.

    The Window interface's matchMedia() method returns a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.

    For instance:

    const [toggle, setToggle] = useState(window.matchMedia("max-width: 768px").matches);