Search code examples
javascriptreactjsmernswiper.js

Setting a background as a image url


I am creating a real estate app with the MERN stack as well as utilizing Swiper as a image slider and I am encountering a issue when trying to set the background of a div to images with a slider that was uploaded when creating a real estate listing. I am mapping through the array of images correctly however when attempting to set the background I get nothing. Here is the snippet of the code that is not working.

    {listing && !loading && !error &&(
        <div>
            <Swiper navigation>
                {listing.imageUrls.map((url)=>(
                <SwiperSlide key={url}>
                <div
                    className='h-[550px]'
                    style={{
                    background: `url(${url}) center no-repeat`,
                    backgroundSize: 'cover',
                    }}
                ></div>
                </SwiperSlide>
                ))}
            </Swiper>
        </div>
)}

Solution

  • A few issues could be happening so here are some potential solutions:

    Make sure background positioning and size is correct as it acts differently than <img/> (see snippet below)

    Replacing your div with these styles should help(making sure the background fills the div and adding height to div):

         <div
            className='h-[550px]'
            style={{
              backgroundImage: `url(${url})`,
              backgroundPosition: 'center',
              backgroundRepeat: 'no-repeat',
              backgroundSize: 'cover',//adding size cover makes sure the image fills the entire div
              height: '550px !important', // must add base height if div is empty to still show background
            }}
          >
              Showing background for {url}
          </div> 
    
    

    If you still have an issue

    1. Make sure when you access the URL it is a path or URL to an image ONLY
    2. If your URL array is an array of objects and not strings then you need to destructure the url from the object first such as url.name which you can debug with a console log like this:
        {
          listing.imageUrls.map((url) => {
            console.log('attempting to use url:', url)
            return (
            <SwiperSlide key={url}>
              <div
                className="h-[550px]"
                style={{
                  background: `url(${url.name}) center no-repeat`,
                  backgroundSize: "cover",
                }}
              ></div>
            </SwiperSlide>
          );});
        }
    

    Other Additions

    Make sure your class h-[550] is not overriding any background or color styles (will cause background to not show) I suggest creating a classname for this specific element and add it to css instead of inline css.