DEV Community

David Miller
David Miller

Posted on

1

Dynamic background image loading

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",}}`

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs