Skip to content

Commit

Permalink
better image loading for NFTMedia
Browse files Browse the repository at this point in the history
  • Loading branch information
samepant committed Jan 23, 2024
1 parent 90911f9 commit 147446d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
3 changes: 2 additions & 1 deletion frontend/src/components/NFTMedia/NFTMedia.module.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.noImage {
height: 100%;
width: 100%;
aspect-ratio: 1;
background-color: var(--box-bg);
border-radius: 10px;
}
Expand Down
13 changes: 11 additions & 2 deletions frontend/src/components/NFTMedia/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from "react"
import { useEffect, useState } from "react"
import { MoralisNFT } from "../../types/Token"

import classes from "./NFTMedia.module.css"
Expand All @@ -12,9 +12,14 @@ const getIPFSHashFromURL = (url: string) => {

const NFTMedia = ({ nft }: { nft: MoralisNFT }) => {
const [imageError, setImageError] = useState(false)
const [imageLoaded, setImageLoaded] = useState(false)
const metadata = JSON.parse(nft.metadata || "{}")
const alt = metadata.name || "NFT image"

useEffect(() => {
setImageLoaded(false)
}, [nft])

let src = ""
let type = "image/*"

Expand Down Expand Up @@ -45,7 +50,9 @@ const NFTMedia = ({ nft }: { nft: MoralisNFT }) => {
}
return (
<>
{(imageError || !src) && <div className={classes.noImage}></div>}
{(imageError || !imageLoaded || !src) && (
<div className={classes.noImage}></div>
)}
{!imageError && src && (
<div className={classes.imageContainer}>
{type.includes("image") && (
Expand All @@ -54,13 +61,15 @@ const NFTMedia = ({ nft }: { nft: MoralisNFT }) => {
alt={alt}
className={classes.image}
onError={() => setImageError(true)}
onLoad={() => setImageLoaded(true)}
/>
)}
{type.includes("video") && (
<video
src={src}
className={classes.image}
onError={() => setImageError(true)}
onLoad={() => setImageLoaded(true)}
autoPlay
muted
/>
Expand Down

1 comment on commit 147446d

@vercel
Copy link

@vercel vercel bot commented on 147446d Jan 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.