I am creating a React component that randomly cycles through a large number of background images. From my understanding, I could ignore Webpack here and just dynamically generate the require/import statements and pass them to the component.
However, if I want Webpack to use a loader and generate hashes, etc - I haven't found a solution.
This question is similar, but the responses don't address the problem: Dynamically Add Images React Webpack
My current solution involves just requiring all of the images in the component - however, I'm wondering what the 'costs' of this are - just an increased bundle size? Attached is sample code to demonstrate what I mean:
import React from 'react';
import styles from './Background.css';
const pic0 = require('./imgs/0.jpg');
const pic1 = require('./imgs/1.jpg');
const pic2 = require('./imgs/2.jpg');
const pic3 = require('./imgs/3.jpg');
// etc etc etc
class Background extends React.Component {
constructor(props) {
super(props);
this.state = {
pic: {},
};
this.changeBackground = this.changeBackground.bind(this);
}
componentWillMount() {
this.setState({ pic: pic0 });
}
componentDidMount() {
// set timeout here
}
changeBackground() {
// change background via component state here
}
render() {
return (
<img className={styles.background} src={this.state.pic} />
);
}
}
export default Background;
Thoughts? Any help would be greatly appreciated.