Dynamic image loading with NextJS

This short blog post is to provide an example of dynamically serving content (images in this case) in NextJS.

Over the last few years, Next has seen its method of static file storage change, so figuring out how to dynamically display this content can be a bit confusing.

I recently ran into an issue where I was loading cards with images in a loop, and my solution using next-images suddenly stopped working in production. Here is the code that solved the problem. All images used in the example below are stored in /public.

import React, { Component } from "react";

class Team extends Component {
  state = {
    members: [
      {
        id: 1,
        name: "Richard Hendricks",
        title: "CEO",
        image: "/RichardHendrick.png"
      },
      {
        id: 2,
        name: "Jared Dunn",
        title: "COO",
        image: "/JaredDunn.png"
      },
      {
        id: 3,
        name: "Bertram Gilfoyle",
        title: "CTO",
        image: "/BertramGilfoyle.png"
      }
    ]
  };
  render() {
    return (

      <div className="flex flex-wrap justify-center">
        {this.state.members.map(member => (
          <div className="w-full md:w-1/3">
            <div
              key={member.id}
              className="bg-dark text-white"
            >
              <div className="mx-5 py-4">
                <h3 className="font-bold text-lg">{member.name}</h3>
                <h5 className="text-gray-500">{member.title}</h5>
              </div>
              <div className="w-full h-64 rounded-b-lg bg-cover bg-center" style={{ backgroundImage: `url(${member.image})` }}>
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  }
}

export default Team;

Notice that the code loops through members (which can be loaded in from your db or elsewhere in the application), but when it comes to loading the images in backgroundImage, the following code does the trick:

backgroundImage: `url(${member.image})`

Where member.image is replaced by a path such as /RichardHendrick.png.

Previously, with next-images, the solution that worked was:

backgroundImage: `url(${require(`../public/${member.image}`)})`

This linked directly to where the images were stored in the application, but became problematic in production, as Next would no longer understand what that path meant when compiling.

You can find Next's docs on basic static file serving here, but in short, it recommends that you store your images in /public in your project, and access them with /my-image.png, without any extra importing or any additional libraries.

I hope you found this useful, if you have any questions, you can find me @alexgordienko_.