简体   繁体   中英

Image is not rendering in the DOM while passing as props in the App.js file?

I am passing the image name as props in the instance of the Card component in App.js. Then I am receiving it from the Card component and render it to the DOM. But my image is not showing in the DOM. What could be the reason?

This is my App.js

import React from "react";
import "./style.css";
import Navbar from "./components/Navbar";
import Hero from "./components/Hero";
import Card from "./components/Card";
import "./images/image12.png";
import "./images/Star1.png";
function App() {
  return (
    <div className="App">
      <Navbar />
      <Hero />
      <Card
        img="image12.png"
        star="Star1.png"
        obtainedRating={5.0}
        TotalRating="6-USA"
        briefText="Life lessons with Katie Zaferes"
        price="$136"
        person="/person"
      />
    </div>
  );
}

export default App;

Here is my Card component

import React from "react";
import "../style.css";
import "../images/image12.png";
import "../images/Star1.png";
export default function Card(props) {
  console.log(props);
  return (
    <div className="card--section">
      <img src={`../images/${props.img}`} className="card--image" alt="Katie" />

      <div className="rating">
        <img
          src={`../images/${props.star}`}
          className="star--image"
          alt="star"
        />
        <small>
          {props.obtainedRating} <span>{props.totalRating}</span>
        </small>
      </div>
      <p className="brief-text">{props.briefText}</p>
      <p className="price">
        <strong>{props.price}</strong>
        {props.person}
      </p>
    </div>
  );
}

This is my Folder structure

src -components -Card.js -images -image12.png -Star1.png -App.js -index.js

This is not working because you need to import an image like this and then put imageName as the value of src attribute . You can give any name you like.

import imageName from "../images/image12.png";

src={imageName}

Import images like:

import img12 from '../images/image12.png'
import star1 from './images/Star1.png'

The image path can retrieved by using the import statement

like below

import "./styles.css";
import clouds from "./Images/clouds.jpeg";
import CardImage from "./CardImage";

export default function App() {
  console.log("cloud path", clouds);
  return (
    <div className="App">
      <CardImage path={clouds} alt="clouds" />
    </div>
  );
}

在此处输入图像描述

I have found the solution.I simply imported

import cardImage from "./images/image12.png"
import star from "./images/Star1.png"

And used them in App.js

<Card img={cardImage} star={star}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM