0

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" />

zr0gravity7
  • 2,308
  • 1
  • 6
  • 22
mateoc15
  • 377
  • 3
  • 15

2 Answers2

2

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?

ᴓᴓᴓ
  • 1,103
  • 1
  • 6
  • 17
2

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.

Kelvin Schoofs
  • 7,823
  • 1
  • 10
  • 29
  • I've used such a thing in C#, didn't know about it in JS. Very convenient, thanks for the detailed explanation. – mateoc15 Jul 20 '21 at 22:05