How to call preventDefault () before a synthetic event is processed?

I have the following function in the React component that runs when a link is clicked:

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

    const doIt = await checkSomething();

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

The problem is that by the time it reaches the e.preventDefault()synthetic event is being processed. So, how can I tell the browser not to follow the link if it is clicked, when some logic is needed to calculate this solution and before the synthetic event is processed?

+4
source share
4 answers

One way to handle this is to use it preventDefault, and when the action is complete and you need to route, call the routing logic yourself usinghistory.push()

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

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

React-router

+2

.

, URL- , .
(currying) .
, IIFE.


JavaScript ( ):

const el = document.getElementById("link");


function onLinkClick() {
  console.log('doing some stuff..');
  for(let i = 0; i < 500; i++){
  	console.log(`doing more stuff #${i}`);  
  }
  return function(e) {
    // this will trigger with the actuall event (note this is an IIFE)
    console.clear();
  }();
}

el.addEventListener('click', onLinkClick);
#big {
  min-height: 950px;
}
<div id="big">
  <a id="link" href="#test">Click to get to the bottom of the page</a>
</div>

<div id="test">Bottom of page</div>
Hide result

:

class App extends React.Component {

  onClick = (e) => {
    console.log('doing some stuff..');
    for (let i = 0; i < 500; i++) {
      console.log(`doing more stuff #${i}`);
    }
    return ((e) => {
      //console.log(e, "inner function")
      console.clear();
    })(e)
  }

  render() {
    return (
      <div>
        <div style={{ height: '950px' }}>
          <a href="#test" onClick={this.onClick} >Click to get to the bottom of the page</a>
        </div>

        <div id="test">Bottom of page</div>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Hide result
+2

preventDefault , . , .

MDN Event.preventDefault Notes, , , - .

preventDefault() , , , , .

SO: event.preventDefault . await , event.preventDefault() await. promises .

:

If you want to access the properties of events in an asynchronous way, you must call event.persist () in the event, which will remove the synthetic event from the pool and resolve the link to the event, which will be saved by the user code.

Here is the SyntheticEvent Documentation .

+1
source

Have you tried using promises and .then ():

// Async/Await
const asyncGreeting = async () => 'Greetings';

// Promises
const promiseGreeting = () => new Promise(((resolve) => {
  resolve('Greetings');
}));

asyncGreeting().then(result => console.log(result));
promiseGreeting().then(result => console.log(result));

You should be able to control default prevention ();

0
source

Source: https://habr.com/ru/post/1691636/


All Articles