I am following a beginner tutorial from Pluralsight, on form submit a value is passed to addUser
component method and I need to push userName to this.stat
@Vinit Raj's approaches works perfectly - tho i prefer to use the arrow function syntax like so.
<Form addUser={ () => this.addUser() }/>
Using an anonymous function like this, you don't need to bind it anywhere.
A good pattern is to bind a method to the class in the constructor function. See https://reactjs.org/docs/handling-events.html
import React from 'react'
import User from 'user'
import Form from 'form'
class Component extends React.Component {
constructor() {
super()
this.state = {
users: null
}
this.addUser = this.addUser.bind(this);
//bind functions which need access to "this"v in the constructor here.
}
// This is triggered on form submit in different component
addUser(userName) {
console.log(userName) // correctly gives String
console.log(this.state) // this is undefined
console.log(this.state.users) // this is the error
// and so this code doesn't work
/*this.setState({
users: this.state.users.concat(userName)
})*/
}
render() {
return (
<div>
<Form addUser={this.addUser}/>
</div>
)
}
}
export default Component
I had the same problem but my issue was trying to access this.state before the this.state = { ... }
call finished. Was doing something like this this.state = { ...this.function1() }
and function1 = () => { a: this.state.b }
. Hope this helps someone