Maksim
Maksim

Reputation: 99

React, having trouble getting event.key from onKeyPress input event

I'm having trouble getting event.key from input onKeyPress event, getting this error when i type in the input field - TypeError: Cannot read property 'key' of undefined

The plan is to update parent state when enter is pressed in child input component.

class ToDoList extends Component {
  constructor(props) {
    super(props);
    this.handleKeyPress = this.handleKeyPress.bind(this);
    this.state = {
      todoArr: [],
    };
  }

  handleKeyPress(e){
    console.log(e.key);
  }

  render(){
    return(
        <div className="wrapper">
          <p className = "title">todos</p>
          <InputField testProp={this.handleKeyPress}></InputField>
          <div className = "filter-wrap">
            <ItemsLeft></ItemsLeft>
            <Filter></Filter>
            <ClearCompleted></ClearCompleted>
          </div>
        </div>
      )
  }
}

class InputField extends Component {
  render(){
    return(
        <input type="text" className="input-field" onKeyPress = {()=> this.props.testProp()}/>
      )
  }
}

Upvotes: 1

Views: 68

Answers (1)

EQuimper
EQuimper

Reputation: 5929

You break the code in the children by doing () => this.props.testProp() if you want this way you should have pass the args like this (e) => this.props.testProp(e)

This is how I would have make it

class ToDoList extends Component {
  constructor(props) {
    super(props);
    this.handleKeyPress = this.handleKeyPress.bind(this);
    this.state = {
      todoArr: []
    };
  }

  handleKeyPress(e) {
    console.log(e.key);
  }

  render() {
    return (
      <div className="wrapper">
        <p className="title">todos</p>
        <InputField testProp={this.handleKeyPress} />
      </div>
    );
  }
}

class InputField extends Component {
  render() {
    return (
      <input
        type="text"
        className="input-field"
        onKeyPress={this.props.testProp}
      />
    );
  }
}

You can test it here :) https://codesandbox.io/s/6n2jp8yzy3

If you want to see the console you have a button bottom left for open it.

enter image description here

By doing this the callback receive all the args provide by the input, so you don't need to write it by your own.

Upvotes: 1

Related Questions