Beginnerprogrammer Beginnerprogrammer - 1 month ago 27
React JSX Question

ReactJs print value of input field

Iam trying to print instantly my input value in the render function. But now I am looking at this link: https://facebook.github.io/react/docs/state-and-lifecycle.html

Here they use an constructor with super(props) and than set the state.

but when I try this:

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>
);
}
}


It throws me this error:
Uncaught TypeError: Cannot read property 'state' of undefined


How do I solve this.

Answer

when 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 :)