Home > Software engineering >  How I can implement e.preventDefault(); in useEffect?
How I can implement e.preventDefault(); in useEffect?

Time:05-18

I have a question for you. I want to add e.preventDefault(); in useEffect so that it is called as soon as the state changes to true. But something does not work, can someone tell me how to implement this method.

const [active, setActive] = useState(false);
 useEffect((e) => {
    if (active === true) {
        e.preventDefault();
    }
}, [active])



<ul
    onClick={() => setBurger(false)}
    <className="nav__ul">
    <li><Link to='/homeWork'>Таблица</Link></li>
    <li><a href="#photo__h2">Галерея</a></li>
    <li><a href="#questions__head">Питання-відповідь </a></li>
    <li><a href="#contacts__h3">Контакти</a></li>
    <li onClick={() => setActive(true)}><a href="/" className="popup_open">Забронювати</a></li>
</ul>

CodePudding user response:

You don't have access to event instance inside useEffect. It's accessible in onClick callback not inside effect.

const onClick = useCallback((e) => {
  setActive(true)
  e.preventDefault()
})

...
<li onClick={onClick} ...

It's also generally a good idea to always wrap your callbacks using useCallback() - this way your callbacks won't need to be re-wired on every render - because on every render you generate new closure.

If you don't wrap your callbacks with 'useCallback()', behind the scene react will be replacing event handler on every render, similarly to:

element.removeEventListener('click', oldClosure)
element.addEventListener('click', newClosure)

also, I'm not sure but looking at your code, I think you might be wanting to put onClick on <a> element not on <li>

  • Related