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>  
    );
}
}
2

1 Answer 1

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>        
)}
Sign up to request clarification or add additional context in comments.

Comments

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.