Home > Software engineering >  Conditional background image
Conditional background image

Time:04-03

I would like to display picture in the background, it works fine but my api does not always show pictures. So I would like to create a conditional that displays another picture instead. I don't know where to display my conditional, in style or in the url? I made several tests but I can't do it.

const bannerStyle = {
        backgroundImage: `url("https://image.tmdb.org/t/p/original/${movie.backdrop_path}")`,
        backgroundPosition: "center",
        backgroundSize: "cover"
    }

 <div style={bannerStyle}>
    ...
 </div>

CodePudding user response:

In your div write a ternary in style:

<div 
  style={ bannerStyle.backgroundImage === 'something' ? `urlA` : `urlB` }  
/>

Or set a background image as a default.

CodePudding user response:

I am considering you're using React or NextJS kind of framework.

You can add condition to the whole link.

const bannerStyle = {
        backgroundImage: `url(${movie?.backdrop_path ? `https://image.tmdb.org/t/p/original/${movie?.backdrop_path}` : "Another Image Link"})`,
        backgroundPosition: "center",
        backgroundSize: "cover"
    }
  • If there is some value movie?.backdrop_path, then it returns path else it returns undefined.

You can then add bannerStyle object in style.

 <div style={bannerStyle}>
    ...
 </div>

CodePudding user response:

Maybe you could use an img tag to do it. You could just use a <img src={} /> tag with a simple ternary condition.

  • Related