Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How I can implement e.preventDefault(); in useEffect?

Gentlemen, 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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading