0

Why do event handlers need to bind with the constructor while render and other methods do not require the same in react?

You may see here in the below code that for handlesubmit I need to bind it with the constructor but I don't need to do the same with api method. Can someone explain to me the reason behind it?

Thank you

class App extends Component{
constructor (props){ 
    super(props);

  this.state={
    users:[],
    loading:false
  };
  this.handleSubmit = this.handleSubmit.bind(this); 
}

api(){ 
  this.setState({
    loading: true
  }) 
    axios('https://api.randomuser.me/')
  .then(respond => this.setState({ 
    users: [...this.state.users, ...respond.data.results], 
    loading: false
  }))
}
handleSubmit(e){ 
  e.preventDefault(); 
  this.api();
}

UNSAFE_componentWillMount(){
this.api();
}

render(){
let {loading,users} = this.state; 
console.log("run")
return <div className = "App"> 
 <form onSubmit = {this.handleSubmit}> 
  <input type="submit" value= "Refresh" /> 
  </form>
{!loading 
  ? (users.map( user => 
  <div key = {user.id.value}> 
  <h2> {user.name.first} </h2>
  <p>{user.email}</p>
  </div>
)) : (<Loading/>)} 
</div>;
}
}

export default App;

1 Answers1

0

So that their references don't change on each re-render.

  this.handleSubmit = this.handleSubmit.bind(this); 

You can just use arrow function

handleSubmit = (e) => { 
  e.preventDefault(); 
  this.api();
}

why do you need to bind a function in a constructor

See more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

voice
  • 830
  • 10
  • 17