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
You need to either bind the function or use arrow functions
() => {}
forthis
to work.See doc: https://reactjs.org/docs/handling-events.html
or