Tutorial: Events

Let's dive right in. This example component renders a div that responds to click events.

Syntax

var BannerAd = React.createClass({
  onBannerClick: function(evt) {
    // codez to make the moneys
  },

  render: function() {
    // Render the div with an onClick prop (value is a function)
    return <div onClick={this.onBannerClick}>Click Me!</div>;
  }
});

That's it. You add onXXX to the nodes you want. Notice how the value of the prop is a function. For the list of supported events, see the official event system docs.

But inline handlers?

First XML in my JavaScript and now inline handlers. I promise that React doesn't hate the world. We know that inline onclicks are a bad practice in HTML, but not in React. We'll see why soon in the deep dive section.

Exercise: Events

This one's a little trickier but you know everything you need. Remember that you can pass functions as props.

View Solution

Peek under the hood

We'll take a deeper look under the hood soon but for those of you who can't wait, the short answer is that React uses event delegation and listens for events at the root of the application. React keeps track of which rendered nodes have listeners. The synthetic event system implements its own bubbling and calls the appropriate handlers.

Next Article

State

We'll learn about the other half of what makes React components special.

Liked this?

Subscribe

Subscribe for a range of articles from React basics to advanced topics such as performance optimization and deep dives in the React source code.