0
0
Reactframework~5 mins

Handling events in React

Choose your learning style9 modes available
Introduction

Handling events lets your React app respond when users click buttons, type in inputs, or do other actions. It makes your app interactive and fun to use.

When you want to run code after a user clicks a button.
When you need to update something as the user types in a form.
When you want to react to mouse movements or keyboard presses.
When you want to show or hide parts of the page based on user actions.
Syntax
React
function MyComponent() {
  function handleClick(event) {
    // code to run on click
  }

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

Use camelCase for event names like onClick, onChange.

Pass a function to the event attribute, not a string.

Examples
This button shows an alert when clicked.
React
function MyButton() {
  function sayHello() {
    alert('Hello!');
  }

  return <button onClick={sayHello}>Say Hello</button>;
}
This input logs what you type to the browser console.
React
function InputLogger() {
  function logInput(event) {
    console.log(event.target.value);
  }

  return <input type="text" onChange={logInput} />;
}
You can use an inline arrow function for simple handlers.
React
function InlineHandler() {
  return <button onClick={() => alert('Clicked!')}>Click me</button>;
}
Sample Program

This component shows a button and a count. Each time you click the button, the count increases by one and updates on the screen.

It uses useState to keep track of clicks and onClick to handle the button press.

Also includes an aria-label for accessibility.

React
import React, { useState } from 'react';

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

  function handleClick() {
    setCount(prevCount => prevCount + 1);
  }

  return (
    <div>
      <button onClick={handleClick} aria-label="Increment count">Click me</button>
      <p>You clicked {count} times</p>
    </div>
  );
}

export default ClickCounter;
OutputSuccess
Important Notes

Always use camelCase event names in React, like onClick, not lowercase.

Pass a function reference or an inline function, not a string like in HTML.

Remember to use accessibility attributes like aria-label for better user experience.

Summary

React uses camelCase event names and functions to handle events.

Event handlers let your app respond to user actions like clicks and typing.

Use useState to update your UI when events happen.