In Reactjs, events are actions triggered by elements in the application, such as a button click, input text changes, form submissions, mouse movements, and many more.
Here’s how events work in Reactjs:
1. Inline Event Handlers: In most cases, React uses inline handlers for events. These are specified as part of the attributes of the elements that we define in the render method.
```
```
1. Synthetic Events: React wraps the browser’s native event into synthetic events. Synthetic events have the same interface as native events in the browser, but they work consistently across all browsers. They are named using camelCase, rather than the lowercase that is customary in HTML.
1. Event Handlers and this Context: In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called. This is not specific to React. You have to be careful about the meaning of this in JSX callbacks and prefer the use of arrow functions or binding in the constructor.
```
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// ‘this’ is accessible here
}
/*
OR, you can use an arrow function like this:
*/
handleClick = () => {
// ‘this’ is accessible here
}
```
1. Event Pooling: For performance reasons, the synthetic events system in React reuses event objects between different events. Therefore, accessing properties of the event object within an asynchronous function will return null because the event object is returned back to the pool.
To avoid this, you can call `event.persist()`, which will remove the synthetic event from the pool and allow references to the event.
Note: It’s important to call `preventDefault` synchronously, due to the event pooling in React. If it is required to use an event in an asynchronous way, `event.persist` must be called.