How do I add the same CSS property (e.g. background-image) multiple times with React?

Viewed 410

I want to do the equivalent of style="background-image: url(foo.jpg); background-image: -webkit-image-set(url(foo_1x.jpg) 1x, url(foo_2x.jpg) 2x)" in a React component.

React requires me to provide a style object, not a string. But a JS object can't have the same property twice.

How do I get two background-image properties? Also, the order is significant – the image-set needs to be last.

It needs to be an inline style. (Because the URL is a dynamic, interpolated value retrieved from DB.)

2 Answers

I think I initially misunderstood your question. Seems you are looking to create a style object to pass as a prop to a component. You can combine your background images into a single comma separated list. You can use a string template to inject the dynamic image urls at runtime.

const style = {
  backgroundImage: `url(${url1}),-webkit-image-set(url(${url2}) 1x, url(${url3}) 2x)`,
};

"spassvogel" on GitHub has a clever solution using CSS variables: https://github.com/facebook/react/issues/20757#issuecomment-776191029

The idea is to set CSS variables in the style property, like

style={ "--url1": "url(1.jpg)", "--url2": "url(2.jpg)" }

and then using them from an external style sheet, like

background-image: var(--url1);

and so on.

Turns out this still wasn't enough to solve everything I wanted – this rabbit hole runs ever deeper – but that's no fault of React's, so I'll consider this a valid answer.

Related