Reaction event

Learn how to interact with events in React applications

React provides a simple way to manage events. Ready to say goodbyeaddEventListener.

In the previous article on countries, you saw the following 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, it’s just like the old oneJavaScript event handler, Except this time you want to use JavaScript instead of HTML to define everything, and you want to pass functions instead of strings.

The actual event name is different because in React, you use camelCase for everything, soonclickbecomeonClick,onsubmitbecomeonSubmit.

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

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

Event handler

By convention, the event handler is defined as a method of the Component class:

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

All handlers will receive event objects obeyed across browsersW3C UI event specification.

BindingthisIn the method

Don't forget the binding method. By default, methods of ES6 classes are not bound. What does it meanthisUnless you define the method as an arrow function, it is undefined:

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

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

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

Activity reference

Many events are supported, this is a summary list.

Clipboard

works

keyboard

Focus

form

mouse

Selection

Touch

User Interface

Mouse wheel

media

image

cartoon

transition

Download mine for freeResponse Handbook


More response tutorials: