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.
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
This shows the component post rendering and the style element is not present
What would prevent the style element from rendering even though is it populated from an object containing CSS properties?
use ES6 for this.
background: `url(${imageUrl}) no-repeat`
Add " surrounding the imageURL
{ background: "url(\"" + imageUrl + "\") no-repeat ..."}
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');
}
}}
/>
I believe that !important is the main culprit here. Simply remove it and everything should render with the variable inside.
Inline CSS will, as a general rule, override any CSS in your stylesheet assuming the same level of specificity.
Have a look at MDN for more info about specificity and !important to learn more
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
A rule about !important
!important inside inline stylingI think you might need to import the path in jsx
// require also works
background:`url(${import("./images/your_image")}) no-repeat 50% 40%`
If it does not work, try this:
style={{
backgroundImage: `url(${require('./images/your_image')})`,
backgroundRepeat: 'no-repeat',
}}