Reputation: 312
I have a problem, I tried to transform in a class this function from this example : https://codesandbox.io/s/5vn3lvz2n4
But, I got an error. Here is the code :
import React, { Component, useCallback } from "react";
import Gallery from "react-photo-gallery";
import Carousel, { Modal, ModalGateway } from "react-images";
class Gallerie extends Component {
constructor(props){
super(props)
this.state = {
currentImage: 0,
setCurrentImage: 0,
viewerIsOpen: false,
setViewerIsOpen: false,
}
}
render(){
const openLightbox = useCallback((event, { photo, index }) => {
this.state.setCurrentImage(index);
this.state.setViewerIsOpen(true);
}, []);
const closeLightbox = () => {
this.state.setCurrentImage(0);
this.state.setViewerIsOpen(false);
};
return (
<div>
<Gallery photos={this.props.photos} onClick={() => openLightbox} />
<ModalGateway>
{this.state.viewerIsOpen ? (
<Modal onClose={() =>closeLightbox}>
<Carousel
currentIndex={this.state.currentImage}
views={this.props.photos.map(x => ({
...x,
srcset: x.srcSet,
caption: x.title
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
);
}
}
export default Gallerie;
Here is the problem and what I got :
I don't exaclty know what the useCallBack does. If I just copy / paste the example, it works. The problem is that the variable "photos" is used as props cause it will be different for each user. So I need it into other components. If I use a function like the example, I can't use props...
Thanks for your help.
Upvotes: 0
Views: 1242
Reputation: 21357
You're using a hook
inside a class
based component
. First convert it to a functional component
const Gallerie = props =>{
const [state, setState] = useState({
currentImage: 0,
setCurrentImage: 0,
viewerIsOpen: false,
setViewerIsOpen: false,
})
const openLightbox = useCallback((event, { photo, index }) => {
setState({...state, setCurrentImage: index, setViewerIsOpen: true});
}, []);
const closeLightbox = () => {
setState({...state, setCurrentImage: 0,setViewerIsOpen: false })
};
return (
<div>
<Gallery photos={props.photos} onClick={() => openLightbox} />
<ModalGateway>
{state.viewerIsOpen ? (
<Modal onClose={() =>closeLightbox}>
<Carousel
currentIndex={state.currentImage}
views={props.photos.map(x => ({
...x,
srcset: x.srcSet,
caption: x.title
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
);
}
Upvotes: 1