I have made my first React app using Webpack with the create-react-app tool.
I have an unknown amount of images in a folder I would like to display as my apps background at random. Using some code from the Webpack docs and other threads I use this code in my component.
import React, { Component } from 'react';
import './styles/css/App.css';
function requireAll(r) {
r.keys().forEach(r);
var images = r.keys();
images = images.map( path => "./images/backgrounds/" + path );
console.log(images);
return images;
}
var images = requireAll(require.context('./images/backgrounds/', true, /\.jpg$/));
let randomIndex = Math.floor(Math.random() * images.length) + 0;
var randomImgRef = images[randomIndex];
class App extends Component {
render() {
return (
<div className="App" style={{backgroundImage: "url(" + randomImgRef + ")"}} >
<h1>hi</h1>
</div>
);
}
}
export default App;
This seems to work, the background style has the right path and my console logs the right path also. But no images are displayed, and I'm clueless.
I think Webpack might not be including the images in the build, though the code I'm using seems like it should do that. So I'm clueless.
Any ideas?