So I have a GatsbyImage component which is styled using styled components. It has an onClick event listener which is used to trigger a popup with the image.
So while I'm running the project on my PC using npm run develop everything is working as it should. I can click on an image and the openImageModalHandler function runs.
The issue only appears after I deploy the website to a service like Netlify or Gatsby Cloud.
So if I access the home page of the website first and then go to a page that contains an image (generated from a template) everything works as it should.
But if I go directrly to a page that is generated from a template and contains an image the onClick event listener doesn't appear on the images. I even added a console.log confirms that the event listener is not added to the images.
Here is a link to the home page: https://goofy-beaver-7fc18b.netlify.app/
Here is a link to a page with images: https://goofy-beaver-7fc18b.netlify.app/Assassin's%20Creed%20III/
GitHub: https://github.com/DantchoLV9/gamer8
The image component:
import React, { useState } from "react";
import { GatsbyImage, getImage } from "gatsby-plugin-image";
import useKeypress from "../../hooks/useKeypress";
import styled from "styled-components";
const Image = ({ image, alt }) => {
const [imageModalState, setImageModelState] = useState(false);
const openImageModalHandler = () => {
document.body.style.overflow = "hidden";
console.log("test");
setImageModelState(true);
};
const closeImageModalHandler = (e) => {
if (e !== undefined) {
if (e.target.classList.contains("background")) {
document.body.style.overflow = "auto";
setImageModelState(false);
}
} else {
document.body.style.overflow = "auto";
setImageModelState(false);
}
};
useKeypress("Escape", closeImageModalHandler);
return (
<>
<StyledImage
onClick={openImageModalHandler}
image={getImage(image)}
alt={alt}
/>
{imageModalState && (
<ImageModalBackground
className="background"
onClick={closeImageModalHandler}
>
<ModalImage image={getImage(image)} alt={alt} />
</ImageModalBackground>
)}
</>
);
};
const StyledImage = styled((props) => <GatsbyImage {...props} />)`
margin-bottom: 1rem;
border-radius: 10px;
cursor: pointer;
`;
const ImageModalBackground = styled.div`
width: 100%;
padding: 0rem 5rem;
min-height: 100vh;
background: rgba(0, 0, 0, 0.5);
position: fixed;
top: 0;
left: 0;
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
@media (max-width: 780px) {
padding: 0rem 2rem;
}
`;
const ModalImage = styled((props) => <GatsbyImage {...props} />)`
border-radius: 10px;
max-width: 100%;
cursor: default;
`;
export default Image;