Use the right-size image (using next.js / react)

Hi,
I uploaded images with the media library (to aws s3). I can fetch them alright with the getStrapiMedia function. I can see that in aws I have a small, medium, large and thumbnail version of each images, beside the original. Now I am displaying them in cards and I noticed that the original is being used… how could I enforce it to use a small/thumbnail for the cards?

Thanks!

in case it helps, adding the script I use to call images (I believe that it comes from the strapi-react-next blog)

import { getStrapiMedia } from "../lib/media";
const Image = ({ image, style, imageClass }) => {
  const imageUrl = getStrapiMedia(image);
  return (
    <img
      className={imageClass}
      src={imageUrl}
      alt={image.alternativeText || image.name}
      style={style}
    />
  );
};
export default Image;

All files have the same name as the original one, but with an additional prefix:
image

small_
medium_
large_
thumbnail_

In that case you can add your desired prefix to the original image path:

const imageThumbnailURL = `thumbnail_${imageOriginalSize}`;

I’m not sure how AWS s3 stores the path of the file, its relative, or its full path, but you got the idea of displaying the desired size in frontend.

1 Like

Thanks! that worked! for anyone runing into a similar issue (aws s3 that is). I added a prefix option to the generation of the image div and then did this to my image.js. Note that I just googled around how to parse javascript strings, so anyone with any experience can write this in a prettier way…

import { getStrapiMedia } from "../lib/media";
const Image = ({ imageClass, image, style, prefix }) => {
  var imageUrl = getStrapiMedia(image);
  if (prefix) {
    imageUrl =
      imageUrl.substr(0, imageUrl.lastIndexOf("/")) +
      "/" +
      prefix +
      "_" +
      imageUrl.substr(imageUrl.lastIndexOf("/") + 1, imageUrl.length - 1);
  }
  return (
    <img
      className={imageClass}
      src={imageUrl}
      alt={image.alternativeText || image.name}
      style={style}
    />
  );
};
export default Image;
2 Likes