4

I am new to React and I appreciate if anyone could help...

I set up the environment using "create-react-app", and all image files are in img folder under src folder. One of components sets background image dynamically.

This works fine:

<div style={{ background: `url(${require("../img/file-name.jpg")}) no-repeat`}}/>

However, when I tried to use a variable for the file name (something like shown below), I get the error: Error: Cannot find module '../img/file-name.jpg'

let imageUrl = '../img/' + filenames[0];

...

<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>

I also tried something like below just for a test, but I got the same error.

let imageUrl = '../img/file-name.jpg';

...

<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>

I appreciate if anyone could help!! Thank you!

1
  • That is because require uses paths and when you separate the path, required would read the value but it would treat it as a string and include the .. or ./ as a string character not as a path separator. Commented Oct 15, 2020 at 9:00

1 Answer 1

6

There are a lot of similiar questions so I wont repeat my self, to understand why this code doesn't work you should research on how Webpack works.

One option it so move images to static folder, this snippet is valid:

const imageUrl = 'static/img/file-name.jpg';
<div style={{ background: `url(${require(imageUrl)}) no-repeat`}}/>

If you want to import from src folder, you must import if beforehand (file urls are resolved in build time due to webpack).

// or use require, doesn't metter
import img1 from '../img/cat.jpg';
import img2 from '../img/dog.jpg';

const imageURL = filenames[0] === cat ? img1 : img2;
<div style={{ background: `url(${imageURL}) no-repeat`}}/>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I ended up using the static folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.