Search code examples
javascriptreactjs

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="" />

         </div> 
     }

 </div>

 export default MyComp

My problem is that when I add this:

<img src={Ico1} alt="" />

...it shows the image but if I do this:

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

...it 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?


Solution

  • 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 = () => (
      <div>
        <h1>This is the app</h1>
        <Icon icon={icon} />
      </div>
    );
    
    export default App;
    

    And here is your Icon.js

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

    Here is a working example: https://codesandbox.io/s/4z64wyqnn9