React Events

React Events

An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the same events as HTML: change, mouse over, click, etc.

React has its event handling system, which is much similar to handling the events on DOM elements. This React event handling system is called as Synthetic events.

React Events

There are some differences between handling the events with react and handling the events with DOM. These are:

  1. The naming convention of the React event is in camelCase instead of lowercase.

For example:

onClick instead of onclick.

  • With JSX, a function is treated as an event handler instead of a string. 

For example:

React event handlers are written in the curly braces:

onClick= {show} instead of onclick=”show()”.

  • Declaration of Event in HTML:
 
  • Declaration of Event in React:
 
  • In react, we cannot return the false for preventing the default behavior, rather than we have to call preventDefault event for preventing the default behavior.

For example:

  • In HTML, for preventing the default link behavior to open a new page, we write as:

Hello
 
  • In React, it can be written as:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You visited a Link.');
}
return (

Hello

);
}  

Event Handler Example

The below example defines how to generate an event in React.

import React, { Component } from 'react';
class App extends React.Component {
hello() {
alert("!!!!! Hello World !!!!!");
}
render() {
return (

Event Handler Example

Click the following button to generate the event

); } } export default App;

Output:

Event Handler Example

Once you click on the button, you will get the following output.

Event Handler Example

Child Event

When we require updating the state of the parent component from its child, we can create an event handler (updateState) inside the parent component, and it will pass as a prop (updateStateProp) to the child component where we can call it.

import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'Hello World!!!!'
} 
this.updateState = this.updateState.bind(this);
};
updateState() {
}
render() {
return (
); } } class Hello extends React.Component { render() { return (

Child Event Example

{this.props.myDataProp}

); } } export default App;

Output:

After compiling the above code, you will get the following output:

Child Event

Once you click on the button, you will get the following output:

Child Event



ADVERTISEMENT
ADVERTISEMENT