React Events
- An event is an action that can be triggered either by a user interaction or a system-generated occurrence. Examples of events include a mouse click, page load, key press, window resize, and other similar interactions.
- React uses its own event handling system, called Synthetic Events, which closely resembles handling events on DOM elements. Synthetic Events are a cross-browser wrapper around the browser's native events.
Handling events in React has some syntactic differences compared to DOM event handling. These include:
- React event names are written in camelCase rather than lowercase.
- In JSX, a function is passed as the event handler instead of a string. For example:
<button onclick="showMessage()">
Hello Gocourse
</button>
Event declaration in React:
<button onClick={showMessage}>
Hello Gocourse
</button>
In React, we cannot return false to prevent the default behavior. Instead, we must explicitly call the `preventDefault` method on the event to stop the default action. For example:
Example
- In the following example, we use a single component and attach an onChange event. This event triggers the `changeText` function, which returns the company name.
- Sure! Here's another example where the user can enter their age, and it will display the entered age dynamically:
```javascript
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
age: ''
};
}
changeAge(event) {
this.setState({
age: event.target.value
});
}
render() {
return (
<div>
<h2>Simple Age Input Example</h2>
<label htmlFor="age">Enter your age: </label>
<input
type="number"
id="age"
onChange={this.changeAge.bind(this)}
/>
<h4>You entered: {this.state.age}</h4>
</div>
);
}
}
export default App;
```
This example is similar to the previous one, but instead of the company name, the user inputs their age. The entered age will be displayed dynamically.
Output
When you run the above code, the following output will be displayed.
After entering the name in the text box, the output will be displayed as shown in the screen below.