Handling Events
In React, handling events is similar to handling events in vanilla JavaScript, but with a few differences.
Event Handling Syntax
In React, event handlers are specified as attributes in JSX, just like other HTML attributes. The naming convention for event handlers is camelCase instead of lowercase.
For example, to handle the onClick
event for a button, you can define an event handler function and pass it as a prop to the button component:
1// Handle onClick event
2const handleClick = () => {
3 // Code logic for handling the event
4};
5
6// JSX
7return (
8 <button onClick={handleClick}>Click me!</button>
9);
In the example above, when the button is clicked, the handleClick
function will be called to handle the event.
Event Object
In React, the event object passed to event handlers is a synthetic event, which is a cross-browser wrapper around the native event.
The synthetic event provides properties and methods that are compatible with different browsers, making it easier to write cross-platform event handling code.
Prevent Default
To prevent the default behavior of an event in React, you can call the preventDefault()
method on the event object.
For example, to prevent the default form submission behavior when a submit button is clicked, you can do the following:
1// Handle form submit event
2const handleSubmit = (event) => {
3 event.preventDefault();
4 // Code logic for handling the form submission
5};
6
7// JSX
8return (
9 <form onSubmit={handleSubmit}>
10 {/* form fields */}
11 <button type="submit">Submit</button>
12 </form>
13);
In the example above, the handleSubmit
function prevents the default form submission behavior by calling preventDefault()
on the event object.
Handling events is an important part of building interactive applications in React. By using event handlers and understanding the event object, you can create dynamic and responsive user interfaces.
xxxxxxxxxx
// Handle onClick event
const handleClick = () => {
// Code logic for handling the event
};
// JSX
return (
<button onClick={handleClick}>Click me!</button>
);