React Events Tutorial

In this React Events Tutorial, you will learn how to work with events in your applicaion.

What are React Events?

  1. React events are a way to detect and respond to user interactions in React applications.
  2. React events are similar to DOM events, but they are normalized to provide a consistent cross-browser experience.
  3. To handle an event in React, you need to pass a function as a prop to the element that you want to listen for the event on.
  4. This function is called the event handler

For example, to handle a click event on a button, you would pass an onClick prop to the button element:

<button onClick={() => alert('You clicked me!')}>Click me!</button>

Passing Arguments to Event Handlers

  1. You may need to pass additional data to an event handler function.
  2. You can use arrow functions or bind to achieve this.
import React from 'react';

    class EventArgumentsComponent extends React.Component {
      handleClickWithArgument(arg) {
        console.log('Button clicked with argument:', arg);
      }
    
      render() {
        return (
          <button onClick={() => this.handleClickWithArgument('Hello')}>Click me</button>
        );
      }
    }
    

Using Event Objects

  1. When you define an event handler, React passes an event object containing information about the event.
  2. You can access properties like event.target, event.preventDefault(), and more.
import React from 'react';

    class EventObjectComponent extends React.Component {
      handleClick(event) {
        console.log('Button clicked on', event.target);
      }
    
      render() {
        return (
          <button onClick={this.handleClick}>Click me</button>
        );
      }
    }
    

Event Types in React

You can handle various types of events in React components, such as onClick, onChange, onSubmit, onMouseOver, and more.

onClick

This event is used to handle clicks on elements like buttons, links, or any other interactive components.

import React from 'react';

        function ClickExample() {
          const handleClick = () => {
            alert('Button clicked!');
          };
        
          return (
            <button onClick={handleClick}>Click Me</button>
          );
        }
        

onChange

The onChange event is used for input elements like text fields, checkboxes, and radio buttons to capture changes in their values.

import React, { useState } from 'react';

function InputExample() {
    const [text, setText] = useState('');

    const handleInputChange = (event) => {
    setText(event.target.value);
    };

    return (
    <input type="text" value={text} onChange={handleInputChange} />
    );
}

onSubmit

This event is commonly used with form elements to handle form submissions.

import React, { useState } from 'react';

function FormExample() {
    const [name, setName] = useState('');
    
    const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Form submitted with name: ${name}`);
    };

    return (
        <form onSubmit={handleSubmit}>
        <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        />
        <button type="submit">Submit</button>
        </form>
    );
}
    

onMouseOver and onMouseOut

These events are used to capture mouse hover and mouse leave actions on elements.

import React, { useState } from 'react';

function MouseExample() {
    const [isHovered, setHovered] = useState(false);

    const handleMouseOver = () => {
    setHovered(true);
    };

    const handleMouseOut = () => {
    setHovered(false);
    };

    return (
    <div
        onMouseOver={handleMouseOver}
        onMouseOut={handleMouseOut}
        style={{ backgroundColor: isHovered ? 'blue' : 'red' }}
    >
        Hover me
    </div>
    );
}
    

Synthetic events

  1. Synthetic events are a cross-browser wrapper around native DOM events.
  2. This means that you can write the same event handlers for all browsers, without having to worry about cross-browser compatibility.
function handleClick(event) {
    console.log(event.type); // "click"
}

<button onClick={handleClick}>Click me!</button>
  

This code will work in all browsers, even though the underlying native DOM event may be different in each browser.

Event bubbling

  1. Event bubbling is a process by which events propagate up the DOM tree.
  2. This means that if you click on a child element, the click event will also bubble up to the parent element and all of its ancestors.

    <button>Click me!</button>
</div>
const div = document.querySelector("div");

div.addEventListener("click", function(event) {
    console.log("Div clicked!");
});

const button = document.querySelector("button");

button.addEventListener("click", function(event) {
    console.log("Button clicked!");
});

When you click on the button, the following output will be logged to the console:

Event capturing

  1. Event capturing is the opposite of event bubbling.
  2. It allows you to listen for events on an element before they are propagated up the DOM tree.
<div>
    <button>Click me!</button>
</div>
const div = document.querySelector("div");

div.addEventListener("click", function(event) {
    console.log("Div clicked!");
}, true); // Capture phase

const button = document.querySelector("button");

button.addEventListener("click", function(event) {
    console.log("Button clicked!");
});

You will see the below output on your console.