Security, Tech & Programming
NextJS import images dynamically from directory

NextJS import images dynamically from directory

We can import images directly from a folder in nextjs and use their original path and filename by using the code below.

Routinely, we import the image that we want to show on the page using import statement like this:

import Image from "next/image";
import app_screen_1 from "/public/assets/images/app_screens/1.png";

export default function Output() {
  return (
    <>
      <Image src={app_screen_6} />
    </>
  )
}

However, we can avoid doing that and use dynamic method like this:

import Image from "next/image";

const dirPath = '/assets/images/app_screens/';
const images = require.context(
  "public/assets/images/app_screens/",
  false,
  /^\.\/(?!.*\/)[^.]+\.(png|jpe?g|gif|webp)$/i
);
const imagePaths = images.keys();

export default function Output() {
  return (
    <>
      {imagePaths.map((imagePath, index) => (
        <Image key={index}
          src={`${dirPath}${imagePath.replace("./", "")}`}
          width={100}
          height={100}
        />
      ))}
    </>
  );
}

Example with Splide slider using images dynamically

So if you want to load a splide slider with images dynamically from a certain folder in nextjs public folder, use this:

import Image from "next/image";
import { Splide, SplideSlide } from "@splidejs/react-splide";

const dirPath = '/assets/images/app_screens/';
const images = require.context(
  "public/assets/images/app_screens/",
  false,
  /^\.\/(?!.*\/)[^.]+\.(png|jpe?g|gif|webp)$/i
);
const imagePaths = images.keys();

export default function Output() {
  return (
    <>
      <div className="slider_outer">
        <Splide>
          {imagePaths.map((imagePath, index) => (
            <SplideSlide key={imagePath}>
              <div className="carousel-image-wrap">
                <Image
                  src={`${dirPath}${imagePath.replace("./", "")}`}
                  width={100}
                  height={100}
                />
              </div>
            </SplideSlide>
          ))}
        </Splide>
      </div>
    </>
  );
}

Note that we wrapped the image in div with class: carousel-image-wrap so that we can style the image by using:

.carousel-image-wrap img {
    width: xxx;
    height: xxx;
}

Hope this helps. Please let me know if you need my assistance / services in your project.

Leave a Reply

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

Hire Me!