You are here: Home / Topics / Chapter 4: Event Handling

Chapter 4: Event Handling

Filed under: React JS Tutorial on 2025-11-20 07:35:40

Introduction to Event Handling


In React, event handling is used to respond to user interactions such as clicks, hover, and form submissions. Events are handled using event handlers, which are functions that are called when an event occurs.

Handling Events


To handle an event in React, you can use the `onEventName` syntax, where `EventName` is the name of the event (e.g., `onClick`, `onMouseOver`, etc.). Here's an example:


import React from 'react';

function Button() {
 function handleClick() {
   console.log('Button clicked!');
 }

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

In this example, the `handleClick` function is called when the button is clicked.

Event Handler Functions


Event handler functions receive an event object as an argument, which contains information about the event. Here's an example:


import React from 'react';

function Button() {
 function handleClick(event) {
   console.log(event.target); // The button element
   console.log(event.type); // 'click'
 }

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

Binding Event Handlers


When using event handlers in class components, you need to bind the event handler function to the component's context using the `bind` method:
import React, { Component } from 'react';

class Button extends Component {
 constructor(props) {
   super(props);
   this.handleClick = this.handleClick.bind(this);
 }

 handleClick() {
   console.log('Button clicked!');
 }

 render() {
   return <button onClick={this.handleClick}>Click me!</button>;
 }
}

Alternatively, you can use an arrow function to bind the event handler:


import React, { Component } from 'react';

class Button extends Component {
 handleClick = () => {
   console.log('Button clicked!');
 }

 render() {
   return <button onClick={this.handleClick}>Click me!</button>;
 }
}

Example Code
Here's an example of a simple React app that handles events:


import React, { useState } from 'react';

function Counter() {
 const [count, setCount] = useState(0);

 function handleIncrement() {
   setCount(count + 1);
 }

 function handleDecrement() {
   setCount(count - 1);
 }

 return (
   <div>
     <p>Count: {count}</p>
     <button onClick={handleIncrement}>+</button>
     <button onClick={handleDecrement}>-</button>
   </div>
 );
}

 

Here's a practice exercise:

Create a simple React app that displays a form with a text input and a submit button. When the form is submitted, log the input value to the console.

Hint: Use the `onSubmit` event handler to handle form submissions. Use the `event.preventDefault()` method to prevent the default form submission behavior.


About Author:
A
Ankit Singh     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.