Home > other >  How do I load an image from my project folder inside a js file?
How do I load an image from my project folder inside a js file?

Time:02-25

I am trying to build a website and I currently am using a data.js file to be the source of images and links in one of my components. The file structure looks like this right now.

enter image description here

And my data.js file looks something like this:

export const products = [
  {
    id: 1,
    img: "",
    link: "http://lama.dev",
  },
  {
    id: 2,
    img: "",
    link: "http://lama.dev",
  },
];

I wish to use the images under my 'img' folder to be inside the img: "xxx" part but I am unsure how. Is this even possible?

Not sure if this is needed but this is how I intend to use my data.js file:

import "./product.css";

const Product = ({ img, link }) => {
  return (
    <div className="p">
      <div className="p-browser">
        <div className="p-circle"></div>
        <div className="p-circle"></div>
        <div className="p-circle"></div>
      </div>
      <a href={link} target="_blank" rel="noreferrer">
        <img src={img} alt="" className="p-img" />
      </a>
    </div>
  );
};

export default Product;

enter code here

CodePudding user response:

you can import your image from your img folder like this.

import FirstImg from "./img/pexels-cátia-matos-1072179.jpg";

and you can use like this in same file

export const products = [
  {
    id: 1,
    img: FirstImg,
    link: "http://lama.dev"
  }
];

or

You can change your img folder location to public

Folder structer image

public/img

and you can use like this

export const products = [
  {
    id: 1,
    img: "./img/470a19a36904fe200610cc1f41eb00d9.jpg",
    link: "http://lama.dev"
  }
];

CodePudding user response:

Try this in your data.js

import figma from './me.jpg'
export const products = [
  {
    id: 1,
    img: figma,
    link: "http://lama.dev",
  },
  {
    id: 2,
    img: "",
    link: "http://lama.dev",
  },
];

CodePudding user response:

You can move your images folder under public directory. Otherwise all those images would be bundled when you create your react app.

You can then make your data.js to

const products = [
  {
    id: 1,
    img: '/img/image.jpg',
    link: 'http://file/'
  }

]

export default products

CodePudding user response:

use require method in js

const products = [
  {
    id: 1,
    img: require('/img/image.jpg'),
    link: 'http://file/'
  }

]

export default products
  • Related