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!
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`}}/>