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.

Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
  • Does this answer your question? [How to perform string interpolation in TypeScript?](https://stackoverflow.com/questions/45399951/how-to-perform-string-interpolation-in-typescript) – jtbandes Aug 11 '23 at 01:54

3 Answers3

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>
Nikhil G
  • 2,096
  • 14
  • 18
2

It looks like you're almost there, but you're not properly concatenating the url variable within the style object. When you use curly braces {} within JSX, you're indicating that you want to embed JavaScript expressions within the JSX code. In your case, you need to ensure that the url variable is properly evaluated and inserted into the backgroundImage property.

Here's the correct way to do it:

var url = "/lectures/" + id + "/thumbnail.jpg";

style={{
  backgroundImage: `url(${url})`,
}}

In the code above, I've used template literals (denoted by backticks) to embed the url variable within the backgroundImage property. This way, the actual value of url will be inserted into the URL string, and it will correctly display the different images depending on the id.

So, for example, if id is 1, the generated style will be:

style={{
  backgroundImage: "url(/lectures/1/thumbnail.jpg)",
}}

And if id is 2, it will be:

style={{
  background-image: "url(/lectures/2/thumbnail.jpg)",
}}

And so on, adapting to the different values of id.

Meghshyam Sonar
  • 394
  • 3
  • 12
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

}}

  • 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](/help/how-to-answer). – Community Aug 14 '23 at 10:05