Back to Basics: Event Handling in React

William Le

What are event handlers, and why are they important? Event handlers make a website’s user experience a two-way street. You’re not just presented with nicely styled content… you can actually click, type, scroll it!

With React, event handling is easy to learn ⁠— especially if you already know how to accomplish it with standard HTML & JavaScript.

The Basics of React Event Handling

React is designed to be an easy transition for web developers. For example, creating a click event on a <button/> element could look like this with plain ‘ole HTML/JS:

index.html

<button id="foobutton" onclick="handleClick()">
  Click Me
</button>

index.js

// like this...
function handleClick() {
  alert('clicked.');
};

Accomplishing the same feature in React isn’t much different…

LoudButton.js

class LoudButton extends Component {
  handleClick = () => {
    alert('clicked.');
  }
  render() {
    return <button onClick={this.handleClick}>Click Me</button>
  }
}

There are 2 things to note…

Firstly:   camelCase vs lowercase

You probably noticed that the onClick attribute is camelCase instead of lowercase:

// React Code
<button
  onclick={handleClick()}     // 🙅 
  onClick={this.handleClick}  // 👌
>

This is pretty much 90% of the difficulty (or ease?) of learning React event handling. Well, there’s the curious way that handleClick is defined on the LoudButton class… but that’s more of a ES6 classes matter.

Secondly:   onClick only accepts a single function

Also this.handleClick wasn’t invoked. This contrasts with HTML/JS where onclick can be any arbitrary amount of JavaScript code:

<button onclick="handleClick(); const pizza = true; hazPizza(pizza);">
  Click Me
</button>

Additional Examples

So far we’ve only looked at click events, so let’s look at a few other events. Below is a code snippet that has 3 different events. It’s interesting to see how the event (or e argument) varies between different kinds of events:

class App extends Component {
  state = {
    inputText: '',
    mouseX: 0,
    mouseY: 0    
  }
  handleInput = (e) => {
    this.setState({inputText: e.target.value});
  }
  handleSubmit = () => {
    alert(`Quoteth Shakespeare, "You cad! ${this.state.inputText}"`);
  }
  handleMouse = (e) => {
    this.setState({ mouseX: e.screenX, mouseY: e.screenY });
  }
  render() {
    return (
      <div>

        <input
          onChange={this.handleInput}  {/* ⌨ input text */}
          value={this.state.inputText}
        />

        <form onSubmit={this.handleSubmit}>  {/* 📥 onsubmit */}
          <input value={this.state.inputText}/>
          <button type="submit">submit dis</button>
        </form>

        <div>
          <img
            src="doggo.jpeg"
            onMouseMove={this.handleMouse} {/* 🖱️ mouse movement */}
          />
          {this.state.mouseX}px / {this.state.mouseY}px
        </div>

      </div>
    )
  }
}

You’ll commonly see the word handle... used. This is merely a popular convention. For example, sometimes I’ll even mirror the prop name because I’m mildly OCD: <button onClick={this.onClick}/>. Just use whatever works!

The event argument

Notice the e argument. It’s automatically passed into the handler whenever the event is emitted. And depending on the kind of handler, sometimes the e argument has a slightly different API (eg., e.target.value vs e.screenX). If you haven’t written too many event handlers before… don’t worry about remembering the differences! You’ll start to remember the different e APIs as you use them.

Frankly, I only use ~3 different kinds of events with any kind of frequency. Just keep the React docs for Synthetic Events close-by for reference purposes. 😉


Try interacting with the demo!

W3C ✅

There’s A LOT of different kinds of events. React events emulated the W3C suite of events, which includes:

Visit the official React documentation on Event Handling for the full lowdown.

dominoes

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#