I am trying to load local JPG image by it's path that must be get from the props of the component. But when I try to do that, the image is not loaded and its src path looks like that:
Module {default: "/ff5a7601c48dcb99c92acfca45eb2439.png", __esModule: true, Symbol(Symbol.toStringTag): "Module"}
But when I use import statement, it outputs right path:
/fa8b72877658d9175b437ebb88e3ef2c.jpg
I can't use import, because I need to get the path in the body of the component. So, how can I properly load the file?
There are my JSX component:
import React from 'react';
import { Card } from 'react-bootstrap';
import '../../../resources/scss/style.scss';
class ArticleCard extends React.Component {
constructor(props) {
super(props);
}
render() {
const { article } = this.props;
return (
<Card>
<Card.Img variant="top" src={require(article.imagePath)} />
<Card.Body>
<Card.Title>{article.title}</Card.Title>
<Card.Text>{article.description}</Card.Text>
</Card.Body>
</Card>
)
}
}
export default ArticleCard;
and webpack.config.js fragment:
{
test: /\.(jpe?g|png|gif|svg|jpg)$/i,
use: {
loader: 'file-loader',
options: {
name: 'client/resources/images/[name].[ext]',
outputPath: 'dist/img/',
},
},
},
I've found a solution. require returns an object and image's path can be ejected from its default property:
<img src={require('path/to/img.png').default} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With