Search code examples
javascriptreactjsprop

React won't load local images using props


Card.js

import React from "react"
import '../index.css';

import Star from "../image/Star 1.png";
export default function Card(props) {
    return (
        <div className="card">
           
            <img src={`../image/${props.img}`} className="card--image" alt="swimer" />
            <div className="card--stats">
            <img src={require(`../image/Star 1.png`)} className="card--star"  alt="star" />
                <span>{props.rating}</span>
                <span className="gray">(6) • </span>
                <span className="gray">USA</span>
            </div>
            <p>Life Lessons with Katie Zaferes</p>
            <p><span className="bold">From $136</span> / person</p>
        </div>
    )
}

App.js

import React from "react"
import Navbar from "./Airbnb/Navbar"
import Hero from "./Airbnb/Hero"
import Card from "./Airbnb/Card"
export default function App() {

    return (
        <div>
            <Navbar />
            <Hero/>
            <Card 
            img="swimer.png"
            rating="5.0"
            reviewCount={6}
            country="USA"
            title="Life Lessons with Katie Zaferes"
            price={136}
            />
        </div>
    )
}

the image was not showing to begin so i used props it worked for me but then it come to <img src={../image/${props.img}} className="card--image" alt="swimer" /> I tried "requires" I tried "default" but it's not working. what should i do display the image.


Solution

  • you can do this

    import imageAddress from '../image/swimer.png';
    
    <Card 
            img={imageAddress}
            rating="5.0"
            reviewCount={6}
            country="USA"
            title="Life Lessons with Katie Zaferes"
            price={136}
            />
    

    it should work