1

Using React 16.13.1, I have the follow class:

import React from "react";
const path = require('path');
class Portrait extends React.Component {
  render() {
    const vikingName = this.props.name.toLowerCase();  // Expected output of "ulf"
    return (
      <div>
        // below img tags go here
      </div>
    )
  }
}
export default Portrait

I'm trying to have a the src prop of the img tags be dynamic, so when the parent component calls it, it passes the name of the viking. The file directory is name-spaced.

This works:

<img src={require('../../../../res/img/ulf/picture.png') />

Error: "Module not found at '../../../../res/img/ulf/picture.png'

<img src={require(path.join('../../../../res/img', vikingName, 'picture.png'))} />

Error: "Module not found at '../../../../res/img/ulf/picture.png'

<img src={require(`../../../../res/img/${vikingName}/picture.png`)} />

When this.props is loading correctly, (this.props.name gives expected output) and all types are String and print the correct, same path, why do the bottom two do not work?

bananabrann
  • 556
  • 7
  • 26

1 Answers1

2

The problem isn't your code itself. The problem lays a little deeper in how Webpack bundles your code.

Webpack bundles your code and assets and creates an entirely new folder structure and/or filenames.

Webpack will turn a folder structure like this:

src
 - app.jsx
 - components
 - - MyComponent.jsx
 - assets
 - - image.jpg

into:

dist
- main.js
- image.jpg

The whole point about imports/exports is that they are static. Webpack will change all your paths behind the scenes to point towards the newly created bundled path during it's bundling process. That's why your first example works smoothly. That path has been defined before runtime, so before webpack bundles your code.

However...

Dynamic imports which are updated at runtime point towards a path which doesn't exist in your bundled code. That's why it throws an error that it can't find your file. Because there simply is no such file at that location in your bundled code.

Luckily there is a workaround for this issue


How to solve this:

It's possible to access the files path relative to your bundle using require.context. This allows you to parse your relative path to the bundled path and dynamically update your images.

This answer should be able to set you on your way.

Community
  • 1
  • 1
Luïs
  • 2,671
  • 1
  • 20
  • 33