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;