React Events

Handling Events

Adding Events

React handles events in the DOM same as regular HTML. React event handler functions are written in square brackets and the event itself is written in camelCase. For example,

In HTML:

<button onclick=”increase()”> Increase </button>

In React:

<button onClick={increase}> Increase </button>

There are various event handlers in react such as onClick, onMouseover, onChange, onSubmit, onMousedown etc.

Binding ‘this’ in React

In class components, the ‘this’ keyword is not defined by default, regular functions call refer to the object that called the function such as a button, the global window, or a paragraph tag. If you use regular functions instead of arrow functions in ES6, you must bind ‘this’ keyword to the method.

This is not a React thing, it is a basic Javascript rule. An example is given below:

import React, { Component } from "react";

class LieDetector extends Component {
  constructor() {
    super();
    this.state = { isALie: false };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange = () =>  {
    this.setState((prevState) => ({isALie: !prevState.isALie }));
  }

  render() {
    return (
      <div>
        <p>He {this.state.isAlie ? "lies" : "says the truth"} </p>
        <button onClick={this.handleChange}>
          {this.state.isAlie ? "truth" : "lie"}
        </button>
      </div>
    );
  }
}

export default LieDetector

In the example above, ‘this’ is bond to the object handling it which is a button. The state is then changed accordingly to either true or false when the button is clicked. If you forget to bind ‘this’ the function call will result in ‘undefined’.

Putting it together

Let’s create a React code that logs the console when the mouse pointer hovers an element and also when it leaves the element, to do this we will use the event handlers; onMouseover and onMouseLeave:

import React from 'react'

const App = () => {
  const hover = () => {
      console.log('Hovered!')
   }
   const leave = () => {
      console.log('Left!')
   }

   return (
      <div onMouseOver={hover} onMouseLeave = {leave} style= {{backgroundColor: 'green', color: 'white'}}>
         <p>Hover and Leave!</p>
      </div>
   )
}

export default App

Result: