Skip to content

React Events

New Course Coming Soon:

Get Really Good at Git

Learn how to interact with events in a React application

React provides an easy way to manage events. Prepare to say goodbye to addEventListener.

In the previous article about the State you saw this example:

const CurrencySwitcher = props => {
  return (
    <button onClick={props.handleChangeCurrency}>
      Current currency is {props.currency}. Change it!
    </button>
  )
}

If you’ve been using JavaScript for a while, this is just like plain old JavaScript event handlers, except that this time you’re defining everything in JavaScript, not in your HTML, and you’re passing a function, not a string.

The actual event names are a little bit different because in React you use camelCase for everything, so onclick becomes onClick, onsubmit becomes onSubmit.

For reference, this is old school HTML with JavaScript events mixed in:

<button onclick="handleChangeCurrency()">...</button>

Event handlers

It’s a convention to have event handlers defined as methods on the Component class:

class Converter extends React.Component {
  handleChangeCurrency = event => {
    this.setState({ currency: this.state.currency === '€' ? '$' : '€' })
  }
}

All handlers receive an event object that adheres, cross-browser, to the W3C UI Events spec.

Bind this in methods

Don’t forget to bind methods. The methods of ES6 classes by default are not bound. What this means is that this is not defined unless you define methods as arrow functions:

class Converter extends React.Component {
  handleClick = e => {
    /* ... */
  }
  //...
}

when using the property initializer syntax with Babel (enabled by default in create-react-app), otherwise you need to bind it manually in the constructor:

class Converter extends React.Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(e) {}
}

The events reference

There are lots of events supported, here’s a summary list.

Clipboard

Composition

Keyboard

Focus

Form

Mouse

Selection

Touch

UI

Mouse Wheel

Media

Image

Animation

Transition

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: