gene b.
gene b.

Reputation: 12044

React: Dynamically pass Img Src into Child Component

I have a child component that should receive an icon=.. property to dynamically load an image. The images work when statically specified as img src={name}, but not when dynamically passed through properties, even if I import them in both the Parent & Child.

import laptopHouse from './../images/icons/laptop-house.svg'

export default function Infographic(props) {
    return (


        <Col lg={4} className="home-tile" id="my-telework-tile">
            <img src={props.icon} className="home-tile-img" alt=""/>
            <div className="home-tile-content">
                <h2>{props.title}</h2>
                <p>{props.text}</p>
            </div>
        </Col>

    );
}

Usage

import laptopHouse from './../images/icons/laptop-house.svg'

export default function Home(props) {
    return (
         <Infographic icon="laptopHouse" title="Welcome" text="This is an infographic" />
    );
}

Upvotes: 0

Views: 762

Answers (2)

kyun
kyun

Reputation: 10294

I have a few solutions.

  1. pass the resource with curly braces
import laptopHouse from './../images/icons/laptop-house.svg'

export default function Home(props) {
    return (
         <Infographic icon={laptopHouse} title="Welcome" text="This is an infographic" />
    );
}

  1. pass the img itself
export default function Infographic(props) {
    return (
        <Col lg={4} className="home-tile" id="my-telework-tile">
            {props.children}
            <div className="home-tile-content">
                <h2>{props.title}</h2>
                <p>{props.text}</p>
            </div>
        </Col>

    );
}


import laptopHouse from './../images/icons/laptop-house.svg'

export default function Home(props) {
    return (
         <Infographic title="Welcome" text="This is an infographic">
           <img src={laptopHose} className="home-tile-img" alt=""/>
         </Infographic>
    );
}

Upvotes: 1

Prime
Prime

Reputation: 60

You shoud pass "laptopHouse" in {curly braces}

Upvotes: 1

Related Questions