Categories
Uncategorized

Handling events in React.JS

Event handling in React is slightly different from Javascript.

1) In Javascript, we write:

<button onclick="activateLasers()">
Activate Lasers
</button> 

however in React, we write: 

<button onClick={activateLasers}>
Activate Lasers
</button>

2) In React, we can not return false, it can be done by calling ‘PreventDefault’ explicitly. In javascript: 

<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>

In react, we use ‘PreventDefault’:

function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}

return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}


The reason developers use React.JS is that it allows to break javascript functions to a deeper level for making complex functionalities, rather than making changes in overall structure of project. Jquery has a simple Toggle function(), same functionality can be added through Javascript using if and else conditions. Let us see how to create toggle functionality in React.JS:

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}

render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}

ReactDOM.render(
<Toggle />,
document.getElementById('root')
);

First of all an ES6 class named ‘Toggle’ has been created. It contains constructor() function, handleClick() function and render() function. Finally this class has been rendered using ReactDOM.render(). Let us know about them one by one:

1) constructor() function, is used to initialize local state of the component through this.state object. A constructor function also binds event handler methods that occur in component. 

So this makes it clear that the initial state of function has been set to true through:

this.state = {isToggleOn: true};

In Javascript, methods are bound by default. In React, it need to be bound manually. If we miss binding here, then, when we call function on button like onClick={this.handleClick}, then it will be undefined. So to bind it, we write following code: 

this.handleClick = this.handleClick.bind(this);

(Various binding methods has been explained in end of this page.)

2) The handleClick() function uses this.setState which is only way to update initial state. The !prevState.isToggleOn is opposite of isToggleOn, ( ! = opposite ) so it sets isToggleOn to false. So we used it as shown below:

handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}

 3) In the end we used the render() function which holds the visible part of the button. It is a simple button coding in HTML <button> ON </button> , inside it, it holds ternary operator of javascript, which says if this.state.isToggleOn is true, then show ‘ON’ text, else show ‘OFF’ text. It also holds another javascript function ‘onclick()’ which calls function handleClick() in a react way onClick={this.handleClick}. All this combined makes following code: 

render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}

Whole of the above code in ‘toggle’ class gets rendered through ReactDOM.render() as shown below:

ReactDOM.render(
<Toggle />,
document.getElementById('root')
);


Binding done above in constructor() function above through code. It is one method of binding:

this.handleClick = this.handleClick.bind(this);

Binding can be done in various ways. Let us study them one by one:

1) We can remove above binding code and write the handleClick() function in following way:

handleClick = () => {

Overall handleClick() function will look like: 

handleClick =() => {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}

2) Another method is if we use e and arrow key in render() function directly onClick={(e)=>this.handleClick(e)} , like:

render() {
return (
<button onClick={(e)=>this.handleClick(e)}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}

3) Another method is if we write ‘bind’ and ‘this’ onClick={this.handleClick.bind(this)} in render() function directly. Overall render() function code look like:

render() {
return (
<button onClick={this.handleClick.bind(this)}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}


If we have a row ‘id’ as well, then we can write binding method as:

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>

<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

Both of the above two button codes for binding give correct output.

Leave a Reply

Your email address will not be published. Required fields are marked *