TypeError: this is undefined - React JS, Javascript
import React from 'react'
class UsernameForm extends React.Component {
constructor(props) {
super(props)
this.state = {
username: ''
}
this.onchange=this.onChange.bind(this)
this.onSubmit=this.onSubmit.bind(this)
}
onChange(e) {
this.setState({
username: e.target.value
})
}
onSubmit(e) {
e.preventDefault()
this.props.onSubmit(this.state.username)
}
render() {
return (
<div>
<form onSubmit={this.onSubmit}>
<input type='text'placeholder='What is your username ?' onChange={this.onChange} />
<input type='submit' />
</form>
</div>
)
}
}
export default UsernameForm
I am getting error: this is undefined
So that i bind this on {this.onChange} see the solution below
import React from 'react'
class UsernameForm extends React.Component {
constructor(props) {
super(props)
this.state = {
username: ''
}
this.onchange=this.onChange.bind(this)
this.onSubmit=this.onSubmit.bind(this)
}
onChange(e) {
this.setState({
username: e.target.value
})
}
onSubmit(e) {
e.preventDefault()
this.props.onSubmit(this.state.username)
}
render() {
return (
<div>
<form onSubmit={this.onSubmit}>
<input type='text'placeholder='What is your username ?' onChange={this.onChange.bind(this)} />
<input type='submit' />
</form>
</div>
)
}
}
export default UsernameForm
Either a) create a property lexically closed over the instance (this
) using an arrow function or b) use .bind
.
Do one or the other. Either a)
class Layer5 extends React.Component {
constructor(props) {
super(props);
this.handleClick = e => {
e.preventDefault();
this.setState({buttonstate: !this.state.buttonstate});
};
}
}
or b)
render() {
const icon = this.state.buttonstate ? 'images/image1.png' : 'images/image2.jpg';
return <div className="layer5">
<a href="#" onClick={this.handleClick.bind(this)}>
<img src={icon} >
</img>
</a>
</div>;
}
}