0

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.

1

2 Answers 2

2
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>
Sign up to request clarification or add additional context in comments.

Comments

1

The way you have accessed the variable is incorrect. Try it like this

style={{ backgroundImage: url(${url}),// Use backticks to interpolate the url variable

}}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.