As you can see, the property mainImage
in the array is null
and it gives me the error:
Error: Cannot read properties of null (reading ‘url’)
I wanted to show or hide the Image element if the mainImage property in the array is null.
return (
<Container maxWidth="desktop">
<Typography variant="h1" sx={{ mb: 10 }}>
Blog
</Typography>
<Stack gap={5} useFlexGap>
{articles.map((article: Article) => (
<Box key={article._id} sx={{ display: "flex", gap: 3 }}>
<Box
sx={{
position: "relative",
aspectRatio: "16/9",
flexShrink: 0,
width: "30%",
}}
>
<NextImage
src={article.mainImage.url}
alt={article.title}
placeholder="blur"
blurDataURL={
article.mainImage?.metadata?.lqip?.toString() ?? ""
}
fill
style={{
objectFit: "cover",
}}
/>
</Box>
<Box>
<Typography variant="h2" sx={{ mb: 2 }}>
<Link
href={`/blog/${article.slug}`}
component={NextLink}
underline="hover"
>
{article.title}
</Link>
</Typography>
<Typography variant="body2" sx={{ mb: 2 }}>
By: {article.author}
</Typography>
<Typography variant="body2">{article.excerpt}</Typography>
</Box>
</Box>
))}
</Stack>
</Container>
);
Sample Data Returned:
[
{
excerpt: "omitted",
mainImage: null,
categories: null,
_id: '3453',
_createdAt: '2024-12-11T16:39:29Z',
title: 'omitted',
slug: 'omitted',
author: 'omitted'
},
]
2
Answers
You can check if it’s null before you render the
<NextImage />
componentOption 1: Use Optional Chaining (?.) to Check if mainImage is Null
Option 2: Use a Placeholder Component as a Fallback
Additional: Use the onError Handler with the Next.js Image Component
If you are using the Image component provided by Next.js, you can handle errors gracefully with the onError handler. Check the official documentation for more details: https://nextjs.org/docs/pages/api-reference/components/image.