Skip to content

Commit

Permalink
Merge pull request #64 from erichbehrens/fix/handle-dynamic-children
Browse files Browse the repository at this point in the history
Handle dynamic children
  • Loading branch information
erichbehrens authored Oct 18, 2018
2 parents 17854c9 + 8a7bf43 commit 77e1001
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-animated-slider",
"version": "1.1.3",
"version": "1.1.4",
"description": "Animated slider component for react",
"main": "build/index.js",
"scripts": {
Expand Down
7 changes: 7 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ class Slider extends React.PureComponent {
}
}

componentWillReceiveProps(props) {
this.slideCount = React.Children.count(props.children);
if (this.state.currentSlideIndex >= this.slideCount) {
this.setState({ currentSlideIndex: 0 });
}
}

setupAutoplay = () => {
if (this.props.autoplay && !this.isMouseOver) {
this.stopAutoplay();
Expand Down
32 changes: 32 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,35 @@ test('test autoslide enabled', () => {
expect(animatedSnapshot).toMatchSnapshot();
expect(animatedSnapshot).not.toEqual(initialSnapshot);
});

test('can handle adding children', () => {
const slider = ReactTestRenderer.create(<Slider><div /><div /></Slider>);
expect(slider.getInstance().slideCount).toBe(2);
slider.update(<Slider><div /><div /><div /></Slider>);
expect(slider.getInstance().slideCount).toBe(3);
});

test('can handle removing children', () => {
const slider = ReactTestRenderer.create(<Slider><div /><div /><div /></Slider>);
expect(slider.getInstance().slideCount).toBe(3);
slider.update(<Slider><div /><div /></Slider>);
expect(slider.getInstance().slideCount).toBe(2);
});

test('should not reset currentSlideIndex when removing next slide(s)', () => {
const slider = ReactTestRenderer.create(<Slider slideIndex={1}><div /><div /><div /></Slider>);
expect(slider.getInstance().slideCount).toBe(3);
expect(slider.getInstance().state.currentSlideIndex).toBe(1);
slider.update(<Slider><div /><div /></Slider>);
expect(slider.getInstance().slideCount).toBe(2);
expect(slider.getInstance().state.currentSlideIndex).toBe(1);
});

test('should reset currentSlideIndex when removing current slide', () => {
const slider = ReactTestRenderer.create(<Slider slideIndex={2}><div /><div /><div /></Slider>);
expect(slider.getInstance().slideCount).toBe(3);
expect(slider.getInstance().state.currentSlideIndex).toBe(2);
slider.update(<Slider><div /><div /></Slider>);
expect(slider.getInstance().slideCount).toBe(2);
expect(slider.getInstance().state.currentSlideIndex).toBe(0);
});

0 comments on commit 77e1001

Please sign in to comment.