javascriptreactjsfile-structure

How to import images properly into an array in React


I have some images in my project folder and want to either use their relative links to show them in each respective array item.

I want to eventually use the image in a react component to show the image on my webpage.

File Structure

Project.jsx

export default function Project({ project, theme }) {
  return (
    <div id="project">
      <h3 className="subheading">{project.name}</h3>
      <div>
        <img src={project.img}>
      </div>
    </div>
  );
}

project.js

// import projectImages from '../data/projectImages' (tried to import an array of img)

module.exports = [
  {
    type: "",
    name: "",
    desc: "",
    tech: ["", "", "", ""],
    summary: "",
    year: ,
    img: '../data/images/img.jpg', // tried projectImages[0]
    link: "",
  },
  {
    ...
    img: '../data/images/img2.jpg', // tried projectImages[1]
    ...
  },
  {
    ...
    img: '../data/images/img3.jpg', // tried projectImages[2]
    ...
  },

I have tried to import img from '../data/projectImages/img.jpg but the variable was not accepted in the object array. I have also tried to shove the images into an array and use the array to reference them but that did not work as well.


Solution

  • You are using create-react-app which uses webpack behind the scenes.

    It's been a while since I did this, but I believe that you can do something like:

    const myRequireContext = require.context('./someDir', false, /\.jpg$/);

    which will give you an object that looks something like:

    {
      "./img.jpg": "some/path",
      "./img2.jpg": "some/otherPath",
      "./img3.jpg": "some/yetAnotherPath"
    }
    

    (this is off-the-top-of-my-head, so details might be a little different)

    See https://webpack.js.org/guides/dependency-management/#require-with-expression