React onClick Example and Tutorial

January 2, 2017

Reasons Why Your React onClick Event Isn't Firing

  • You aren't using an arrow function or you forgot to bind the onClick event handler this.eventHandler = this.eventHandler.bind(this) in the constructor
  • You forgot the event argument in eventHandler(event)
  • When calling the function inside the onClick attribute, you wrote onClick={eventHandler} instead of onClick={this.eventHandler}.

Link to Codepen

How To Add A Class With React onClick

The following snippet adds the class red when the button is clicked.

Things to note:

  • Don't forget to use className instead of class with JSX. Example: <div className="myclass"></div>.

Adding a Class vs Setting the Class with this.setState

What if you already have a class associated with a

and you just want to add a class with an onClick event? See this discussion about adding classes in ReactJS.

React onClick Link Event

Triggering an onClick event for links is fundamentally the same as for buttons.

<a href="javascript:void(0)" onClick={this.eventHandler}>{this.state.toggle ? 'Click me' : 'Successfully clicked!'}</a>

Triggering Multiple Functions onClick

To accomplish this you just need to call other functions inside your eventHandler() function.

class extends React.Component {
  anotherFunction() {
    console.log("Another function was called!");
  }
  eventHandler(event) {
     this.anotherFunction();
     this.setState((prevState) => ({
       toggle: !prevState.toggle
     }))
   }
 }

But don't forget to bind both method classes within the constructor:

this.eventHandler = this.eventHandler.bind(this);
this.otherFunction = this.otherFunction.bind(this);