VITSOLS
2025-11-06
What Are Events in React?
Events in React are actions that occur as a result of user interaction — such as clicking a button, typing in an input box, or submitting a form. React provides its own event system, which is consistent across browsers and follows the W3C specifications.
// Example: Handling a Button Click function ClickExample() { function handleClick() { alert('Button was clicked!'); } return ( <button onClick={handleClick}>Click Me</button> ); }
Binding Events and Passing Parameters
You can also pass parameters to event handlers. This allows components to perform specific actions based on context or user input.
// Example: Passing Parameters in Event Handlers function UserGreeting({ name }) { function greetUser(userName) { alert(`Hello, ${userName}!`); } return ( <button onClick={() => greetUser(name)}> Greet User </button> ); }
Handling Form Events
Forms are another common use case for event handling. React allows you to handle form input changes using the onChange event.
// Example: Handling Input Change function FormExample() { const [name, setName] = React.useState(''); function handleChange(event) { setName(event.target.value); } return ( <div> <input type="text" value={name} onChange={handleChange} placeholder="Enter your name" /> <p>Hello, {name}!</p> </div> ); }
Real-Time Use of Event Handling
- Form validation and dynamic updates as the user types.
- Interactive UI elements like dropdowns, modals, and accordions.
- Live search and filtering features.
- Tracking user activity (clicks, navigation, etc.) for analytics.
camelCase (e.g., onClick instead of onclick), and event handlers are passed as functions, not strings.