SVG not getting loaded dynamically in Next/Image

44 views Asked by At

I am trying to load multiple images dynamically using the Image tag from the next/Image. But I am getting error at the tag. The error says : Use another rendering method.

Here I am sharing an example code snippet.

import Image1 from '@/public/fig1.svg'
import Image2 from '@/public/fig2.svg'
import Image3 from '@/public/fig3.svg'

const ImageList = [
{src: Image1, text: 'item1'},
{src: Image2, text: 'item2'},
{src: Image3, text: 'item3'},
];

export default function HomeCOmponent () {

  return (
    <>
      {ImageList.map(eachItem, index)=> <ImageComponent key={index} src={eachItem.src} text={eachItem.text} /> }
    </>
  )
}

Image component

export function ImageComponent ({src, text}) {
  return (
    <>
      <Image src={src} alt={text} />
    </>
  )
}

1

There are 1 answers

1
MMT Tello On

The error you're encountering is occurring because you're trying to use the Next.js Image component with dynamically imported images. The Image component from Next.js requires a static source (local or remote) and does not support dynamically imported images.

import Image1 from '@/public/fig1.svg';
import Image2 from '@/public/fig2.svg';
import Image3 from '@/public/fig3.svg';
const ImageList = [
  { src: Image1, text: 'item1' },
  { src: Image2, text: 'item2' },
  { src: Image3, text: 'item3' },
];

export default function HomeComponent() {
  return (
    <>
      {ImageList.map((eachItem, index) => (
        <ImageComponent key={index} src={eachItem.src} text={eachItem.text} />
      ))}
    </>
  );
}

function ImageComponent({ src, text }) {
  return (
    <div>
      <img src={src} alt={text} />
      <span>{text}</span>
    </div>
  );
}