Home > Software design >  class method does not work with onClick event in react
class method does not work with onClick event in react

Time:10-24

I was trying to update my state variable when the button is clicked on my page. But I see that I cannot use react class component methods. Here is the minimum reproducible example.

import React, { Component } from 'react'

export class Name extends Component {
    constructor(){
        super();
        this.state = {
            name : "Farhan Ahmed"
        }
    }
    clickMe() {
        this.setState({
            name:"Ahmed Farhan"
        })
    }

    render() {
        return (
            <div>
                <h1>{this.state.name}</h1>
                <button className="btn btn-success" onClick={this.clickMe}>Change Text</button>
            </div>
        )
    }
}

export default Name

Error :

TypeError: Cannot read properties of undefined (reading 'setState')

But when I replace the same with arrow function it works for me.

My question is why didn't regular class method work in this case why do I need to replace the same with arrow function?

CodePudding user response:

In the docs found here https://reactjs.org/docs/handling-events.html this error is explained, along with possible solutions. If you're not using the experimental "public class fields syntax" the docs refer to, you can either bind your function, or use an arrow function:

With bind

onClick={this.clickMe.bind(this)}

Arrow function

onClick={() => this.clickMe()}

These are the most common (that I've seen personally), but the docs provide more solutions as well.

CodePudding user response:

When you try to access this keyword without binding the function, this keyword is undefined. so, you need to either bind that function in constructor or use an arrow function syntax which ensures this is bound within that function. You can check documentation of bind method method and Arrow Function

CodePudding user response:

Button is not clicked, but function will run while the component is rendering.

onClick={this.clickMe}  

And this;

onClick={() => this.clickMe} 

Function only works when the buttons are clicked.

Read this: https://beta.reactjs.org/learn/responding-to-events

  • Related