event
argument in eventHandler(event)
onClick={eventHandler}
instead of onClick={this.eventHandler}.
Link to Codepen
The following snippet adds the class red when the button is clicked.
Things to note:
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
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>
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);