How to use props and state inside a function declaration in a class component?

66 views Asked by At

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

1

There are 1 answers

0
Bill On BEST ANSWER

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>

        )
    }
}