Reputation: 311
I am making api calls to receive images and certain calls do not have actual images and so I believe I am getting these values of null that are causing react to throw an error. I have tried using an onError method in my code to place a fallback image but that did not work as well. I have tried handling this error with a ternary expression as well but have not had any luck. My question is what is the best way to get rid of this error and provide a default image in cases where I receive null.
This is the line of code where I am getting an error:
<img
className="cover-photo"
src={this.props.detail.img}
alt={this.props.detail.caption}
/>
Upvotes: 1
Views: 341
Reputation: 3780
This is how you can check if this.props.detail
is null and set a default. This is using the conditional (ternary) operator
<img
className="cover-photo"
src={this.props.detail ? this.props.detail.img : "/default/img/path.png"}
alt={this.props.detail ? this.props.detail.caption : ""}
/>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
Upvotes: 1