DEV Community

Cover image for Event Handling in React
Anil
Anil

Posted on

Event Handling in React

Event handling in React involves using event handlers to respond to user interactions such as clicks, key presses, form submissions, etc. Here's an example demonstrating event handling in a React component:

import React, { useState } from 'react';

const EventHandling = () => {
  // State to track button click count
  const [clickCount, setClickCount] = useState(0);

  // Event handler for button click
  const handleClick = () => {
    setClickCount(clickCount + 1);
  };

  // Event handler for form submission
  const handleSubmit = (event) => {
    event.preventDefault();
    alert('Form submitted!');
  };

  return (
    <div>
      <h2>Event Handling</h2>
      {/* Button with onClick event handler */}
      <button onClick={handleClick}>Click me</button>
      <p>Click count: {clickCount}</p>

      {/* Form with onSubmit event handler */}
      <form onSubmit={handleSubmit}>
        <input type="text" placeholder="Enter your name" />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default EventHandling;


Enter fullscreen mode Exit fullscreen mode

In this example:

We use the useState hook to create a state variable clickCount to track the number of times a button is clicked.
We define the handleClick function as an event handler for the button click event (onClick). Inside this function, we update the state to increment the click count.
We define the handleSubmit function as an event handler for the form submission event (onSubmit). Inside this function, we prevent the default form submission behavior using event.preventDefault() and show an alert.
The handleClick and handleSubmit functions are passed as event handlers to the respective elements (<button> and <form>) using the onClick and onSubmit attributes.
When the button is clicked or the form is submitted, React calls the respective event handler function, which updates the UI accordingly.
This is a basic example of event handling in React. You can use similar patterns to handle other types of events such as onChange for input elements, onKeyDown for key presses, etc.

github
website

Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js

Top comments (0)