Why does React use State not display img by default?

Viewed 47

I have a code that should change the banner under certain circumstances, and it does, but I want useState to leave the banner by default when the conditions are not met, but it does not see it. Although when I output its value to the console, it works for manual input.

 import {useState } from "react";
 import banner from '/public/images/banner.webp'
    
 export function MainBanner() {
    
   const [pic, setPic] = useState(`${banner.src}`)

CSS:

 .banner {
                        display:flex; 
                        width: 100%;
                        height: 600px;
                        justify-content: center;
                        background-blend-mode: darken;
                        background: rgba(0, 0, 0, .50);
                        background-position: center center;
                        background-image: url('${pic}');
                        background-repeat:no-repeat;
                        background-size:cover;   
         }

The problem is that the default value is not visible and is equal to : enter image description here

When the condition is not met useState should leave the default path to the banner, why doesn't it see the default path? When I output it to the console, by default it is /_next/static/media/banner.5954803e.webp and if I put it in css without using useState, then everything works

2 Answers

You can use console.log(banner) to view your imported "banner" and you will see it is a string like "/static/media/...", which is the url string you can used as the url content.

So you can use "banner" below:

const [pic, setPic] = useState(banner)

.banner {
  background-image: url(`${pic}`);
}

Update: use inline style

<Banner style={{backgroundImage: `url(${pic})`}}/>

The statement import banner from '/public/images/banner.webp' refers to the exported content of the file, in this case, the banner itself. So, ${banner.src} will always be undefined. You can directly set the path in useState itself, like this:

const [pic, setPic] = useState(`/_next/static/media/banner.5954803e.webp`)
Related