I see sometimes in JSX this being using ?.
For example
const featuredImageInfo = {
url,
// eslint-disable-next-line camelcase
alt: image?.alt_text,
};
I get invalid token unless i remove the ?
. What is it for?
I see sometimes in JSX this being using ?.
For example
const featuredImageInfo = {
url,
// eslint-disable-next-line camelcase
alt: image?.alt_text,
};
I get invalid token unless i remove the ?
. What is it for?
This is called Optional chaining but not specific to JSX.
It is safe way to access the nested object properties even if an intermediate property doesn’t exist.
Optional chaining props?.value
means if the property exist then get the value of that else assign undefined.
const z = {
test: {
key: "val"
}
};
console.log(z.test.key);
console.log(z.test2?.key)
console.log(z.test2.key) // error
In the above example you can see while using optional chaining it logs undefined when property does not exist , without it , it throws error
it's called Optional Chaining
;) https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html