M
M
MuradSky2020-08-22 18:44:29
JavaScript
MuradSky, 2020-08-22 18:44:29

How to remove css class outside button click and menu in React?

Please tell me how to write the code correctly when, when clicking outside the navigation area and the button, remove the css class ?!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Loli E1ON, 2020-08-23
@MuradSky

Hang a click handler on the document, then check the occurrence of the selector, if it is not there, then remove the class

const removeClass= (e) => {
    if (!e.target.closest(".nav")) {
      // remove class
    }
};
useEffect(() => {
    document.body.addEventListener("click", removeClass);
    return () => document.body.removeEventListener("click", removeClass);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question