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
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 (
)
}
}
export default Component