Error: Cannot find module './' When importing images in React?

I'm pulling in some data from a .json to propagate a grid in a react app I'm working on.

{props.title} and {props.author} are returning correctly but I cannot get the image to appear. Currently i'm landing on an "Error: Cannot find module './'" page when going to this route.

I'm convinced its my file path to /assets/images but can't get it worked out.

Here's my file path:

```
src
 ┣ assets
 ┃ ┗ images
 ┃ ┃ ┣ burger-logger.png
 ┃ ┃ ┗ green_cup.png
 ┣ components
 ┃ ┣ About
 ┃ ┃ ┣ About.js
 ┃ ┃ ┣ Hello.js
 ┃ ┃ ┗ index.scss
 ┃ ┣ PortfolioGrid
 ┃ ┃ ┣ PortfolioGrid.js
 ┃ ┃ ┗ tileData.js
 ┃ ┣ Header.js
 ┃ ┗ Hero.js
 ┣ pages
 ┃ ┣ Home
 ┃ ┃ ┣ index.js
 ┃ ┃ ┗ style.css
 ┃ ┗ Portfolio
 ┃ ┃ ┗ index.js
 ┣ App.js
 ┣ index.css
 ┣ index.js
 ┗ projects.json
```

Here's the grid component -

```
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import GridList from '@material-ui/core/GridList';
import GridListTile from '@material-ui/core/GridListTile';
import GridListTileBar from '@material-ui/core/GridListTileBar';
import ListSubheader from '@material-ui/core/ListSubheader';
import IconButton from '@material-ui/core/IconButton';
import InfoIcon from '@material-ui/icons/Info';
import Projects from '../../projects.json';
import '../../assets/images/burger-logger.png';

const useStyles = makeStyles((theme) => ({...

/**
 
export default function PortfolioGrid(props) {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <GridList cellHeight={180} className={classes.gridList}>
        <GridListTile key="Subheader" cols={2} style={{ height: 'auto' }}>
          <ListSubheader component="div"></ListSubheader>
        </GridListTile>
        {Projects.map((props) => (
          <GridListTile key={props.image}>
            <img src={require(`../../assets/images/${props.image}`)} alt={props.title} />
            <GridListTileBar
              title={props.title}
              subtitle={<span>by: {props.author}</span>}
              actionIcon={
                <IconButton aria-label={`info about ${props.title}`} className={props.icon}>
                  <InfoIcon />
                </IconButton>
              }
            />
          </GridListTile>
        ))}
      </GridList>
    </div>
  );
}
```

Here's the .json structure -

```
[
  {
    "id": 1,
    "title": "Burger-Logger",
    "image": "burger-logger.png",
    "author": "Me"
  },
  {
    "id": 2,
    "title": "test",
    "image": "",
    "author": "Me"
  }
]
```

Sorry for the wall of text. Any direction greatly appreciated.

1 answer

  • answered 2020-10-29 22:12 krimo

    Try this

    <img src={require(`../assets/images/${props.image}.png`)}/>