0
class A extends React.Component{
   constructor(props){
      this.sendMsg = this.sendMsg.bind(this)
   }

   sendMsg(){
     console.log("Message is send!!!")
   }

keyPressed(event){
    if (event.key === "Enter") {
        this.sendMsg()
    }
}

render(){
   return(
      <input 
          type="text" 
          className="form-control input-chat border-0" 
          id="inputMessage" 
          placeholder="Type a new message" 
          onKeyPress={this.keyPressed}
      />
   )
}

}

Error: this.sendMsg() is undefined.

The above code show a component of input box, if the user click enter, I would like to display a console message. But there have a problem occur as above. What need to be added to the code to run it properly?

alexlee11111
  • 87
  • 1
  • 10
  • https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function – Nikita Madeev Jun 02 '20 at 07:12
  • You need to bind keyPressed as well, because `this` is `undefined` in the method body. And thus you are accessing from `undefiend.sendMsg()` – Yash Joshi Jun 02 '20 at 07:12
  • you are missing the ```super(props)``` and bind keyPressed or use arraow functions https://codesandbox.io/s/modern-bush-cj8rq?fontsize=14&hidenavigation=1&theme=dark – Junius L Jun 02 '20 at 07:15

2 Answers2

1

You need to bind the keyPressed function too.

class A extends React.Component{
constructor(props){
super(props);
  this.sendMsg = this.sendMsg.bind(this)
 this.keyPressed = this.keyPressed.bind(this)
}

sendMsg(){
 console.log("Message is send!!!")
}

keyPressed(event){
if (event.key === "Enter") {
    this.sendMsg()
}
}

render(){


return(
      <input 
          type="text" 
          className="form-control input-chat border-0" 
          id="inputMessage" 
          placeholder="Type a new message" 
          onKeyPress={this.keyPressed}
      />
   )
}
}
Adesh Kumar
  • 952
  • 2
  • 16
  • 33
0

You are not calling the parent contructor in your component, which means you can't use this until after you’ve called the parent constructor.

constructor

Add super(props)to your constructor to call the parent constructor.

constructor(props) {
  super(props);
  this.sendMsg = this.sendMsg.bind(this);
}

You also need to bind the keyPressed function as this inside keyPressed points to a different thing or use arrow functions instead.

constructor(props) {
  super(props);
  this.sendMsg = this.sendMsg.bind(this);
  this.keyPressed = this.keyPressed.bind(this);
}

Using arrow functions

export default class A extends React.Component {

  sendMsg = () => {
    console.log("Message is send!!!");
  }

  keyPressed = event => {
    if (event.key === "Enter") {
      this.sendMsg();
    }
  };

  render() {
    return (
      <input
        type="text"
        className="form-control input-chat border-0"
        id="inputMessage"
        placeholder="Type a new message"
        onKeyPress={this.keyPressed}
      />
    );
  }
}
Junius L
  • 15,881
  • 6
  • 52
  • 96