Handling Events in React

In this tutorial, we will learn how to handle events in React App.

Event Handling Overview

In React, event handling allows you to handle user interactions, such as button clicks, form submissions, or mouse movements, within your application. 

Event handling in React follows a similar pattern to standard JavaScript event handling but with some differences: 
  • React events are written in camelCase syntax: onClick instead of onclick
  • React event handlers are written inside curly braces: onClick={shoot}  instead of onClick="shoot()"

React Event Handling Example

1. Create a new React app

Open your terminal or command prompt and navigate to the directory where you want to create your React app. Run the following command to create a new React app using create-react-app:
npx create-react-app my-app
This command creates a new directory named my-app and sets up a basic React project structure inside it.

2. Navigate into the app directory

Move into the newly created app directory by running the following command:
cd my-app

3. Start the development server

Start the development server by running the following command in the terminal:
npm start
This command starts the development server and opens your React app in the browser. You should now see Bootstrap styles being applied to your app.

4. Example 1: Create EventHandlingComponent Functional Component

Create EventHandlingComponent.js file and within this file, create a functional component named EventHandlingComponent with the below code:

import React, { useState } from 'react';

const EventHandlingComponent = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  const handleReset = () => {
    setCount(0);
  };

  return (
    <div>
      <h2>Event Handling Example</h2>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
      <button onClick={handleReset}>Reset</button>
    </div>
  );
};

export default EventHandlingComponent;
In this example, we have a functional component called EventHandlingComponent. It maintains a count state using the useState hook. The component renders a heading, a paragraph displaying the current count, and two buttons.

The handleClick function is called when the "Increment" button is clicked. It updates the count state by incrementing it by 1 using the setCount function provided by the useState hook.

The handleReset function is called when the "Reset" button is clicked. It sets the count state back to 0.

Both the handleClick and handleReset functions are attached to the buttons using the onClick event handler attribute. When the buttons are clicked, the corresponding functions are executed, resulting in state updates and re-rendering of the component.

5. Example 2: Event handling in React for a Form

Create FormExample.js file and within this file, create a functional component named FormExample with the below code:
import React, { useState } from 'react';

const FormExample = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: ''
  });

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(formData);
    // You can perform further actions like submitting the data to a server
    // or resetting the form fields.
  };

  return (
    <div>
      <h1>Form Example</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="name">Name:</label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
          />
        </div>
        <div>
          <label htmlFor="email">Email:</label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
          />
        </div>
        <div>
          <label htmlFor="message">Message:</label>
          <textarea
            id="message"
            name="message"
            value={formData.message}
            onChange={handleChange}
          ></textarea>
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default FormExample;
In this example, we have a functional component called FormExample that manages the form data using the useState hook. The form has input fields for name, email, and a textarea for a message. 

The handleChange function is triggered when any input field's value changes. It updates the corresponding field's value in the formData state using the setFormData function. It uses the name attribute of the input field to identify the field being updated. 

The handleSubmit function is triggered when the form is submitted. It prevents the default form submission behavior and logs the form data to the console. You can perform further actions in this function, such as submitting the data to a server or resetting the form fields. 

By using the onChange event handler on each input field, we associate the handleChange function with the field, allowing it to update the form data as the user types. 

Finally, the onSubmit event handler on the form element triggers the handleSubmit function when the form is submitted by clicking the "Submit" button.

Comments