Event handling in React

Event handling in React is how you capture and respond to user interactions such as clicks, typing, mouse movements, form submissions, and more. React handles events in a synthetic event system, which wraps the browser’s native events to provide consistent behavior across different browsers.

Here’s a clear breakdown:


Key Points About Event Handling in React

  1. CamelCase Syntax: Event names use camelCase, unlike HTML where they are lowercase. <button onClick={handleClick}>Click Me</button>
  2. Functions as Handlers: You pass a function as the event handler, not a string like in HTML. // Correct <button onClick={handleClick}>Click</button> // Incorrect <button onClick="handleClick()">Click</button>
  3. this Binding (for class components): If you’re using class components, you often need to bind this in the constructor or use arrow functions.

Example 1: Function Component

import React, { useState } from 'react';

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

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

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

export default App;

Explanation:

  • onClick={handleClick}: When the button is clicked, React calls the handleClick function.
  • The function updates the state using setCount, which re-renders the component with the new value.

Example 2: Event Object

React provides a synthetic event object with useful properties.

function App() {
  const handleClick = (event) => {
    console.log("Button clicked!");
    console.log(event.type); // "click"
    console.log(event.target); // <button> element
  };

  return (
    <button onClick={handleClick}>Click Me</button>
  );
}

export default App;

Example 3: Form Handling

function App() {
  const [name, setName] = React.useState('');

  const handleChange = (event) => {
    setName(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault(); // Prevent page reload
    alert(`Submitted name: ${name}`);
  };

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

export default App;

Explanation:

  • onChange updates the state as the user types.
  • onSubmit captures the form submission and prevents the default browser behavior.

In short, event handling in React is similar to HTML/JS, but with JSX syntax and synthetic events, making it more consistent and easier to manage across components.

Leave a Reply