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>
CodePudding user response:
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);
CodePudding user response:
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
CodePudding user response:
Are you using tailwindcss? follow this to add tailwind to your project through CDN https://tailwindcss.com/docs/installation/play-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)
.
CodePudding user response:
Set the default state to false and use useState callback
// MY STATE
const [toggle, setToggle] = useState(window.innerWidth > 700);
<button onClick={() => setToggle(toggleBefore => !toggleBefore)}>Open</button>
<div
className="box_order mobile_fixed"
style={{ display: toggle ? "block" : "none" }}
>
// BASKET CODE
</div>