Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - how to trigger preventDefault() before the synthetic event is recycled?

I have the following function within a React component which is run when a link is clicked:

onClick(e, { name }) {
    e.stopPropagation();

    const doIt = await checkSomething();

    if (doIt) {
        e.preventDefault();
        doSomethingElse();
    }
}

Problem is that by the time e.preventDefault() is reached the synthetic event is recycled. So, how do I tell the browser not to follow the link if it is clicked, when some logic is needed to calculate this decision and before the synthetic event is recycled?

like image 766
JoeTidee Avatar asked Jan 02 '18 19:01

JoeTidee


1 Answers

One way to handle this would be to use preventDefault and when the action is complete and you need to route, call the Routing logic yourself using history.push()

onClick(e, { name }) {
    e.stopPropagation();
    e.preventDefault();
    const doIt = await checkSomething();

    if (doIt) {
        doSomethingElse();
    } else {
        this.props.history.push('/pathToRoute');
    }
}

Check this answer on how to Programmatically navigate with React-router

like image 182
Shubham Khatri Avatar answered Sep 30 '22 17:09

Shubham Khatri