0
const handleMenu = async () => {
        let menu = await document.querySelector('.navbar-list');
        menu.classList.toggle('.navbar-list-active');
    }

return (
    <div className="navbar-list">
                    <div onClick={handleMenu} className="hamburger">
                    </div>
    </div>
)

The thing is that after class is added to component it really added on the element, but the CSS styling doesn't appear on the element with added class, is this something React is doing? How can I force CSS to re-render the page?

1
  • why the await? Queryselector isnt asyncrhonous Commented Feb 20, 2021 at 22:18

1 Answer 1

1

await doesn't do anything useful unless the value you are awaiting is a promise. querySelector returns either null or an element: never a promise. Your code won't wait for the element to exist.

Now, you can use useRef to get a reference to the element which would then let you toggle the class on it… but don't.

The React way to solve this problem is to store the toggled state in the state and deal with it in the JSX.

const MyComponent = () => {

    const [active, setActive] = useState(false);

    const classNames = ["navbar-list"];
    if (active) classNames.push("navbar-list-active"); 

    const handleMenu = () => setActive(!active);

    return (
        <div className={classNames}>
            <button onClick={handleMenu} className="hamburger">
                Toggle Menu
            </button>
        </div>
    ;)
}

Note that I've changed the div to a button. This is an important accessibility feature and allows the menu to be activated by people who don't use a pointing device to access a page. There is more you should do for accessibility and this article is a good starting point (although it uses traditional DOM instead of React so you'll need to adapt it to use state as I did here).

Sign up to request clarification or add additional context in comments.

2 Comments

I did the way you told, but still style doesnt appear on element when is active, any suggestions?
It's hard to tell why your attempt failed without a minimal reproducible example (the first version of mine forgot to include the handleMenu function so it would have errored at the rendering stage so you can't have been using my code unmodified).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.