const Sample = ({card}) = > {
const {createdAt, title} = card;
const dateFormat = isThisYear(createdAt) ? 'MMM d' : 'MMM d, yyyy';
return(
<Child title={title} />
)
}
I got an error message saying TypeError: Cannot destructure property 'createdAt' of 'card' as it is undefined.
Can I get createdAt, title
only card exists or card is also passed from the parent component, so get createdAt, title
if the card is passed?
const Sample = ({card}) = > {
const dateFormat = isThisYear(card?.createdAt) ? 'MMM d' : 'MMM d, yyyy';
return(
<Child title={card?.title} />
)
}
I could not destruct props and add ?
like above but if there is a way to destruct props and get createdAt, title
only card exists, I'd be happy to know!
CodePudding user response:
One option is to provide a default value of an empty object for your card
prop:
const Sample = ({ card = {} }) = > {
const {createdAt, title} = card;
// rest of component
}
In this case, when card
is undefined
, it will default to an empty object and createdAt
and title
will be undefined
.