I am trying to add 'open' class to <div className='menu' onClick={handleSidebar}>
when I click it, and remove when clicked again. In devtools I can see 'open' be added but when I click it again it will not remove. Is there a different approach to removing class?
import React, { useEffect } from 'react';
import './menu.styles.scss';
function Menu({ handleSidebar }) {
useEffect(() => {
const menu = document.querySelector('.menu');
let menuOpen = false;
menu.addEventListener('click', () => {
if (!menuOpen) {
menu.classList.add('open');
menuOpen = !menuOpen;
} else {
menu.classList.remove('open');
menuOpen = !menuOpen;
}
});
});
return (
<div className='menu' onClick={handleSidebar}>
<div className='menu-btn'></div>
</div>
);
}
export default Menu;
You're better off doing this with useState
...the way you have it now with the document.querySelector
is sort of besides the point of react.
import React, { useEffect } from 'react';
import './menu.styles.scss';
function Menu({ handleSidebar }) {
const [ open, setOpen ] = useState(true)
return (
<div className={`menu ${open ? 'open' : ''}`} onClick={setOpen(!open)}>
<div className='menu-btn'></div>
</div>
)
}
export default Menu;
Your code will not reach else part as u assign false to menuOpen. So the if condition will satisfy evey time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.