0

I am making a grid, 3 columns each, each a Jumbotron with a button.


renderProperties = data => {
  var properties = []
  var propRow = []
  data.forEach(function(property,index){
    propRow.push(<Col xs={{ size:3, offset: .5}}> 
      <Jumbotron>
        <Image src={require("./images/1.jpg")} fluid rounded />
        <b> {property.location} </b> 
        <div> 
        <td> <Button variant="info" onClick={()=> this.handleRentProperty(property)}> Rent Property </Button> </td> 
        </div>
      </Jumbotron> 
    </Col> )
    if((index+1)%3 == 0){ // if first in the row
      properties.push(<Row>{ propRow }</Row>)
      propRow = []
    }

  })
  return (
    <Container>
      {properties}
    </Container> 
  )
}


handleRentProperty = prop =>{
this.setState({show: true}); 
  //this.setState({rentProperty: prop.location })

}

The renderProperties in rendered in the render as :

render() {
    {this.renderProperties(data)} 
} 

I keep on getting

"TypeError: Cannot read property 'handleRentProperty' of undefined"

I have tried bind like in the following different ways:

onClick={(e)=> this.handleRentProperty(property, e)}
onClick={this.handleRentProperty.bind(this, property)}
onClick={this.handleRentProperty(property)}
onClick={()=>this.handleRentProperty.bind(this,property)}

1 Answer 1

1

Change data.forEach(function(property,index){ to data.forEach((property,index) => {

Arrow functions get this from the scope they are defined in. Regular functions get their own this based on the caller.

Sign up to request clarification or add additional context in comments.

2 Comments

Please add a comment to explain your answer, regarding the use of an arrow function vs a regular function so future SO users will better understand why this is happening
O wow, thank you, I can/will search it up online ( and thank you jo_va for saying what it is). I gotta wait 9 minutes before I can accept answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.