javascriptnode.jsreactjsswiper.jsreact-swiper

Swiper not showing background image from local directory in react


I tried adding image from the project local repo called "images" and use it as background image in the swiper carousel, but the image is not displaying. It's showing only the and

write-up. The background image is not showing. The write up suppose to be on top of the image and slide along with the image. Here is my code. Please I need help in resolving the background image issue.

<section className="site-section pt-5 pb-5">
  <div className="container">
    <div className="row">
      <div className="col-md-12">
        <Swiper
          spaceBetween={30}
          centeredSlides={true}
          autoplay={{
            delay: 2500,
            disableOnInteraction: false
          }}
          pagination={{
            clickable: true
          }}
          navigation={true}
          modules={[Autoplay, Pagination, Navigation]}
          className="mySwiper"
        >
          <SwiperSlide>
            <a
              href="blog-single.html"
              className="a-block d-flex align-items-center height-lg"
              style={{
                backgroundImage: "url('src/images/img_1.jpg')"
              }}
            >
              <div className="text half-to-full">
                <span className="category mb-5">Cybersecurity</span>
                <div className="post-meta">
                  <span className="author mr-2">
                    <img src="src/images/person_1.jpg" alt="author" />
                    Sneid{' '}
                  </span>
                  {'. '}
                  <span className="mr-2">June 20, 2022 </span>
                  {'. '}
                  <span className="ml-2">
                    <span>
                      <CommentIcon sx={{ fontSize: 14 }} />
                    </span>
                    {' 3'}
                  </span>
                </div>
                <h3>How to protect yourself in the cyber world</h3>
                <p>
                  Lorem ipsum dolor sit amet, consectetur adipisicing
                  elit. Quidem nobis, ut dicta eaque ipsa laudantium!
                </p>
              </div>
            </a>
          </SwiperSlide>
        </Swiper>
      </div>
    </div>
  </div>
</section>

Solution

  • You should save the photos in the public folder and then instead of src, you should give the relative path of the photo you want from the public folder. React itself understands where the image path is. Move images/person_1.jpg from src folder to public folder and put images/person_1.jpg instead of src/images/person_1.jpg in src attribute.

    first way:

    <img src="/images/person_1.jpg" alt="author" />
    

    second way:

    <img src={process.env.PUBLIC_URL + "/images/person_1.jpg"} alt="author" />
    

    PUBLIC_URL is the public folder path of your React project.

    I hope you can solve your problem with what I said.