Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require local image in React

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/',
      },
   },
},
like image 302
Amphyx Avatar asked Jun 18 '26 07:06

Amphyx


1 Answers

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} />
like image 193
Amphyx Avatar answered Jun 19 '26 19:06

Amphyx