skip to Main Content

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


  1. You can check if it’s null before you render the <NextImage /> component

    {
      article.mainImage && <NextImage {...otherProps} />
    }
    
    Login or Signup to reply.
  2. Option 1: Use Optional Chaining (?.) to Check if mainImage is Null

    <Box
      sx={{
        position: "relative",
        aspectRatio: "16/9",
        flexShrink: 0,
        width: "30%",
      }}
    >
      <NextImage
        src={article.mainImage?.url || "your_placeholder_img_url.jpg"}
        alt={article.title}
        placeholder="blur"
        blurDataURL={article.mainImage?.metadata?.lqip?.toString() ?? ""}
        fill
        style={{
          objectFit: "cover",
        }}
      />
    </Box> 
    

    Option 2: Use a Placeholder Component as a Fallback

    <Box
      sx={{
        position: "relative",
        aspectRatio: "16/9",
        flexShrink: 0,
        width: "30%",
      }}
    >
      {article.mainImage?.url ? (
        <NextImage
          src={article.mainImage.url}
          alt={article.title}
          placeholder="blur"
          blurDataURL={article.mainImage?.metadata?.lqip?.toString() ?? ""}
          fill
          style={{
            objectFit: "cover",
          }}
        />
      ) : (
        <YourPlaceholderComponent />
      )}
    </Box>
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search