0

i am very new to React, i am trying to use react slick, so as to achieve image as background with carousel . but when i try to do it, i am getting blank instead of image. i cannot see my inline style as well when i inspect. but if i use tag that is showing the image.

enter image description here

below is the code

import React, { Component } from 'react';
import './home.css';
import Slider from "react-slick";
import image2 from '../../images/image2.jpg';
import image1 from '../../images/image1.jpg';
import image3 from '../../images/image3.jpg';



class Home extends Component{


  render(){

    let pics = [
      {"name":"pic_1",
        "url": image1
      },
      {"name":"pic_2",
        "url": image2
      },
      {"name":"pic_3",
        "url": image3
      }
    ]

    let settings = {
      dots: true,
      infinite: true,
      speed: 500,
      slidesToShow: 1,
      slidesToScroll: 1
    }
    return(

          <div >
            <Slider {...settings}>
              {pics.map((picture, i)=>{
                return(
                  <div key={i} style={{
                    backgroundSize: 'cover',
                    border: 'none',
                    height: '100vh',
                    backgroundImage: `url(${picture.url})`

                  }}>
                  <div>
                    {picture.name}
                  </div>

                  </div>
                )
              }
            )
          }
            </Slider>
          </div>

    )
  }
}

export default Home;

i try going through this answer Setting a backgroundImage With React Inline Styles but this didn't resolve my problem.

thanks in advance!

Milan Mangar
  • 41
  • 1
  • 9

1 Answers1

0

Slick changes the css style of the root element of each slide.

Add your actual slide image as a child of each slide's first element.

This way it works for me:

<Slider {...settings}>
  {slideshowImages.map((image, index) => (
    <div key={index} style={{width: '100%', height: '400px'}}>
      <div
        style={{
          backgroundImage: `url(${image.url})`,
          width: '100%',
          height: '400px',
          backgroundSize: 'cover',
          backgroundPosition: 'center'
        }} />
    </div>
  ))}
</Slider>

Note that I am setting the same width & height to the root element of each slide and its child element holding the image. These dimensions may not work for you specific slideshow.

Antonio Brandao
  • 1,353
  • 13
  • 19