If you have a list of potential images at build time, you can use the dynamic import
function to load them, although this will return a promise like so:
export class ImageLoader extends React.Component {
constructor(props: any){
super(props);
this.state = {
imagePath: undefined
};
}
render() {
if(this.state.imagePath)
return <img src={this.state.imagePath} />; // Render the image
import(/* webpackMode: "eager" */`../imgs/${this.props.imageName}.png`) // Bundle all paths of images into the bundle
.then((imagePath: string) => {
this.setState({ imagePath}); // Set the new state with the loaded image path
});
return null; // Don't render anything right now since the image hasn't loaded yet.
}
}
This will bundle ALL png images under the imgs directory, use a switch
statement with all possible names if that is too much.
See Webpack Documentation and How does Dynamic Import in webpack works when used with an expression?