5

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
  • the path is correct. Commented Jun 9, 2019 at 15:23

1 Answer 1

8

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.