0

I can't understand why to use .bind() operation in the react applications. I noticed that most of the developers use it in their codes.And also without that operation i got errors. After adding that bind() operation successfully compile the code. but i don't know why to use that and what kind of thing done by that .bind() operation.(i got that code from the internet)

//App.js

 import React, { Component } from 'react';
    import logo from './resources/metro-library-3.jpg';
    import './App.css';
    import Table from './components/bookTable.js';
    import Footer from './components/footer.js';
    import Header from './components/header.js';

    class App extends Component {

        constructor(props){
            super(props); 
            this.setSelectedAuthor = this.setSelectedAuthor.bind(this);
            this.updateFooter = this.updateFooter.bind(this);

            this.state = {
                authors: [],
                selectedAuthor: "select author",
                footerBook: {
                    name: "",
                    author: ""
                }
            }

        }

        setSelectedAuthor(author){
            this.setState({
                selectedAuthor: author
            }, () =>{
                this.setState({selectedAuthor: author});
                console.log(this.state.selectedAuthor);
            })
             console.log(author);

        }

        updateFooter(book){
            this.setState({
                footerBook: book
            })
    }


    componentDidMount(){
        let url = 'http://localhost:8083/getAll';
        let auth = [];
        fetch(url).then(response => response.json()).then((data) => {
            data.bdata.map((book) =>{
                auth.push(book.author)
            })
            this.setState({
                authors: auth
            })
        })
    }
     render() {
    return (
      <div className="App">
          <select value={this.state.selectedAuthor} onChange={(e) => this.setSelectedAuthor(e.target.value)}>
              <option value="select author">Select Author</option>
              {
                  this.state.authors.map((author, key) =>
                      <option key={key} value={author}>{author}</option>
                  )
              }
          </select>
          <Table filterBook = {this.state.selectedAuthor} update = {this.updateFooter}/>
          <Footer book={this.state.footerBook}/>

      </div>
    );
     }
    }

    export default App;

//AppContainer.js

import React, {Component} from 'react';
import {BrowserRouter as Router} from 'react-router-dom';
import Route from 'react-router-dom/Route'
import App from '../App';
import Header from '../components/header.js';
import AddBooks from "../components/AddBooks";

class AppContainer extends Component{
    render(){
        return(
            <Router>
                <div>
                    <Route path = "/" component={Header}/>
                    <Route exact path = "/" component={App}/>
                    <Route exact path = "/addBook" component={AddBooks}/>
                </div>
            </Router>
        );
    }
}

export default AppContainer;
  • Possible duplicate of [why do you need to bind a function in a constructor](https://stackoverflow.com/questions/38334062/why-do-you-need-to-bind-a-function-in-a-constructor) – Sulthan Jun 07 '18 at 20:30
  • There are at least 3 other ways to do the same without `bind`. To understand why we have to `bind` means you have to understand how `this` works in Javascript functions. – Sulthan Jun 07 '18 at 20:30

2 Answers2

0

@Chamali Read this to know.

Binding functions

Bounded function in JavaScript is a function that is bounded to a given context. That means no matter how you call it, the context of the call will stay the same. The only exception is the new operator which always return a new context.

To create a bounded function out of the regular function, the bind method is used. bind method take context to which you want to bind your function as a first argument. The rest of arguments are arguments that will be always passed to such function. It returns a bounded function as a result. Let’s see an example:

function add(x, y) {
  this.result += x + y;
}

var computation1 = { result: 0 };
var boundedAdd = add.bind(computation1);

boundedAdd(1, 2); // `this` is set to `computation1`.
                  //  computation1 after call: { result: 3 }

var boundedAddPlusTwo = add.bind(computation1, 2);
boundedAddPlusTwo(4); // `this` is set to `computation1`.
                      // computation1 after call: { result: 9 }

Bounded function can’t be changed even by manually calling call and apply! See these examples:

var obj = { boundedPlusTwo: boundedAddPlusTwo };
obj.boundedPlusTwo(4); // `this` is set to `computation1`.
                       // even though method is called on `obj`.
                       // computation1 after call: { result: 15 }
var computation2 = { result: 0 };
boundedAdd.call(computation2, 1, 2); // `this` is set to `computation1`.
                                 // even though context passed to call is
                                 // `computation2`
                                 // computation1 after call: { result: 18 }

You are now equipped with this knowledge about the JavaScript. Let’s jump to your React component classes and see how function call context affects your code.

More details

React Binding Patterns: 5 Approaches for Handling this

Hope this clears your doubt.

Harshal Yeole
  • 4,812
  • 1
  • 21
  • 43
0

The TL:DR version is that it sets the App class method's context to be the same as the App class context. Uses: this.setState, this.props, etc...

Eric Hasselbring
  • 1,374
  • 1
  • 10
  • 18