TypeError: Cannot read property ‘search’ of undefined

Posted on Updated on

In a react componenet, I was having a problem calling a function from another function. I kept getting the error


TypeError: Cannot read property 'search' of undefined

by binding “this” to the first function, it was then able to call the second function.

This example by Rafi Ud Daula Refat on Stackoverflow helped me figure this out.

Here is a little example using some code I made for my project

import React, { Component } from 'react';
class Header extends Component {
search() {
console.log("Enter Button Pressed");
}
handleKeyPress(target) {
if(target.charCode==13){
this.search();
}
}
render(){
return(
 input  onKeyPress={this.handleKeyPress.bind(this)} placeholder="Enter search term" 
)
}

*note input not in <> because wordpress doesnt render it correct, keeps making actual inputs or removes the text

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s