I am trying to implement a flexible lightbox component for displaying images. I am using this npm , image URL's i am getting from api.
How should I pass current image index value to (Which image clicked on) the component so that the adject image displayed on modal.
Below is the JSON that I am getting from backend
{
"count": 3,
"next": "http://127.0.0.1:8000/api/aws/gallery/all-gallery/?page=2",
"previous": null,
"results": [
{ "id": 127, "gallery_img_url": "https://mysite.amazonaws.com/gallery/test2.jpg" },
{ "id": 126, "gallery_img_url": "https://mysite.amazonaws.com/gallery/CaptureXYZ.PNG" },
{ "id": 125, "gallery_img_url": "https://mysite.amazonaws.com/gallery/Capture2.PNG" }
]
}
onClick image I am passing this id from results array to the component, I think this might be the issue, Can Someone please suggest me how to pass the exact index value (precisely, Image clicked on) to the component.
Here is my component
import React, { Component } from 'react'
import { connect } from 'react-redux';
import { getAllGalleryImages } from '../actions/gallery';
import Lightbox from 'react-image-lightbox';
import 'react-image-lightbox/style.css';
class ViewGalleryImage extends Component {
state = {
photoIndex: 0,
isOpen: false,
}
componentDidMount() {
// this will Fetch data from api
this.props.getAllGalleryImages();
window.scrollTo(0, 0)
}
render() {
const { photoIndex, isOpen } = this.state;
const images = [];
this.props.images && this.props.images.results && this.props.images.results.map(result =>
images.push(result.gallery_img_url),
)
return (
<div>
{this.props.images.count === 0 ? <p><strong>No Images found!</strong></p> :
<React.Fragment>
{this.props.images && this.props.images.results && this.props.images.results.map(result =>
<div className='masonry-item' key={result.id}>
<img src={result.gallery_img_url} onClick={() => this.setState({ isOpen: true, photoIndex: result.id })} alt='myImage' className='dlt_blg_img' />
</div>
)}
</React.Fragment>
}
{
isOpen && (
<Lightbox
mainSrc={images[photoIndex]}
nextSrc={images[(photoIndex + 1) % images.length]}
prevSrc={images[(photoIndex + images.length - 1) % images.length]}
onCloseRequest={() => this.setState({ isOpen: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex: (photoIndex + images.length - 1) % images.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex: (photoIndex + 1) % images.length,
})
}
/>
)
}
</div>
)
}
}
const mapStateToProps = state => ({
isLoading: state.gallery.isLoading,
images: state.gallery
});
export default connect(
mapStateToProps,
{ getAllGalleryImages }
)(ViewGalleryImage);
I have found a simple solution for this. I think it might help newbie like me.
Below is the part of updated component