In react I would like to lock scroll-bar when sub-menu is out and then again unlock it when menu is hidden. I press the same button to open and close sub-menu (adds and removes translate for this element). With what i did page sucessfully locks but when i press menu button and sub-menu dissapears the page is still locked, how can i change that the code is below:
const [isActive, setActive] = useState(false);
const toggleClass = () => {
setActive(!isActive);
document.body.style.overflow = "hidden"
};
<div className="button"
onClick={toggleClass}
className={
isActive ? "nav-button closebtn active" : "nav-button closebtn"}>
<span></span>
</div>
how can I toggle the value of overflow
from hidden to unset by pressing the button, just like i do with adding the class when i press the same button
CodePudding user response:
Use toggle
and add style in CSS file.
import './myStyle.css';
const [isActive, setActive] = useState(false);
const toggleClass = () => {
setActive(!isActive);
document.body.classList.toggle('lock', isActive); // <-- Add this
};
<div className="button"
onClick={toggleClass}
className={
isActive ? "nav-button closebtn active" : "nav-button closebtn"}>
<span></span>
</div>
// myStyle.css
.lock {
overflow: hidden;
}
CodePudding user response:
I believe that in your togle you have to validate if it is active or not and in that change the hidden to visible
Something like:
const toggleClass = () => {
setActive((active) => {
if(active){
document.body.style.overflow = "visible";
return !active;
}
document.body.style.overflow = "hidden";
return !active;
});
};