skip to Main Content

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

  • src
    • assets
      • data
        • project.js
        • projectImages.js
      • images
        • img.jpg
        • img2.jpg
        • img3.jpg
    • components
      • Project.jsx

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. Directly inside your array, use require()

    module.exports = [
      {
        type: "",
        name: "",
        desc: "",
        tech: ["", "", "", ""],
        summary: "",
        year: ,
        img: require('../data/images/img.jpg'), 
        link: "",
      },
      {
        ...
        img: require('../data/images/img2.jpg'), 
        ...
      },
      {
        ...
        img: require("'../data/images/img3.jpg", 
        ...
      },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search