react jsx inline style not rendering when populated from a variable

Viewed 552

I added an inline style element to a div tag in a react component along with a className element. The className property renders but the style is not displaying. I am setting from an object variable. However, if I set the style element directly using double curly braces it works, just not working from a variable.

Here is an image of the object value I am using to set the style element.

enter image description here

This shows where the style element should be getting set as the component is rendering, the styleElement object has a value set at this point

enter image description here

This shows the component post rendering and the style element is not present

enter image description here

What would prevent the style element from rendering even though is it populated from an object containing CSS properties?

5 Answers

It seems like your issue lies in the !important part. React doesn't support using !important in the style object. If you can get rid of that !important part it would be for the best, but if you can't then here is a workaround (taken from this SO answer):

<div
  ref={(node) => {
    if (node) {
      node.style.setProperty('background', `url(${imageUrl}) no-repeat 50% 40%`, 'important');
    }
  }}
/>

use ES6 for this.

background: `url(${imageUrl}) no-repeat`

the background image syntax is

background-image: url("img_tree.gif");

You are missing the " on between the file name. change to

{ background: 'url("' + imageUrl + '") no-repeat 50% 40% !important' }

the other thing you might want to check is make sure img_tree.gif is actually the correct path, usually, it should relative path or absolute path, something like ./img_tree.gif or http://example.com/img_tree.gif

also make sure have a background size

background-size: cover 

Add " surrounding the imageURL

{ background: "url(\"" + imageUrl + "\") no-repeat ..."}
Related