I'm trying to print instantly my input value in the render function.
In the documentation of the concept of state and lifecycle in a React ponent, I see the use of a constructor
with a super(props)
as well as this.state
.
I get the error below when trying same;
Uncaught TypeError: Cannot read property 'state' of undefined
Below is my code;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: ''
};
};
handleChange(event) {
this.setState({
text: event.target.value
});
};
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.text}.</h2>
<input type="text" onKeyUp={this.handleChange} />
</div>
);
}
}
How can I fix it?
I'm trying to print instantly my input value in the render function.
In the documentation of the concept of state and lifecycle in a React ponent, I see the use of a constructor
with a super(props)
as well as this.state
.
I get the error below when trying same;
Uncaught TypeError: Cannot read property 'state' of undefined
Below is my code;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: ''
};
};
handleChange(event) {
this.setState({
text: event.target.value
});
};
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.text}.</h2>
<input type="text" onKeyUp={this.handleChange} />
</div>
);
}
}
How can I fix it?
Share Improve this question edited Jan 22, 2020 at 6:55 nyedidikeke 7,6788 gold badges47 silver badges63 bronze badges asked Oct 24, 2016 at 17:15 SireiniSireini 4,26213 gold badges55 silver badges96 bronze badges 1- 2 this.handleChange=this.handleChange.bind(this) in constructor – Burak Karasoy Commented Oct 24, 2016 at 17:28
4 Answers
Reset to default 3when you call a function like that, it is called by the window, not by your react object.
To make the function be bound to your react object (and have the ability to use the setState method, you need to use this:
onKeyUp={this.handleChange.bind(this)}
this
will bind it to your react object :)
You have to bind this
to your event handler like this:
<input type="text" onKeyUp={this.handleChange.bind(this)} />
Working Example: https://codepen.io/shanedaugherty/pen/ALwAzL
this.handleChange = this.handleChange.bind(this);
You can bind it like this in constructor and it will work, as you have to bind this to your react function.
You use value as an attribute.
value={this.state.text}
OR