Answer the question
In order to leave comments, you need to log in
How to hang a different onclick in React depending on the current state?
I just started touching react and I'm trying to make a mobile menu that should open and close on a click on the burger button, and also close on a click outside the menu.
To handle a click outside the element, I took a component from airbnb OutsideClickHandler, which wraps the component, the click outside of which is caught and then passes false to state. And clicking on the burger toggles the state. The problem is that it lies outside the menu and when I click on the burger while the menu is open, the state changes to false due to OutsideClickHandler and immediately back to true due to clicking on the burger.
I thought that it could be solved in the following way: If state = true (the menu is open), then pass the onclick function to the burger, which makes state = false, and if state = false, then vice versa. Maybe somehow you can hang a different onclick in React depending on the current state? Or are there any other simpler solutions to my problem? Thanks for any advice.
const Nav = (props) => {
const [burgerState, setBurgerState] = useState(false);
const changeBurger = () => {
setBurgerState(!burgerState);
};
return (
<nav className="nav nav--theme-dark">
<Burger onClick={changeBurger} burgerState={burgerState} />
<ul className="nav__list">
<li className="nav__item nav__item--more">
<a className="nav__link nav__link--drop nav__link--theme-dark">
{data.additionalName}
</a>
<OutsideClickHandler onOutsideClick={() => {setBurgerState(false)}}>
<div className={cn("nav__drop js-drop", {'is-open' : burgerState === true})}>
меню
</div>
</OutsideClickHandler>
</li>
</ul>
</nav>
);
};
const Burger = ( {onClick, burgerState} ) => {
console.log(burgerState)
return (
<button className={cn("burger nav__burger", {'is-open' : burgerState === true})} onClick={onClick}>
<span className="burger__line" />
</button>
);
};
Answer the question
In order to leave comments, you need to log in
1) wrap changeBurger in useCallback
const changeBurger = useCallback(() => {
setBurgerState(!burgerState);
}, [burgerState]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question