Searching around...lots of suggestions but nothing feels "right". I want to have a true dynamic CSS background image:
const StyledDiv = styled.div`
background-image: url(${props => props.img});
width: 200px;
`;
using my react component, I want to avoid having a long list of import img1 from "../../img1.jpg"; import img2 from "../../img2.jpg" and so on (as example).
So I am trying to use require.context(path) to generate the number of items in the directory. And I implement like so:
import React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import hdImg from "../../../public/assets/img/hd_bgimage.jpg";
// get the number of items in the directory
const imageKeys = require
.context("../../../public/assets/img/bgs/", true)
.keys();
function getBgImage(num) {
const imageUrl = require(`../../../public/assets/img/bgs/${num}_bgimage.jpg`);
return imageUrl;
}
const StyledDiv = styled.div`
background-image: url(${props => props.img});
width: 200px;
`;
const StyledImg = styled.img`
width: 200px;
`;
const Home = () => {
return (
<div>
<h1>Hello World</h1>
<div id="container">
{imageKeys.map((item, i) => (
// loop over items from context
<StyledDiv id="image-bg" img={getBgImage(i + 1)} key={item}>
this is a background image CSS
</StyledDiv>
))}
</div>
<StyledImg id="img" src={hdImg}></StyledImg>
<Link to="/link">Test Link</Link>
</div>
);
};
export default Home;
webpack.config.base:
module.exports = {
entry: {
app: [path.join(__dirname, "./src/scripts")],
},
output: {
publicPath: "/",
filename: "[name]-bundle.js",
},
module: {
rules: [
// js removed
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: "url-loader",
options: {
limit: 8192,
name: "[name].[ext]",
},
},
],
},
],
},
it's working out "fine" when rendered in UI:
but i don't love the code here.
If i try to use just const imgContext = require.context("../../../public/assets/img/bgs/, true)
and then reference imgContext(i) the relative path of ./1_bgimage.jpg) doesn't get found so it seems like I need the full url including ../../../public/assets/img/bgs/.
Is there something I am missing?
Is there something I can do with my webpack config to not have to declare ../../../public??
