React provides a way to handle user interactions such as clicks, form submissions, and other events using event handlers. These handlers work similarly to JavaScript event listeners but are optimized for React’s virtual DOM.
1. Handling Events in React
Key Points:
- Event handlers in React are written as camelCase (e.g.,
onClick
, onChange
).
- Handlers are passed as functions, not strings (e.g.,
onClick={() => alert('Clicked!')}
).
Common Event Handlers
- Click Events: Triggered when an element is clicked.
- Input Events: Triggered when input fields change.
- Form Events: Triggered during form submission.
Handling Click Events
function ClickHandler() {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
function InputHandler() {
const handleChange = (event) => {
console.log(event.target.value);
};
return <input type="text" onChange={handleChange} />;
}
function FormHandler() {
const handleSubmit = (event) => {
event.preventDefault(); // Prevents default form submission behavior
alert('Form submitted!');
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
2. Event Binding and Passing Data with Event Handlers
Event Binding
In React, event handlers automatically bind to the component instance, so you usually don’t need explicit binding as in class components. However, in class components, you can bind methods in three ways:
…