skip to Main Content

I am trying to show different background images depending on an image id:

var url = "/lectures/" + id +"/thumbnail.jpg";
...
style={{
          backgroundImage: "url({url})",
        }}
...

For example, if the id was 1, I would have backgroundImage: "url('/lectures/1/thumbnail.jpg')" I have tried this, and the image displays correctly. However, I want to display a different image depending on the id. It seems that using {} does not work since the field itself (backgroundImage) takes in a string.

2

Answers


  1. var url = "/lectures/" + id + "/thumbnail.jpg";
    
    // Inside your JSX component
    <div
      className="your-container-class"
      style={{
        backgroundImage: `url(${url})`, // Use backticks to interpolate the url variable
      }}
    >
      {/* Your content */}
    </div>
    
    Login or Signup to reply.
  2.  style={{
    backgroundImage: `url(${url})`,
    

    }}

    Try it like this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search