url for images not rendering when using template literals and Tailwind css

91 Views Asked by At

I used template literals to pass down fetched urls from my database to my react frontend, however, images don't g et rendered, only when I hard code the URL directly, here is my code:

import React, { useState, useEffect } from "react";
const Dotw = () => {
 const [driverHero, setDriverHero] = useState("");
useEffect(() => {
    const fetchData = async () => {
      const result = await fetch(URL);
      result.json().then((data) => {
        console.log(data)
      
        setDriverHero(data.heroImage);
  
      });
    };
    fetchData();
  }, []);

  return (
 
      <div className={`w-full h-40 md:h-96 lg:h-96 max-w-screen-lg bg-no-repeat bg-cover bg-center lg:bg-center bg-[url('${driverHero}')]`}></div>
     
  );
};

export default Dotw;

it displays correcly on the console:

it works when I use an img tag and set the src as the driverHero state but doesn't provide the same UI when used as background image instead

1

There are 1 best solutions below

0
On

The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS.

Dynamic class names in Tailwind

I would suggest putting the background in the style prop of the div like so:

<div
  className={`w-full h-40 md:h-96 lg:h-96 max-w-screen-lg bg-no-repeat bg-cover bg-center lg:bg-center`}
  style={{backgroundImage: `url(${driverHero})`}}
></div>