From 30e3110388a13dc89644fdc642515d15b69e6608 Mon Sep 17 00:00:00 2001 From: Sean LeBlanc Date: Tue, 11 Feb 2020 11:13:44 -0800 Subject: [PATCH] fix: prevent `currentSlide` from going out of bounds of `totalSlides` (#240) * prevent currentSlide from going out of bounds * Update CarouselProvider.test.jsx --- src/CarouselProvider/CarouselProvider.jsx | 4 ++++ src/CarouselProvider/__tests__/CarouselProvider.test.jsx | 8 +++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/CarouselProvider/CarouselProvider.jsx b/src/CarouselProvider/CarouselProvider.jsx index a5072dbe..0684d7d3 100644 --- a/src/CarouselProvider/CarouselProvider.jsx +++ b/src/CarouselProvider/CarouselProvider.jsx @@ -133,6 +133,10 @@ const CarouselProvider = class CarouselProvider extends React.Component { newStoreState.slideTraySize = slideTraySize(this.props.totalSlides, this.props.visibleSlides); } + if (this.carouselStore.state.currentSlide >= this.props.totalSlides) { + newStoreState.currentSlide = this.props.totalSlides - 1; + } + if (Object.keys(newStoreState).length > 0) { this.carouselStore.setStoreState(newStoreState); } diff --git a/src/CarouselProvider/__tests__/CarouselProvider.test.jsx b/src/CarouselProvider/__tests__/CarouselProvider.test.jsx index ca82b896..605d51bf 100644 --- a/src/CarouselProvider/__tests__/CarouselProvider.test.jsx +++ b/src/CarouselProvider/__tests__/CarouselProvider.test.jsx @@ -49,6 +49,12 @@ describe('', () => { expect(instance.carouselStore.state.slideSize).toBe(25); expect(instance.carouselStore.state.slideTraySize).toBe(200); }); + it('should keep currentSlide within bounds of totalSlides', () => { + const wrapper = shallow(); + const instance = wrapper.instance(); + wrapper.setProps({ totalSlides: 3 }); + expect(instance.carouselStore.state.currentSlide).toEqual(2); + }); it('should not update the carouselStore if some prop we do not track changes', () => { const wrapper = shallow(); const instance = wrapper.instance(); @@ -58,7 +64,7 @@ describe('', () => { expect(start).toEqual(end); }); it('should not reset the currentSlide or disableAnimation values when unrelated props change', () => { - const wrapper = shallow(); + const wrapper = shallow(); const instance = wrapper.instance(); instance.carouselStore.setStoreState({ currentSlide: 2 }); const start = clone(instance.carouselStore.state);