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.

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

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


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

You can set the default value of toggle according to screen size with the media queries api. And listen for screen size change I you need.

Please take a look to this response: Media query syntax for Reactjs

Method 3

Are you using tailwindcss? follow this to add tailwind to your project through CDN

Refactor your className like ${toggle ? "hidden" : "block"} sm:block and remove your style property. In mobile view, the div will always be hidden. It won’t display it as a block because the media query sm:block will only display it as a block when the screensize reaches 768 width & more. This will only display the basket once you’ve click the button. Also use this convention for your setToggle function setToggle(prevState => !prevState).

Method 4

Set the default state to false and use useState callback

  const [toggle, setToggle] = useState(window.innerWidth > 700);

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

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x