Within my create-react-app project, I'm building a react component with an image in it. I want to pass the exact image location through as component-property (or -state). Within my component, I'm using require, like this:
<Image
height={"100px"}
borderRadius={8}
src={require(this.props.image)}
alt="logo"
/>
Which gives this error:
Error: Cannot find module '../images/restaurants/sea.jpeg'
webpackEmptyContext
src/components sync:2
However, when I hardcode the exact value I'm passing through the property into require it does work!
<Image
height={"100px"}
borderRadius={8}
src={require("../images/restaurants/sea.jpeg")}
alt="logo"
/>
Why does this work so counter-intuitively? And what is the best workaround?
Webpack needs to know about the file at the time of bundling - otherwise it won't include it (it's trying to keep the size of your bundle down).
If you pass the file path as a prop it doesn't know about it at bundle time - it only knows about it at runtime.
The suggested solution of passing the base64 encoded image is a good one - alternatively you could pass in a url to a publicly hosted image?