Getting Started with React - Lesson #16

Listening for User Events with React

Every interactive website will listen for user interactions. React makes this easy since we can declaratively bind user events right into our JSX.

An example of listening for a click on a button element:

jsx
<button onClick={() => alert('button clicked!')}>
    Go!
</button>

We pass a function into the onClick handler and run an alert. This can be anything we want to do in JavaScript.

Note: The syntax for event listeners in react is to lowercase on and capitalize the event name.

We can use any of the HTML DOM Events with our event listeners. The popular ones are:

  • click → onClick
  • mouseover → onMouseOver (for hovering)
  • mouseleave → onMouseLeave
  • change → onChange (for input fields)
  • submit → onSubmit (for forms)
  • drag → onDrag
HTML DOM Events List

In the example above, we included our function directly in our JSX markup. This is a fine practices when the task we need to do is smaller and ideally on one line.

Personally I will only use an inline function if it is using a setState. I like to know that all my logic is in named functions which makes my code more readable.

jsx
<button onClick={() => setActive(true)}>
    Turn On
</button>

For 95% of cases though, I'll use a named function.

To use a named function, you will create the function in your component. You can then reference that function inside your event handler.

jsx
function App() {
    
    // our named function
    function saySomethingCool() {
        alert('i am cool!');
    }

    // our jsx template
    return (
        <button onClick={saySomethingCool}>Do It</button>
    );
}

Also note, these two are the same and both valid:

jsx
<button onClick={() => saySomethingCool()}>Do It</button>

// functional javascript ftw!
<button onClick={saySomethingCool}>Do It</button>

It all comes down to preference. I have seen many people use the "handle{Event}" naming scheme. For instance, if we had a button with an onClick, we would see the named function called handleClick.

This is a fine practice, but don't be set on it. If you can name your function something more specific and descriptive, go ahead and do that.

jsx
// this is ok for understanding your code
<button onClick={handleClick}>Do It</button>

// now we know exactly whats going to happen
<button onClick={alertTheUser}>Do It</button>

React will wrap all events with a SyntheticEvent to help with cross-browser compatibility. For our uses, it doesn't matter since the SyntheticEvent has the same interface as the browser native event.

In order to get the event from the handler, we will pull the event out of the handler.

jsx
// get the input fields value
<input type="text" onChange={e => console.log(e.target.value)} />

We can listen for a form's submit event like so:

jsx
<form onSubmit={handleSubmit}>

</form>

But we will want to use a preventDefault on the form so that HTML doesn't refresh the browser.

jsx
function App() {
  function handleSubmit(event) {
    // prevent the form from refreshing the page
    event.preventDefault();
    
    // process the form here
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* form goes here */}
    </form>
  )
}

Handling user events in React is quickly done by binding the event handler directly onto the JSX element. The hard work happens after we've captured the user event and you figure out how you want to create your functions and work with the user input!

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.