I am trying to access nested JSON objects such as the code below, which works currently.
<img id="inactive-drive2" src='/src/assets/image/InActiveDrive.png' className={info.data.drives[1]?.isActive ? "d-none" : ""} />
If I change my code to this :
<img id="inactive-drive2" src='/src/assets/image/InActiveDrive.png' className={info.data.drives[1].isActive ? "d-none" : ""} />
get me an error that isActive field is not defined.
I think info.data.drives[1].isActive is correct but when running the app gets an error.
Why does it work this way?
2
Answers
info.data.drives[1]
might beundefined
at some point when the component renders. Ifinfo.data.drives[1]
isundefined
, trying to access.isActive
directly without checking ifdrives[1]
exists first will result in an error. This is why the optional chaining operator?.
is useful – it safely checks if the value exists before attempting to access a property.The reason why removing the
optional
operator raises an Error should not be that hard to spot.And yet, we are still confident enough to ask it to extract a value from a List, which may or may not even contain anything?🤔 Actually
TypeScript
is helping out by throwing an Error to indicate that the array might be empty or even undefined or ratherNullish
.Since there is no complex computation required in this particular Code, you may also move it to a One-Liner Function – "if seeing those Question Marks (?) that annoys You". Something along these Lines:
And then use it like so: