In React, events are similar to how events work in regular DOM elements but have some key differences. Here are the main points to understand about handling events in React:
Event Naming
In React, event names are written in camelCase, rather than lowercase. For example, instead of using onclick
, you use onClick
.
Event Handlers
You pass event handlers as functions to React elements. For example:
<button onClick={handleClick}>Click Me</button>
The function handleClick
is the event handler and will be called when the button is clicked.
Prevent Default and Stop Propagation
To prevent the default action of an event, you call event.preventDefault()
within your event handler.
To stop the event from propagating (bubbling up), you call event.stopPropagation()
.
Passing Arguments to Event Handlers
You can pass additional arguments to your event handlers using arrow functions or the bind method. For example:
<button onClick={(e) => handleClick(e, id)}>Click Me</button>
Or
<button onClick={handleClick.bind(this, id)}>Click Me</button>
Common Events
Some common React events include:
- onClick for click events
- onChange for input field changes
- onSubmit for form submissions
- onMouseEnter and onMouseLeave for mouse events
- onKeyDown, onKeyPress, and onKeyUp for keyboard events
React’s approach to event handling is designed to be simple and intuitive, while also providing the flexibility needed for building complex user interfaces.
Example of Event Handling
import React from 'react';
function App() {
const handleClick = () => {
alert('Button clicked!');
};
return (
<div>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
export default App;
Event Handling in Class Components
import React, { StrictMode } from "react";
class App extends React.Component {
constructor(props) {
super(props);
//this.handleClick = this.handleClick.bind(this);
}
handleClick() {
alert('Button clicked!');
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
export default App;
.