user16013401
user16013401

Reputation:

How do I load an image from my project folder inside a JavaScript file?

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;

Upvotes: 0

Views: 1910

Answers (4)

Ridwan Ajibola
Ridwan Ajibola

Reputation: 1089

use require method in js

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

]

export default products

Upvotes: 0

Singh3y
Singh3y

Reputation: 381

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

Upvotes: 0

BIRKAN
BIRKAN

Reputation: 81

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"
  }
];

Upvotes: 1

Ilian Futekov
Ilian Futekov

Reputation: 174

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",
  },
];

Upvotes: 0

Related Questions