0

I have a class component which has a function inside it named printData() I want to make use of the states and props variable of the class inside this function. How can I do it?

Code -

class ReadData extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: ""
        }
    }

    componentDidMount() {
        this.setState({ data: "Hello World" })
    }

    printData(props) {
        console.log(this.props.data)
    }

    render() {
        return (
            <div>
                <p>{this.state.data}</p>
                <button onClick={this.printData}>Print</button>
            </div>

        )
    }
}

The actual code is different. This is an example of what I am trying to implement. The console says

Uncaught (in promise) TypeError: Cannot read property 'props' of undefined

Using this.state.data instead of this.props.data also did not work.

Note: The render return successfully prints the desired output on the window. Also, I want to make use of Class component and not functional component

Amit Pathak
  • 1,145
  • 11
  • 26
  • 1
    Two options. Change the function to an arrow one: `printData = (props) => { ... }`. Older method is to bind it in the constructor, like Bill's answer – Jayce444 Sep 29 '20 at 09:13

1 Answers1

2

You need to either bind the function or use arrow functions () => {} for this to work.

See doc: https://reactjs.org/docs/handling-events.html

class ReadData extends Component {
    constructor(props) {
        super(props);
        // This binding is necessary to make `this` work in the callback
        this.printData = this.printData.bind(this);
    }

    printData() {
        console.log(this.props.data)
    }

    render() {
        return (
            <div>
                <p>{this.state.data}</p>
                <button onClick={this.printData}>Print</button>
            </div>

        )
    }
}

or

class ReadData extends Component {
    // Use arrow function to make `this` work in the callback
    printData = () => {
        console.log(this.props.data)
    }

    render() {
        return (
            <div>
                <p>{this.state.data}</p>
                <button onClick={this.printData}>Print</button>
            </div>

        )
    }
}
Bill
  • 764
  • 6
  • 14