0

I have a JS file; Cards.js which implements a card-style div:

import React from "react";
import CardItem from "./CardItem";
import "./Cards.css";

function Cards() {
  return (
    <div classNam="cards">
      <ul className="cards__items">
        <CardItem
          src={require("../images/img-9.jpg").default}
          text="text"
          label="label"
          path="/jobs"
        />
      </ul>
    </div>
  );
}

export default Cards;

And then CardItem.js:

import React from "react";
import { Link } from "react-router-dom";

function CardItem(props) {
  return (
    <div>
      <li className="cards__item">
        <Link className="cards__item__link" to={props.path}>
          <figure className="cards__item__pic-wrap" 
            data-category={props.label}>
            <img 
              src={props.src}
              className="card__item__img" 
              alt="alt"
            />
          </figure>
          <div className="cards__item__info">
            <h5 className="cards__item__text">{props.text} </h5>
          </div>
        </Link>
      </li>
    </div>
  );
}

export default CardItem;

However, on my site, the images from CardItem are not displayed. The Text, Label and Path all work, but no image. I've looked around and have seen different solutions to this issue but none have worked for me.

I've tried using

src="../images/img-9.jpg"

instead of using require but that also didn't work. What's weird is I can see the path AND the preview of the image when looking at the Chrome inspection panel, but they won't load.

I've also tried putting the images folder in the Public directory which is another solution I've seen, but I get an error saying something about loading resources outside of /src

Michael
  • 111
  • 7
  • 2
    Import the image like you would import any other file . `import myImage from 'your path'` and pass it as `src={myImage}` – Shyam Jun 08 '21 at 19:16
  • But why does the above approach not work? – Michael Jun 08 '21 at 19:21
  • 1
    You can read the answers here https://stackoverflow.com/questions/39999367/how-do-i-reference-a-local-image-in-react – Shyam Jun 08 '21 at 19:24

0 Answers0