Search code examples

React passing import name as prop and adding to image src

I have a react component which has a prop passed with the name of an Import which contains an image path.

In this case the prop value is Ico1.

I need to pass the prop in the img src like so:

code below:

import React from 'react';
import Ico1 from '../icon1.png';

 const MyComp = (props) => <div>

           <img src={props.chosenicon} alt="" />



 export default MyComp

My problem is that when I add this:

<img src={Ico1} alt="" /> shows the image but if I do this:

<img src={props.chosenicon} alt="" /> shows no image, even though the value of props.chosenicon is 'Ico1' and typeof says they are both strings.

How can I get this to work so it shows the image?


  • Two components - App.js and Icon.js and an image called icon.jpg

    Here is your App.js

    import React from 'react';
    import icon from './icon.jpg';
    import Icon from './Icon';
    const App = () => (
        <h1>This is the app</h1>
        <Icon icon={icon} />
    export default App;

    And here is your Icon.js

    import React from 'react';
    const Icon = props => (
        <p>This is the icon</p>
        <img src={props.icon} alt="" />
    export default Icon;

    Here is a working example: