React allows you to handle user events, such as mouse clicks and keyboard input, using event handlers. Event handlers are functions that get called when a specific event occurs on a component, like a button click or a form submission. Here’s an example of how to handle a button click event:
jsx class Button extends React.Component { handleClick = () => { console.log("Button clicked!"); }; render() { return ; } }
In this example, we’re defining a `Button` component with a `handleClick` method that logs a message to the console when the button is clicked. We’re then passing this method as a prop to the `
You can also pass arguments to event handlers using arrow functions. Here’s an example of how to pass an argument to a click event handler:
jsx class Greeting extends React.Component { handleClick = (name) => { console.log(`Hello, ${name}!`); }; render() { return (
);
}
}
In this example, we’re defining a `Greeting` component with a `handleClick` method that takes a `name` argument and logs a message to the console. We’re then using arrow functions to pass different names to the `handleClick` method when the user clicks on the corresponding buttons.
You can also prevent default behavior on certain events, such as form submissions, using the `preventDefault()` method. Here’s an example of how to prevent a form submission from reloading the page:
jsx class Form extends React.Component { handleSubmit = (event) => { event.preventDefault(); console.log("Form submitted!"); }; render() { return (); } }
In this example, we’re defining a `Form` component with a `handleSubmit` method that prevents the default form submission behavior using the `preventDefault()` method. We’re then using the `onSubmit` attribute to call the `handleSubmit` method when the user submits the form.
Overall, event handling is a crucial part of building interactive user interfaces in React, and it allows you to create components that respond to user input and update in real-time.