ReactJS – bind() method

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to pass arguments to a function in a React application

React has a predefined bind() method which we can use to pass the arguments to a function in the class based components.

Syntax

this.func.bind(this,[args...])

It accepts two parameters, this keyword and the arguments. 'this' keyword is used to pass the reference to that function while the second parameter is passed as arguments to the function.

Example

In this example, we will build a React application that passes the arguments to a function when a button is clicked.

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(){
      super();
      this.state = {
         name: 'Rahul Bansal',
         email: null,
      };
   }

   fetch = (email) => {
      this.setState({ email: email });
   };
   render() {
      return (
         <div>
            <h1>Name: {this.state.name}</h1>
            <h1>{this.state.email ? 'Email: ${this.state.email}' : null}</h1>
            <button onClick={this.fetch.bind(this, 'qwerty@gmail.com')}>
               Fetch Email
            </button>
         </div>
      );
   }
}
export default App;

Output

raja
Published on 18-Mar-2021 11:30:11
Advertisements