Setting Up Image Upload in Payload CMS & Displaying in Next.js

To upload images in Payload CMS and display them in Next.js.

Steps:

  1. Add an Image Field to Payload CMS Edit payload.config.ts:
ts

Copy

Edit
const Media: CollectionConfig = {
  slug: 'media',
  upload: true,
  fields: [],
};

export default Media;
  1. Upload an Image in Payload CMS Dashboard
  • Go to Collections > Media
  • Upload an image and copy the URL
  1. Fetch & Display in Next.js
tsx

Copy

Edit
import { useEffect, useState } from 'react';

const ImageGallery = () => {
  const [images, setImages] = useState([]);

  useEffect(() => {
    fetch('http://localhost:3000/api/media') // Adjust based on your Payload API URL
      .then((res) => res.json())
      .then((data) => setImages(data.docs));
  }, []);

  return (
    <div>
      <h1>Image Gallery</h1>
      {images.map((img) => (
        <img key={img.id} src={img.url} alt="Uploaded" width={300} />
      ))}
    </div>
  );
};

export default ImageGallery;

Leave a comment

Your email address will not be published. Required fields are marked *