Home > Mobile >  Issues with importing images in React
Issues with importing images in React

Time:07-03

I'm building a small React app with a reusable box component that requires me to map over an array of objects(data.js) that I also created. Here are the components:

data.js:

const cardData = [
    {
        id: 1,
        title: "Small Size bags",
        price: "KES 25",
        coverImg:"product-small.jpeg",
        status: "available"

    },
    {
        id: 2,
        title: "Medium Size bags",
        price: "KES 30",
        coverImg:"product-meduim.jpeg",
        status: "available"
    },
    {
        id: 3,
        title: "Large Size bags",
        price: "KES 40",
        coverImg: "product-large.jpeg",
        status: "available"
    }
]

export default cardData;

App.js:

import "./index.css";
import React from "react";
import Navbar from "./Components/Navbar";
import Card from "./Components/Card"
import Footer from "./Components/Footer";
import cardData from "./data";

export default function App() {
  const cards = cardData.map(item => {
    return (
      <Card 
      key={item.id}
      item={item}
      
      />
    )
  })
  return (
    <div>
      <Navbar />
      {cards}
      <Footer />
    </div>
  );
}

Card.js:

import React from "react";

export default function Card(props) {
  let badgeText;

  if (props.item.status === "available") {
    badgeText = "IN STOCK";
  } else {
    badgeText = "OUT OF STOCK";
  }

  // const image = props.item.coverImg;
  // const baseURL = '../Images/'
  // const finalImg = baseURL   image
  // const stringImg = JSON.stringify(finalImg)
  // const Img = require(`../Images/${props.item.coverImg}`)


  console.log(`../Images/${props.item.coverImg}`)
  const Img = (`../Images/${props.item.coverImg}`)
  console.log(Img)
  return (
    <div>
      {badgeText && <div>{badgeText}</div>}
      <img src={Img} alt="product-pic" />
    </div>
  );
}

The other properties seem to work well. However, the images simply won't load. I've tried using require() and JSON.stringify() (together and in isolation) but these also don't seem to work. I've also commented out some of the approaches that I tried in Card.js. This is the error I get in the console when I try to use require ():

Uncaught Error: Cannot find module './product-medium.jpeg' screenshot of error when using require()

The course I learned this method from (https://scrimba.com/learn/learnreact/loading-images-from-map-coe6c4822bbdc0a0360bd1961) advises moving the images folder from src/ to public/ but apparently, relative imports outside of src/ are not supported (webpack). This is the error I get:

ERROR in ./src/Components/Navbar.js 262:13-51 Module not found: Error: You attempted to import ../../Images/trash-pic0.jpg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

screenshot of error when moving Images folder from src/ to public/

Files: screenshot of files

Oh, and the instructor says that moving the folder from src/ to public/ makes it work "magically" lol.

Someone please clear this up

CodePudding user response:

You can put your images in the public folder and use them in the image tag like below

<img src='/images/image1.jpg' />

and in your public folder, you have sub folder name images and have an image with a file name image1.jpg

I have created a code sandbox demo for it You can check it DEMO

You can find the more info from the below documentation Using the Public Folder

CodePudding user response:

You can also try this approach:

// data.js

import image1 from "<path>"
import image2 from "<path>"
import image3 from "<path>"

const cardData = [
    {
        id: 1,
        title: "Small Size bags",
        price: "KES 25",
        coverImg: image1,
        status: "available"

    },
    {
        id: 2,
        title: "Medium Size bags",
        price: "KES 30",
        coverImg: image2,
        status: "available"
    },
    {
        id: 3,
        title: "Large Size bags",
        price: "KES 40",
        coverImg: image3,
        status: "available"
    }
]

export default cardData;

In your Card.js simple type,

// Card.js

return (
  <div>
    {badgeText && <div>{badgeText}</div>}
    <img src={props.item.coverImg} alt="product-pic" />
  </div>
);

  • Related