Skip to content

Commit

Permalink
Merge pull request #174 from itoldya/rm-unsafe-lifecycles
Browse files Browse the repository at this point in the history
Keep currentImage index actual without using the deprecated componentWillReceiveProps hook
  • Loading branch information
benhowell authored Aug 14, 2022
2 parents 12708e1 + f174c02 commit 90e8c23
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
20 changes: 9 additions & 11 deletions src/Gallery.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,6 @@ class Gallery extends Component {
this.onResize();
}

componentWillReceiveProps (np) {
if (this.state.currentImage > np.images.length - 1) {
this.setState({currentImage: np.images.length - 1});
}
}

componentDidUpdate () {
if (!this._gallery) return;
if (this.getContainerWidth()
Expand All @@ -56,6 +50,10 @@ class Gallery extends Component {
return Math.floor(width);
}

getCurrentImageIndex() {
return Math.min(this.state.currentImage, this.props.images.length - 1)
}

openLightbox (index, event) {
if (event) {
event.preventDefault();
Expand Down Expand Up @@ -89,19 +87,19 @@ class Gallery extends Component {

gotoPrevious () {
if (this.props.currentImageWillChange) {
this.props.currentImageWillChange.call(this, this.state.currentImage - 1);
this.props.currentImageWillChange.call(this, this.getCurrentImageIndex() - 1);
}
this.setState({
currentImage: this.state.currentImage - 1
currentImage: this.getCurrentImageIndex() - 1
});
}

gotoNext () {
if (this.props.currentImageWillChange) {
this.props.currentImageWillChange.call(this, this.state.currentImage + 1);
this.props.currentImageWillChange.call(this, this.getCurrentImageIndex() + 1);
}
this.setState({
currentImage: this.state.currentImage + 1
currentImage: this.getCurrentImageIndex() + 1
});
}

Expand Down Expand Up @@ -202,7 +200,7 @@ class Gallery extends Component {
<Lightbox
images={this.props.images}
backdropClosesModal={this.props.backdropClosesModal}
currentImage={this.state.currentImage}
currentImage={this.getCurrentImageIndex()}
preloadNextImage={this.props.preloadNextImage}
customControls={this.props.customControls}
enableKeyboardInput={this.props.enableKeyboardInput}
Expand Down
11 changes: 11 additions & 0 deletions test/Gallery.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,17 @@ describe("Gallery Component", () => {
expect(arg2.target).toBeDefined();
expect(arg2.altKey).toBeDefined();
});

it("should switch lightbox image when current image is no longer present", () => {
const { rerender } = render(<Gallery images={[image1, image2]} />);
const [, secondItem] = screen.getAllByTestId(
"grid-gallery-item_thumbnail"
);
fireEvent.click(secondItem);
rerender(<Gallery images={[image1]} />);

expect(getLightboxImage()).toHaveAttribute("src", image1.src);
});
});

describe("Selection", () => {
Expand Down

0 comments on commit 90e8c23

Please sign in to comment.