1

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?

Draxy
  • 565
  • 3
  • 6
  • 20
  • Is the images folder added to your web root? What if you go directly to the image in your browser, do you see it? What does the dev console "network" tab says about those images, any errors? – roychri Jan 11 '18 at 23:03
  • @roychri Can you explain further about the image folder and web root? I'm new to webpack. Also no, going to the url in the browser shows no image, and there are no errors in my network tab. – Draxy Jan 11 '18 at 23:18
  • webroot is the folder that contains the final application. If it was an HTML site, it would be the folder where the main index.html is. You gotta make sure the images folder ( the one mentionned in your code) is available from your web root so that your browser can access them. – roychri Jan 12 '18 at 01:45

1 Answers1

0

I think for your example you just have to use randomImgRef.default so use the default property to get the url.

EXAMPLE Using require.context to display images:

const photos = importAll(require.context('../../assets/photos', false, /\.(png|jpe?g|svg)$/));
   

Render:

<div>
    {photos.map((photo, i) => (
        <div className="photo" key={i}>
            <img src={photo.default} alt=`photo-${i}` />
        </div>
    ))}
</div>
StefanBob
  • 4,857
  • 2
  • 32
  • 38