0

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>  
    );
}
}
Shabi Rayan
  • 29
  • 1
  • 10
  • 2
    try using arrow function `(photo) =>
    `as it's automatically bound to the component
    – h1b9b Mar 07 '18 at 19:24
  • Possible duplicate of [What does "this" refer to in arrow functions in ES6?](https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6) – Sterling Archer Mar 07 '18 at 19:30

1 Answers1

2

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>        
)}
sumit
  • 15,003
  • 12
  • 69
  • 110