Binding Event Handler And Method As Props In React

Introduction

 
In the previous article, we learned about destructuring of props and state and the basics of event handling in React. In this article, we will learn about binding event handlers and the number of ways binding can be done and also methods that can be used as props.
 

Binding Event Handlers

 
In the previous article, we reviewed what Event handler is in React. Now in this article, we will go into detail about how to bind event handlers with React. React provides 4 ways to bind the event handlers.
 

Binding in Render() method

 
In React, we can attach events using the bind method in a render function. To call bind method in render function, we will use .bind(this) in render() function.This is an ES6 class, a plain JavaScript function, therefore, it inherits bind() from function prototype. When using any event inside JSX, this keyword will point to the class instance to which it is called. Using this method may cause performance issue as the function is reallocated on every render. The performance issues may not be visible in small React applications but it may cost very much in bigger React applications.
 
For example.
  1. import React from 'react';  
  2.   
  3. class EventBinding extends Component{  
  4.          constructor(props){  
  5.                super(props)  
  6.                this.state = {  
  7.                      message : "Testing"  
  8.                }  
  9.          }  
  10.   
  11.         clickHandler(){  
  12.                this.setState({  
  13.                          message : "Tested"  
  14.                })  
  15.          }  
  16.   
  17.         render(){  
  18.                return(  
  19.                   <div> {this.state.message}  
  20.                            <button onClick={this.clickHandler.bind(this)}>Test</button>  
  21.                   </div>  
  22.         );  
  23.     }  
  24. }  
  25.   
  26. export default EventBinding;  
Now, export the EventBinding in App.js.
  1. import React,{Component} from "react";  
  2. import "./App.css";  
  3. import logo from "./logo.svg";  
  4. import EventBinding from "./Components/EventBinding";  
  5. class App extends Component {  
  6.        render(){   
  7.             return (  
  8.                  <div className="App">  
  9.                         <img src={logo} className="App-logo" alt="logo"/>  
  10.                         <EventBinding></EventBinding>  
  11.                  </div>  
  12.             );  
  13. }  
  14. export default App;  
Now, the output will be displayed as below.
 
Binding Event Handler And Method As Props In React
 
On click of a button, the text is changed.
 
Binding Event Handler And Method As Props In React
 

Arrow function body

 
This approach uses an arrow function body in the render method
 
Update the code as shown below.
  1. <button onClick={() => this.clickHandler}>Test</button>  
This will display the output same as above.
 

Binding in Constructor

 
In React, we have another way to bind events, i.e., using binding in the constructor, as shown below.
 
As per the above example, we will define the event binding in the constructor.
  1. import React from 'react';  
  2.   
  3. class EventBinding extends React.Component{  
  4.             constructor(props){  
  5.                   super(props)  
  6.                   this.state = {  
  7.                         message : "Testing"  
  8.                    }  
  9.                   this.clickHandler = this.clickHandler.bind(this)  
  10.             }  
  11.   
  12.             clickHandler(){  
  13.                     this.setState({  
  14.                         message : "Tested"  
  15.                     })  
  16.             }  
  17.   
  18.             render(){  
  19.                         return(  
  20.                              <div> {this.state.message}<br/>  
  21.                              <button onClick={this.clickHandler}>Test</button>  
  22.                              </div>  
  23.               );  
  24.             }  
  25. }  
  26.   
  27. export default EventBinding;  
 The output will be the same as shown below.
 
Binding Event Handler And Method As Props In ReactBinding Event Handler And Method As Props In React
Using this approach will bind event once in the constructor so it is a better approach from the above 2 and it doesn't rerender on every call.
 

Class property approach

 
This approach is an experimental feature. This approach uses the class property as an arrow function. Using class properties, you can simplify your handler functions. This will create a new function on every render.
 
For example.
  1. import React from 'react';  
  2.   
  3. class EventBinding extends React.Component{  
  4.              constructor(props){  
  5.                     super(props)  
  6.                     this.state = {  
  7.                           message : "Testing"  
  8.                     }  
  9.               }  
  10.   
  11.            clickHandler = ()=>{  
  12.                   this.setState({  
  13.                           message:"Tested"  
  14.                    })  
  15.             }  
  16.   
  17.            render(){  
  18.                  return(  
  19.                       <div> {this.state.message}<br/>  
  20.                       <button onClick={this.clickHandler}>Test</button> </div>  
  21.             );  
  22.        }  
  23. }  
  24.   
  25. export default EventBinding;  
This will also display the same output as displayed above.
 

Higher Order Component (HOC)

 
A Higher Order Component is an advanced technique in React for reusing component logic in our applications. HOC’s are a pattern that emerged from React Composition nature. The HOC is not a part of React API.
 
The HOC is a function that takes a component and returns a new Component. This plays an important role for reusability.
 
For example.
  1. import React from'react';  
  2. functionadd (x, y) {  
  3.    return x + y  
  4. }  
  5. function addFive (x, addReference) {  
  6.    return addReference(x, 5)  
  7. }  
  8. function ParentComponent(){  
  9.    return <div>{addFive(10, add)}</div>  
  10. }  
  11. export default ParentComponent; 
The above code will be displayed as below.
 
Binding Event Handler And Method As Props In React
 
The above example is just a small demo for Higher Order Component. We can create a much more complex application using Redux which we will learn further in the series. 
 

Method as props 

 
This technique is used to share code between React components using a prop whose value is a function. This is mainly used for reusable code in React. It is used to share the state of one component to another component that needed the same state.
 
For example, creating a MasterComponent.js file in the React app.
 
This document has been composed with the free HTML converter. Click here to give it a try.
  1. import React from 'react';  
  2. class ParentComponent extends React.Component{  
  3.        constructor(props){  
  4.               super(props);  
  5.               this.state ={  
  6.                      master : 'master',  
  7.                      message : ""  
  8.               };  
  9.               this.greetHandler = this.greetHandler.bind(this);  
  10.        }  
  11.   
  12.        greetHandler(){  
  13.               this.setState({  
  14.                      message : `This is ${this.state.master}`  
  15.               });  
  16.        }  
  17.   
  18.        render(){  
  19.               return(  
  20.                      <div>  
  21.                           <p>{this.state.message}</p>  
  22.                           <button onClick={this.greetHandler}>Click Me</button>   
  23.                      </div>  
  24.        )  
  25.    }  
  26. }  
  27. export default ParentComponent;  
Now, import ParentComponent in App.js.
  1. import React,{Component} from "react";  
  2. import "./App.css";  
  3. import logo from "./logo.svg";  
  4. import EventBinding from "./Components/EventBinding";  
  5. class App extends Component {  
  6.        render(){   
  7.               return (  
  8.                      <div className="App">  
  9.                          <img src={logo} className="App-logo" alt="logo"/>  
  10.                          <EventBinding></EventBinding>  
  11.                      </div>  
  12.               );  
  13. }  
  14. export default App;  
Import ParentComponent in App.js and use as tag. Then, the above code will be displayed as below in the browser.
 
Binding Event Handler And Method As Props In ReactBinding Event Handler And Method As Props In React
 
Now, let's create a child component named ChildComponent.js.
  1. import React from 'react';  
  2.   
  3. function ChildComponent() {  
  4.       return(  
  5.             <div>  
  6.                   <button>Call Parent Component</button>  
  7.             </div>  
  8.       )  
  9. }  
  10.   
  11. export default ChildComponent;  
Import ChildComponent.js in ParentComponent. The updated code is given below.
  1. import React from 'react';  
  2. import ChildComponent from './ChildComponent';  
  3. class ParentComponent extends React.Component{  
  4.         constructor(props){  
  5.                 super(props);  
  6.                 this.state ={  
  7.                         master : 'master',  
  8.                         message : ""  
  9.                 };  
  10.                 this.greetHandler = this.greetHandler.bind(this);  
  11.         }  
  12.           
  13.         greetHandler(){  
  14.                 this.setState({  
  15.                         message : `This is ${this.state.master}`  
  16.                 });  
  17.         }  
  18.   
  19.         render(){  
  20.                 return(  
  21.                         <div>  
  22.                                <p>{this.state.message}</p>  
  23.                                <button onClick={this.greetHandler}>Click Me</button>   
  24.                                 <ChildComponent/>  
  25.                         </div>  
  26.                  )  
  27.         }  
  28. }  
  29. export default ParentComponent;  
This code will display the output as below.
 
Binding Event Handler And Method As Props In React
 
Now, just modify the code a little bit to call the greetHandler() method from the child as well as parent components.
 
ParentComponent.js
  1. import React from 'react';  
  2. import ChildComponent from './ChildComponent';  
  3. class ParentComponent extends React.Component{  
  4.           
  5.         constructor(props){  
  6.                 super(props);  
  7.                 this.state ={  
  8.                         master : 'master',  
  9.                         message : ""  
  10.                 };  
  11.                 this.greetHandler = this.greetHandler.bind(this);  
  12.         }  
  13.   
  14.         greetHandler(childName){   
  15.                 if(typeof(childName) == 'object'){  
  16.                         this.setState({  
  17.                                 message : `This is ${this.state.master} `  
  18.                         });  
  19.                 }  
  20.                 else{  
  21.                         this.setState({  
  22.                                 message : `This is ${this.state.master} from ${childName}`  
  23.                         });  
  24.                 }   
  25.         }  
  26.           
  27.         render(){  
  28.                 return(  
  29.                         <div>  
  30.                                 <p>{this.state.message}</p>  
  31.                                 <button onClick={this.greetHandler}>I am Parent, Click Me</button>   
  32.                                 <ChildComponent greetChild={this.greetHandler}/>  
  33.                         </div>  
  34.          )  
  35.     }  
  36. }  
  37. export default ParentComponent;  
ChildComponent.js
 
The result will be displayed as below.
 
Binding Event Handler And Method As Props In React
 
On click of the first button, which is available in the parent component, the output will be displayed as below.

Binding Event Handler And Method As Props In React
 
On click of the second button, which is available in the child component, the output will be displayed as below.
 
Binding Event Handler And Method As Props In React
 

Conclusion

 
In this article, we learned a number of ways binding for event handlers can be done. Also, we learned how a method can be used as property. Now in the next article, we will learn about conditional rendering and list rendering in React.
 
Author
Priyanka Jain
0 9.6k 894.8k
Next » Conditional Rendering And List Rendering In React