React Events

React has the same events as in HTML like click, hover, mouseover, change etc. React events are always written in camelCase syntax. Here's an example:


//Event Declaration in Plain HTML
<button onclick="clickHandler()">Click Me</button>
//Event Declaration in React JSX
<button onClick={clickHandler}>Click Me</button>


Event Handlers

A good approach is to put the event handler as a method inside the component Class. Here's an example:


import React from 'react'

class FirstComponent extends React.Component {

  constructor(){
    super()
    //Binding the 'this' keyword
    this.clickHandler = this.clickHandler.bind(this)
  }

  clickHandler(){
    alert('Button Clicked!');
  }

  render(){
    return (
    <button onClick={this.clickHandler}>Submit</button>

    )
  }
}


The this keyword should represent the component that own the method, that's why arrow functions are used.

You must bind this in the constructor method.


Passing Arguments to a function

A simple way of sending arguments is to use an anonymous arrow function. Let's check an example:


import React from 'react'

class FirstComponent extends React.Component {
  constructor(){
    super();
  }


  clickHandler(e){
    alert('Button Clicked with value ' + e);
  }

  render(){
    return (
    <button onClick={() => this.clickHandler('data')}>Submit</button>

    )
  }
}