Skip to content

Instantly share code, notes, and snippets.

@carlosbensant
Created June 26, 2024 01:21
Show Gist options
  • Save carlosbensant/f3b30d856bc23d74a8ca0d8c2eee06cc to your computer and use it in GitHub Desktop.
Save carlosbensant/f3b30d856bc23d74a8ca0d8c2eee06cc to your computer and use it in GitHub Desktop.
custom-fields/Thumbnail.tsx - PayloadCMS show thumbnail vs filename
'use client'
import Image from 'next/image'
import React, { useState, useEffect } from 'react'
import type { CellComponentProps } from 'payload'
import { useTableCell } from '@payloadcms/ui'
import { Media } from '@/payload-types'
const getImage = (imageId: string) => {
return fetch(
`/api/media/${imageId}`
)
}
export const Thumbnail: React.FC<CellComponentProps> = (props) => {
const { cellData } = useTableCell()
const [image, setImage] = useState<Media | null>(null)
const [loading, setLoading] = useState<boolean>(false)
useEffect(() => {
const fetchImage = async () => {
if (cellData) {
try {
setLoading(true);
const response = await getImage(cellData)
const media: Media = await response.json()
if (media && media.url) {
setImage(media)
}
setLoading(false)
} catch (error) {
setLoading(false)
}
}
}
fetchImage()
}, [cellData])
if (loading) {
return (
<div className="relationship-cell">Loading...</div>
)
}
if (!cellData || !image) {
return (
<div>&lt;No {String(props.label)}&gt;</div>
)
}
return (
<div
className="thumbnail"
style={{
backgroundColor: cellData as string,
display: "flex",
position: "relative",
width: "40px",
height: "40px",
}}
>
<Image
src={image.url as string}
alt={image.alt}
fill={true}
style={{
objectFit: 'cover',
}}
/>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment