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

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay