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.
Handling events in 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.
function MyButton() { function sayHello() { alert('Hello!'); } return <button onClick={sayHello}>Say Hello</button>; }
function InputLogger() { function logInput(event) { console.log(event.target.value); } return <input type="text" onChange={logInput} />; }
function InlineHandler() { return <button onClick={() => alert('Clicked!')}>Click me</button>; }
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.
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;
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.
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.