Rohan Kulkarni
Rohan Kulkarni

Reputation: 55

React.js onclick event: Cannot read property 'props' of undefined

I am a beginner in the react framework, so my question may appear basic to many of you. But believe me I've been stuck on this part. I am trying to get the text box value on button click and send the value to other function as a prop. I'm able to extract the value of textbox field but on the click event, i get an error 'Cannot read property 'props' of undefined'.

here are the important points:-

  1. termchange() is used for extracting the input text value.
  2. handleclick is used for extracting textbox value onclick event.
  3. oncitychange is a function to which I've to send the value of textbox (oncitychange() function is inside different component).

Thank you in advance.

here's my code:-

import React,{ Component } from 'react';
import ReactDom from 'react-dom';
class SearchBar extends Component {
  constructor(props){
    super(props);
    this.state = {
      cityname:''
    }
  }

  render(){
    return(
      <div>
        <span>Enter the city: </span>
        <input type="text" id="txtbox" value={this.state.cityname} 
          onChange={event=>this.termchange(event.target.value)} />
        <input type="submit" onClick={this.handleclick} />
      </div>
    );
  }

  termchange(cityname){
    this.setState({cityname});
  }

  handleclick(){
    this.props.oncitychange(cityname);
  }
}

export default SearchBar;

Upvotes: 4

Views: 7447

Answers (3)

pablopunk
pablopunk

Reputation: 371

Just replace onClick={this.handleClick} by:

onClick={this.handleClick.bind(this)}

That way, the function scope will be tight to the React object

Upvotes: 0

Travis White
Travis White

Reputation: 1977

It is all about scope. Your functions don't know what this is. You can bind this in the constructor or other options may be easier depending on your environment.

Add this to your constructor to fix:

this.termchange = this.termchange.bind(this); this.handleclick = this.handleclick.bind(this);

Or read https://blog.andrewray.me/react-es6-autobinding-and-createclass/ for a more detailed explanation of what is going on.

I personally use ES7 fat arrow class methods for the simplicity and I think most developers are moving in that direction.

Upvotes: 9

SALEH
SALEH

Reputation: 1562

Add this.handleClick = this.handleClick.bind(this) at constructor

Upvotes: 2

Related Questions