I am trying to implement a simple react component which change name on clicking. I am getting the error Error - TypeError: this is undefined
while loading my page which has below react component. The error seems to be in the setState
line.
class Layer5 extends React.Component {
constructor(props) {
super(props);
this.state = {buttonstate: false};
}
componentDidMount() {
}
componentWillUnmount() {
}
handleClick(e) {
e.preventDefault();
this.setState({buttonstate: !this.state.buttonstate});
}
render() {
var icon = this.state.buttonstate ? 'images/image1.png' : 'images/image2.jpg';
return (
<div className="layer5">
<a href="#" onClick={this.handleClick}><img src={icon} ></img></a>
</div>
);
}
}
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>;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With