0

I want to know the real reason behind the behavior difference which happens when we use normal function vs arrow function.
So below is my render function of class component:

render() {
    console.log('App Render called');

    const updateName = () => {
      this.setState({ name: 'App Component updated' })
    }

    return (
      <>
        <div>Component Name: {this.state.name}</div>
        <button className="btn btn-sm btn-primary" onClick={() => updateName()}>name update</button>
      </>
    )
  }

So with above definition on onClick current name update works perfectly fine.
while if i use normal function rather than [ES6] arrow function in the updateName function, then i get error:  typeerror-cannot-read-properties-of-undefined-reading-setstate

render() {
    console.log('App Render called');

    function updateName() {
      this.setState({ name: 'App Component updated' })
    }

    return (
      <>
        <div>Component Name: {this.state.name}</div>
        <button className="btn btn-sm btn-primary" onClick={() => updateName()}>name update</button>
      </>
    )
  }

Can someone please help me to know the exact reason creating this issue.?

Bimlendu Kumar
  • 224
  • 2
  • 15

0 Answers0