0

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?

3 Answers 3

8

You have 2 issues :

  1. You bound handleChange but you forgot to bind handleKey in the constructor .

Better is to not use manual binding , but to use arrow function instead.

  handleKey = (e)  => {
   //....... ( See second issue )
  }

  handleChange = (e) => {
    this.setState({value: e.target.value});
  }
  1. Second issue is how to know "enter" key is pressed . Use

     const keyCode = e.keyCode || e.which;
     if (keyCode === 13) {
       // You code when "Enter" is pressed
     }
    

The demo below should work fine.

    class Terminal extends React.Component {
      // no need explicit constructor !
      state = { value: '', cmds: [] };

      handleKey = e => {
        const keyCode = event.keyCode || event.which;
        if (keyCode === 13) {
          this.setState(({ cmds, value }) => ({
            value: '',
            cmds: [value, ...cmds]
          }));
        }
      };

      handleChange = e => {
        this.setState({ value: e.target.value });
      };

      render() {
        return (
          <div>
            <div>
              <span>My Prompt: > </span>
              <input
                type="text"
                value={this.state.value}
                onKeyUp={this.handleKey}
                onChange={this.handleChange}
              />
            </div>
            {this.state.cmds.map(cmd =>
              <div>
                {cmd}
              </div>
            )}
          </div>
        );
      }
    }

    ReactDOM.render(<Terminal />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />

4
  • 2
    I was just about to comment this and agree arrow function is the better and cleaner way to go.
    – Jouke
    Nov 13, 2017 at 22:04
  • i would add that using an arrow function is not a black magic and it will help in this case only because it will use a lexical context for this, which is the class instance in this case.
    – Sagiv b.g
    Nov 13, 2017 at 22:12
  • @abdennour-toumi You're right. The first issue is now obvious to me. About the second issue... as far as I can see from developer.mozilla.org/en-US/docs/Web/Events/keyup the key event value should be preferred but is unimplemented in Firefox. So the solution you provided is mostly for legacy reaons? Nov 13, 2017 at 22:13
  • 1
    @RobertStrauch. Yes it is polyfill , work in any browser. By the way, See the code snippet that I put, You will be happy .. I complete the solution for you 😅. Nov 13, 2017 at 22:15
2

just change thease:

 onChange={this.handleChange}
 onKeyUp={this.handleKey}

to

 onChange={this.handleChange = this.handleChange.bind(this)}
 onKeyUp={this.handleKey = this.handleKey.bind(this)}`
0

You have to bind the function to the context of the class.

<input type="text" value={this.state.value} onKeyUp={this.handleKey.bind(this)} onChange={this.handleChange.bind(this)} />
1
  • From what I can observe it seems to work in that case. I thought I had already bound it in the constructor. However it seems as if I missed binding the handleKey function. Nov 13, 2017 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.