React Event Handling: Building Interactive User Interfaces
Master event handling in React to build interactive and dynamic user interfaces. This tutorial covers handling common events (clicks, key presses, etc.), using synthetic events, managing event propagation, and creating responsive and engaging user experiences.
Handling Events in React Applications
Events are actions triggered by user interactions (clicks, key presses) or system events (page load, window resize). React's event handling system, using synthetic events, simplifies cross-browser compatibility.
Key Differences in React Event Handling
- Camel Case Naming: React event names use camel case (e.g.,
onClick
instead ofonclick
). - Function Handlers: Event handlers are JavaScript functions, not strings. You pass the function directly to the event attribute (e.g.,
onClick={myHandler}
). - Preventing Default Behavior: To prevent default actions (like link navigation), you must explicitly call
event.preventDefault()
within your event handler. Simply returning `false` doesn't work like it does in plain HTML.
Example: Handling a Click Event (Simple Button)
Simple Click Handler
const MyButton = () => {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
};
Example: Preventing Default Link Behavior
Preventing Default Link Behavior
const MyLink = () => {
const handleClick = (event) => {
event.preventDefault();
console.log('Link clicked!');
};
return <a href="/my-link" onClick={handleClick}>Click Me</a>;
};
Example: Handling onChange Event (Input Field)
onChange Handler for Input
import React, { useState } from 'react';
const App = () => {
const [companyName, setCompanyName] = useState('');
const handleChange = (event) => {
setCompanyName(event.target.value);
};
return (
<div>
<label htmlFor="companyName">Company Name:</label>
<input type="text" id="companyName" onChange={handleChange} />
<p>You entered: {companyName}</p>
</div>
);
};
export default App;