Reputation: 654
I am getting (sometimes) an attribute in a JSON response called smallThumbnail
. It may or may not exist... along with parent and grandparent properties imageLinks
and volumeInfo
. Is there a cleaner way than this to prevent me from using a smallThumbnail
value that doesn't exist and throwing errors?
<img src={option.volumeInfo &&
option.volumeInfo.imageLinks &&
option.volumeInfo.imageLinks.smallThumbnail ?
option.volumeInfo.imageLinks.smallThumbnail :
"https://up.quizlet.com/1hbijs-gYV7D-256s.jpg"}
width="40" height="40" />
Upvotes: 0
Views: 48
Reputation: 8718
If you have access to optional chaining, you can write this pretty cleanly:
<img src={option.volumeInfo?.imageLinks?.smallThumbnail
|| "https://up.quizlet.com/1hbijs-gYV7D-256s.jpg"}
width="40" height="40" />
Basically how a?.b
works is "if a
exists, do the rest of the expression, otherwise return undefined". By chaining this several times and combining with ||
as shown above, we have a nice one-liner with a default value.
Since you are using JSX, you're most likely using something like Babel/Webpack that can automatically transform optional chaining to "old JavaScript" to increase compatibility for older browsers or browser versions.
Upvotes: 2
Reputation: 1166
Does this not also throw errors?
If it's supported by your node version, I think this is the best solution: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
If it's not, check out this answer: Checking if a key exists in a JavaScript object?
Upvotes: 2