DEV Community

Patrick Rydwanski
Patrick Rydwanski

Posted on

Map over "null" before next.js/image and provide a fallback

With the use from "Inline If-Else with Conditional Operator" from the react-libary we can easily set up an fallback image if for example your API is providing a "null" for the url.

import Image from "next/image";
import fallbackimg from "../assets/fallbackimg.jpg";
...

{
  data.image != null ? (
    data.image.map((img) => (
      <Image
        alt={img.title}
        src={img.url}
        layout="fill"
        objectFit="cover"
      />
    ))
  ) : (
    <Image
      alt="Fallback"
      src={fallbackimg}
      layout="fill"
      objectFit="cover"
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)