0

I am giving my component 2 props src and alt so that it could display an image like so:

<img src={require(this.props.src)} alt={this.props.alt} />

Running my app gives me this error

Error: Cannot find module "."

I tried the image URL and it is correct and works, the app just doesn't want to work when I supply require the props.

3
  • Why do you need require? Can't you just have src={this.props.src} ? Commented Aug 6, 2017 at 20:12
  • Nope, webpack is handling all of the files. Commented Aug 6, 2017 at 20:18
  • 1
    You shouldn't require files like this in runtime. Give it an absolute path from the destination folder. Commented Aug 6, 2017 at 20:25

1 Answer 1

2

If you're using webpack, I'm going to assume that you're using the webpack image loader. If that's the case it means that you're importing your images in your component, probably using named imports. In that case you can pass the named import as a prop to either a child component or use it directly on the component where the import lives.

// named import
import landscape from "./img/landscape.jpg";
// child component
import Child from "./components/child";

const Parent = () => 
  <div>
    <Child src={landscape} />
  </div>;


// then the child component could look like this
const Child = (props) => 
  <div>
    <img src={props.src} />
  </div>;

If this is not the case, please give more information regarding how webpack is handling the images in your components.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.