I'm taking my first steps with React and I struggle with setting and getting states of an input
element.
- The application shall render a simple
input
element without a submit button. - When pressing Enter the current value of the text field shall be written to the console.
So far I've added two event handlers for onKeyUp
(checking if Enter was pressed) and another for onChange
to output the text field's value.
This is my current code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
class Terminal extends React.Component {
constructor(props) {
super(props);
this.state = {value: ""};
this.handleChange = this.handleChange.bind(this);
}
handleKey(e) {
if (e.key === "Enter") {
console.log("Enter key pressed");
console.log(this.state.value);
}
}
handleChange(e) {
this.setState({value: e.target.value});
}
render() {
return (
<div>
<span>My Prompt: > </span>
<input type="text" value={this.state.value} onKeyUp={this.handleKey} onChange={this.handleChange} />
</div>
);
}
}
ReactDOM.render(
<Terminal />,
document.getElementById("root")
);
Pressing Enter is recognized but logging to the console gives me:
Uncaught TypeError: Cannot read property 'state' of undefined
at handleKey (index.js:24)
What am I missing here?