Event handling is a crucial part of building dynamic applications in React. React provides a declarative way to handle events, making it easier to respond to user actions. While similar to vanilla JavaScript, React's event handling has some key differences.
By the end of this reading, you should be able to:
To add an event listener to an element, define a function to handle the event and associate it with the element’s event attribute.
function AlertButton() {
const showAlert = () => {
window.alert('Button clicked!');
};
return (
);
}
export default AlertButton;
In this example:
showAlert is the event handler.onClick attribute attaches the handler to the button.onClick instead of onclick).onClick={showAlert}) rather than calling it directly (e.g., onClick={showAlert()}).Many HTML elements have default behaviors when an event is triggered. For example, clicking a <button> inside a form submits the form, and clicking an <a> tag navigates to a new page.
function NoDefaultSubmitForm() {
const submitForm = (e) => {
e.preventDefault();
window.alert('Handling form submission...');
};
return (
);
}
export default NoDefaultSubmitForm;
In this example:
e.preventDefault() stops the default form submission.e is passed to the handler automatically.In this reading, you learned:
To continue learning, visit:
Understanding event handling in React is essential for building interactive applications. By managing event listeners and preventing default behaviors, you can create more dynamic and user-friendly interfaces.