Shabi Rayan
Shabi Rayan

Reputation: 29

React JS: Function undefined when called in .map function

When I am using a map function in React, I am unable to use a function which I have already binded in my constructor. In the following code, imageClick is undefined when used in the map function below although I have binded the function and included this as an argument. Any idea what could be wrong?

export default class ScrapeInstagram extends React.Component { 

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

imageClick() {
  console.log("made it here!")
}

render() {
    return (
    <Container>
        <center>
            <h1> A bunch of photos! </h1>
            <div className="box">
            {this.searchResults.map(function(photo){
                return <div className="dataSetBox" key={photo.toString()}><img id={id} src={photo} onClick={this.imageClick} alt="Image" height="350" width="450" margin="15px" border= "10"/></div>;
            }, this)}
            </div>
        </center>
    </Container>  
    );
}
}

Upvotes: 0

Views: 978

Answers (1)

sumit
sumit

Reputation: 15464

Use ES6 Arrow functions which will help you to up access the this value of the enclosing context

{this.searchResults.map(photo) =>
    return <div className="dataSetBox" key={photo.toString()}><img id={id} src={photo} onClick={this.imageClick} alt="Image" height="350" width="450" margin="15px" border= "10"/></div>        
)}

Upvotes: 2

Related Questions