Skip to content

Commit

Permalink
Add fallback image
Browse files Browse the repository at this point in the history
  • Loading branch information
Mansive committed Jan 27, 2024
1 parent c5750f0 commit ec7d2a1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/components/Card/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import styles from "./Card.module.css";
import Image from "next/image";
import ImageWithFallback from "../ImageWithFallback/ImageWithFallback";

type CardInterface = {
id: string;
Expand All @@ -27,8 +28,9 @@ function Card({
return (
<div className={styles.wrapper}>
{cover ? (
<Image
<ImageWithFallback
src={cover}
fallbackSrc={"/tevi.png"}
alt="Cover image of a book"
height={102}
width={72}
Expand Down
25 changes: 25 additions & 0 deletions src/components/ImageWithFallback/ImageWithFallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"use client";
import React, { useState } from "react";
import Image, { ImageProps } from "next/image";

interface ImageWithFallbackProps extends ImageProps {
fallbackSrc: string;
}

// https://stackoverflow.com/a/66953317
const ImageWithFallback = (props: ImageWithFallbackProps) => {
const { src, fallbackSrc, ...rest } = props;
const [imgSrc, setImgSrc] = useState(src);

return (
<Image
{...rest}
src={imgSrc}
onError={() => {
setImgSrc(fallbackSrc);
}}
/>
);
};

export default ImageWithFallback;
2 changes: 2 additions & 0 deletions src/components/ImageWithFallback/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./ImageWithFallback";
export { default } from "./ImageWithFallback";

0 comments on commit ec7d2a1

Please sign in to comment.