11.C. Write a program for responding to events.

Introduction to Events


Events in React.js are how user interactions—like clicks, typing, form submissions, and mouse movements—are handled in a React application. React uses a synthetic event system, which wraps native browser events to provide a consistent behavior across different browsers. Event names are written in camelCase (e.g., onClick, onChange), and instead of passing a string, you pass a function as the event handler. This makes event handling more predictable and easier to manage within components.

Handling events in React is tightly connected to component state and re-rendering. When an event occurs, you typically update the component’s state using hooks like useState, and React efficiently updates only the parts of the UI that need to change. This approach encourages clean separation between UI and logic, improves maintainability, and enables building interactive, responsive user interfaces with minimal direct manipulation of the DOM.


Write a program for responding to events. 


App.js


import React, { useState } from "react";

function App() {

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

  const [name, setName] = useState("");


  // Event handler for button click

  const handleClick = () => {

    setCount(count + 1);

  };


  // Event handler for input change

  const handleChange = (e) => {

    setName(e.target.value);

  };


  return (

    <div style={{ padding: "20px" }}>

      <h2>React Event Handling Example</h2>


      <button onClick={handleClick}>

        Clicked {count} times

      </button>


      <br /><br />


      <input 

        type="text" 

        placeholder="Enter your name"

        onChange={handleChange}

      />


      <p>Hello, {name}</p>

    </div>

  );

}


export default App;


Comments

Popular posts from this blog

Experiment 1: Node.js

Experiment 10: ReactJS – Render HTML, JSX, Components – function & Class

Experiment 6: ExpressJS – Routing, HTTP Methods, Middleware