Handling events in React.js

React JSJavascript LibraryFront End Technology

There are some syntactical differences in writing events but it is handled similar to DOM elements event handling.

The name of event handlers are written in camel case notations.

Example

Event in simple html −

<button onclick=”addUser()”>
   Add User
</button>
Event in React with jsx:
<button onClick={ addUser }>
   Add User
</button>

One of the difference is we do not write return false to prevent default behavior in React. Instead of that we specifically write event.preventDefault()

Example

In simple Html −

<button onclick=”console.log(‘Add user event clicked’); return false;”>
   Add User
</button>

In React it will be written as −

function addUser(event){
   event.preventDefault();
   console.log(‘Add user event clicked’);
}
<button onClick={ addUser }>
   Add User
</button>

Here event passed in React is synthetic and cross browser compatible. A method in ES6 can be an event handler. In JavaScript classes, methods are not bound to class by default. These methods in class should be declared in constructor with binding as shown below −

constructor(props){
   super(props);
   this.addUser=this.addUser.bind(this);
}

Or we can use arrow functions which will bind the methods automatically and then no need to add bind in constructor.

adduser=()=>{
}

If we are not using arrow functions , another alternative is to call the method and binding on React element itself −

addUser(){
}
<button onClick={ (e)=>{this.addUser(e)}}>
   Add User
</button>

The problem with above anonymous callback function is , it will be created every time button renders on the screen and it can affect performance.

Passing arguments to event handlers

<button onClick={ (e)=>this.addUser(id, e) }></button>

Or

<button onClick={ this.addUser.bind(this, id) }></button>

In the above event handler we are passing id as an argument and event object as second argument. The event argument is visible in arrow function but in second approach it is passed implicitly so we have not provided it.

raja
Published on 28-Aug-2019 11:57:24
Advertisements