Reputation: 2941
React how to get the props value from a constructor to a method.
constructor(props) {
super(props)
}
handleSubmit(event) {
event.preventDefault()
}
How access the props value inside the handleSubmit method?
Upvotes: 0
Views: 68
Reputation: 930
You need to initialise state in constructor and then use that in your function.
constructor(props){
super(props);
this.state = {data:'Hey'};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault()
console.log(this.state.data);
}
Upvotes: 0
Reputation: 29749
Simply access it via this.props
. You need to bind the handler method to the correct scope:
constructor(props) {
super(props)
}
handleSubmit = (event) => {
event.preventDefault()
console.log(this.props)
}
The answer of Hemerson Carlin is basically the same, but with another approach on how to bind the method. I find my approach a bit more appealing since you don't need to explicitly write down the bind statement.
Upvotes: 0
Reputation: 7424
You have to bind
the event handler in the constructor
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit() {
console.log(this.props)
}
Upvotes: 2