Next.js Discord

Discord Forum

how to properly use the next/image when getting the paths from a database

Answered
Chartreux posted this in #help-forum
Open in Discord
ChartreuxOP
Hello guys!

I am creating a SSG site using the pages router. I am populating the pages with data from a database. That database also has the paths to the images I am trying to use. However when trying to use the Image component from nextjs I am getting the error to specify width and height.

I know what that error means, but how should I tackle my problem? I cant specify the width and height properties from the data im getting since im only getting the image paths. An example of how one of the cats cat.imageslook like is :
const images = ['/static/images/Elsa_forside-300x300.jpg', '/static/images/Elsa_02-1024x844.jpg', '/static/images/Elsa_04.jpg']

As you can see they are just paths. Im trying to programattically create profile pages for over 100 cats and all the pictures im gonna use is in that array. I would like to get the same benefits as you would get if you manually imported:
import ElsaForside from '../../static/images/Else_forside-300x300.jpg'


Here is the code from the [slug].tsx file im using to create the seperate profile pages for each cat.
function Cats({ cat }) {
  const profileImg = JSON.parse(cat.images)[0].split("/").at(-1);

  return (
    <>
          <p>{cat.name}</p>
          <Image
            src={`/static/images/${profileImg}`}
            alt={`${cat.name} picture`}
            width={300}
            height={300}
            className="rounded-full"
          />
    </>
  );
} 


Anyone got some recommandation what I should do? Thanks in advance!
Answered by fuma
1. Generally, we will also store the image width and height in the database.
2. If you can't, fetch and determine the image size dynamically.

There are some packages like probe-image-size that allows you to get image size from a url or file.
View full answer

10 Replies

1. Generally, we will also store the image width and height in the database.
2. If you can't, fetch and determine the image size dynamically.

There are some packages like probe-image-size that allows you to get image size from a url or file.
Answer
Since App Router, you can directly await in server components, and read files from file system
ChartreuxOP
Its a SSG
Also:
3. Use fill and give it an aspect ratio
@Chartreux Its a SSG
For SSG, just fetch the image size during build time
ChartreuxOP
Oki in getStaticProps then?
Yep, with something like fs.readFile
ChartreuxOP
Aight gotcha! Then I remake a new array with the sizes? And pass to the component ?
Correct.
ChartreuxOP
@fuma Alright thanks! i thought it was better to somehow import them like you would do when you dont need the widths and height. When you import tje image at the top. Cause its local images