David Miller
Posted on December 8, 2023
I've been trying to solve this problem for a while and just don't know what to do. I am trying to dynamically load background images according to what button is clicked. Since I don't have images for all of the buttons yet, I want a fallback background color. I've tried try/catch. I've tried an inline ternary operator for the inline CSS backgroundImage prop.. I Googled the fs library (I think it is) . Nothing is working. I stopped trying for the background color just so I can get to where Here's where I am right now:
` const tryRequire = (path) => {
try {
return require(path);
} catch (err) {
console.log(err.message);
return null; // Return null if the image is not found
}
};
const backgroundImage = tryRequire(
../images/category/${topic}/${topic}.jpg
);
style={{ backgroundImage: backgroundImage
? url(${backgroundImage})
: "none",
backgroundColor: backgroundImage ? "lightgrey" : "purple",}}`
Posted on December 8, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.