Home > Enterprise >  React div background in react not rendering
React div background in react not rendering

Time:05-20

I have a prop being injected in my component called headerImage. I know it's there because when I place it in the HTML of the component like so:

<h1>Hello, {headerImage}</h1>

It renders correctl URI of the image in the above snippet.

However when I place it in my div background style, it won't render for whatever reason:

<div
                className="hide-on-mobile center-image"
                style={{
                  backgroundImage: `url({headerImage})`,
                  backgroundSize: "cover",
                  backgroundRepeat: "no-repeat",
                  backgroundPosition: "right",
                  width: "100%",
                  height: "auto",
                }}
              ></div>

I see it in the developer tools not being properly evaluated:

enter image description here

What am I doing wrong here?

CodePudding user response:

I think you may just be missing a $ evaluation before you try and pass through ${headerImage}.

<div className="hide-on-mobile center-image"
  style={{
    backgroundImage: `url(${headerImage})`,
    backgroundSize: "cover",
    backgroundRepeat: "no-repeat",
    backgroundPosition: "right",
    width: "100%",
    height: "auto",
  }}
></div>

CodePudding user response:

So, to nest variables within an attribute, you must quote the whole attribute, then inject an interpreted variable in to that using the ${} notation.

This is the same technique that you would use if you need to inject more than one class names. Since that is an simpler example, let me share that first, which may make more sense due to the simplicity and that it's using two variables instead of just one, then I'll expand it to your attribute.

So to start off with, I have a css source tied to my component. I'm including this so you know where "styles" is defined. import styles from './PageHeader.module.css';

Then within my component, where I use the two class names from "styles":

<span className={`${styles.left} ${styles.headerlink}`}>

Notice className={} has the back-tick quote within the {}.

So then to extend to your attribute:

  className="hide-on-mobile center-image"
      style={`
          backgroundImage: "url(${headerImage})",
          backgroundSize: "cover",
          backgroundRepeat: "no-repeat",
          backgroundPosition: "right",
          width: "100%",
          height: "auto"
       `}

Hopefully that helps.

  • Related