Passing an image to a react.js component

Viewed 3766

I'm creating a website and i want to pass an image url to a component. How do i do it?

I tried:

App.js :

    import React from 'react';
    import './App.css';

    import Elem from './Elem.js';

    const App = () => {

      return (

          <Prod imgUrl="../../url/to/img.png"/>

        </div>
      );
    }

    export default App;

Elem.js :

    import React from 'react';
    import './Elem.css';

    const Prod = ({imgUrl}) => {
        return (
            <div className="elem">
                <div className="elemImg">
                    <img src={require(`${imgUrl}`)} alt="" />
                </div>
            </div>
        );
    }

    export default Elem;

But it give me error:

Error: Cannot find module '../../url/to/img.png'

1 Answers

I would suggest importing images instead of using the path directly.

import myImage from 'path/to/image.png'

const App = () => <ImageComponent src={myImage} />

const ImageComponent = props => <img src={props.src} />

If you really want to use the path directly, I would suggest adjusting your path from your entry point.

Assuming your entry point is index.html, your relative path should be based on that file not from the JS file.

Related