Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-slick Slider stays on same page if slides items are changed

I am stuck with an issue with react-slick. The subject line may not make sense, but I will try to explain the scenario in detail. See this example fiddle to see the issue in action.

var DemoSlider = React.createClass({
getSlides(count) {
var slides = [];
for(var i = 0; i < count; i++) {
    slides.push((<img key={i} src='http://placekitten.com/g/400/200' />));
}
return slides;
},

render: function() {
var settings = {
    dots: false,
  infinite: false,
  slidesToShow: 3,
  slidesToScroll: 3
}

var slides = this.getSlides(this.props.count);

return (
    <div className='container'>
    <Slider {...settings}>
        { slides }
    </Slider>
  </div>
);
}
});

In this demo, initially the slider shows 20 slides (3 per page). The idea is that if you click the button, it will generate a random number, which would be the new number of slides. The code is fairly simple and self-explanatory.

To reproduce the problem, 1. keep on clicking Next arrow until you reach the last slide.
2. click on the button that says 'Click' to generate a new random number of slides.

My expectation was that the slide will go back to the first slide but not to stay on the page where it previously was. Even worse, if the new number of slides is lower than the previous number, the user will see a blank page with no slides. On clicking Previous error, he/she can go to the previous slides, and everything works normally but the initial display ruins the user experience.

Is there something I am missing to add in the code, or is this a bug?

Thanks, Abhi.

like image 655
Abhishek Jain Avatar asked May 28 '16 14:05

Abhishek Jain


2 Answers

I would say it is rather a buggy behavior, but still you can achieve what you want by forcing a redraw after new collection has been passed as props, by resetting react's key:

<DemoSlider key={Date.now()} count={this.state.count}/> 

UPDATED FIDDLE

like image 98
artur grzesiak Avatar answered Oct 28 '22 16:10

artur grzesiak


Quick workaround: When you change to a new set of slides, remove the component, and reconstruct it again. It would then start with the first slide. You can do this by incrementing the key attribute of DemoSlider.

For a proper fix, you'd need to tell the component to change the 'current slide', so that it's not looking at a slide index beyond the end, but a casual look at the source at https://cdnjs.cloudflare.com/ajax/libs/react-slick/0.11.0/react-slick.js suggests it currently does not allow this. A change would need to be made to InnerSlider.componentWillReceiveProps() to check state.currentSlide against props.slidesToShow and state.slideCount.

It would also benefit from allowing currentSlide to be passed as props.

like image 22
John Valentine Avatar answered Oct 28 '22 15:10

John Valentine