React JS Events: To handle events with react elements is as same as handling events on DOM elements with few differences. The React events are named in Camelcase than lowercase. With JSX, you can pass a function as an event handler rather than a string.
React JS Events
Sample Example in HTML
<button onclick="activateLasers()"> Activate Lasers </button>
is slightly different in React:
<button onClick={activateLasers}> Activate Lasers </button>
preventDefault Example
The other difference is that you cant return false in react to prevent the default behavior. For this, you must call preventDefault explicitly. For example, in HTML you can prevent default link behavior which opens in a new page and the code is as follows
HTML Example for Default Link
<a href="#" onclick="console.log('The link was clicked.'); return false"> Click me </a>
In React, this can be used
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); }return ( <a href="#" onClick={handleClick}> Click me </a> ); }
In the above source code, “e” is the synthetic event that is specified as per W3C so no need to consider cross-browser compatibility. In react, you no need to call addEventListerner() to DOM element add listener after creation.
Toggle Component
You can simply specify a listener when the element is initially rendered. In ES6 class it must contain the common pattern for event handler for the method in the class while you define a component. For example, here we are providing a Toggle component that has a button that contains ON and OFF states.
Toggle Component Example
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(state => ({ isToggleOn: !state.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); } } ReactDOM.render( <Toggle />, document.getElementById('root') );
NOTE: Try the source code on CodePen.
In JSX callbacks we must be careful about defining them. In java scripts, class methods are not bounded in case we forgot to bind them with this.handleClick and pass to onClick which is undefined when you actually called the function. This is not a React behavior, it is just how they function works in javascript. In any case, you prefer a method without bind(), such as
onClick={this.handleClick},
You must bind this method. In case calling bind disturbs you, which can be done in two ways i.e., public class field to bind callbacks.
class LoggingButton extends React.Component { // This syntax ensures `this` is bound within handleClick. // Warning: this is *experimental* syntax. handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
The above source code is enabled default in Create React App.the other methods, instead of class fields syntax is arrow function callback.
class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // This syntax ensures `this` is bound within handleClick return ( <button onClick={(e) => this.handleClick(e)}> Click me </button> ); } }
The problem with the above syntax is it is creating different callbacks every time the LoggingButton is provided. Most of the time this is ok but incase this callback has passed as a prop to lower components which might need extra specification. To avoid such a performance problem we can easily bind the callback in the constructor or in the class field syntax.
Passing Arguments to Event Handlers
Within the loop, we may want to pass an extra parameter to an event handler. For example, if the id is the row ID then the following could work
Passing Arguments to Event Handlers Example
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
The above-mentioned lines are equivalent which uses arrow functions and Function.prototype.bind. In above, both cases, the “e” argument in the React event is passed as the second argument after the ID element. With the help of an arrow function, we can pass it explicitly with further arguments bound automatically.