Events

Differences from HTML

  • camelCase events, rather than lowercase

  • pass a function as the event handler, rather than a string

<!-- HTML -->
<button onclick="activateLasers()">
  Activate Lasers
</button>

becomes

//React
<button onClick={activateLasers}>
  Activate Lasers
</button>

PreventDefault

call preventDefault rather then return false

<!-- HTML -->
<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>

becomes

e is a synthetic event handling cross-browser compat

Usage

Pass functions into event handlers

  • use event.persist(); if you access async because react event objects are recycled so could be different

Bind()

[method].bind(this) is a vanilla JS function that sets the this ptr of the function to the arg passed needed when passing ft like in callbacks rather than calling it

Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.

Not using bind()?

Passing arg to Event Handler

Equivalent using arrow fts and bind respectively, e will be 2nd arg in both

Last updated