Problem with displaying an image as a background on a div in react

38 views Asked by At

I have this problem where the image just won't be displayed as the background of the div. even though the image is displayed normally when put in an image tag.

<div className="card text-dark " style={{ backgroundImage: `url(${mainImg})` }}>
                        {/* <img
                            className="card-img"
                            src={mainImg}
                            alt="Creative Manner Design Lorem Ipsum Sit Amet Consectetur dipisi?"
                        /> */}
</div>

I have checked the css and the syntax with and various ai tools for help and just couldn't solve this problem.

i have changed the syntax to this: <div className="card text-dark" style={{ backgroundImage: "url(" + { mainImg } + ")" }}>

or this

<div className="card text-dark " style={{ backgroundImage: url(/${mainImg}) }}>

<div className="card text-dark " style={{ backgroundImage: url(./${mainImg}) }}>

still didn't work

2

There are 2 answers

0
Harish Krishnan On
<div className="card text-dark" 
     style={{ backgroundImage: `url(${mainImg})`, 
     height: '200px', width: '200px' }}>
</div>

Try adding height and width ? Assuming your path should be right.

0
Parvez Ahmed On

set your component this way

    import React from 'react';

const YourComponent = () => {
  const mainImg = 'https://example.com/image.jpg'; // Replace this with your image URL
  return (
    <div className="card text-dark" style={{ backgroundImage: `url(${mainImg})`}}>
    </div>
  );
};

export default YourComponent;