I'm building a landing page using React Router that has a scrolling menu. Based on the position of the scrolling menu, the background elements change. Everything works, until I navigate to a different page, and receive Uncaught TypeError: Cannot read property 'classList' of null. When I return to the landing page, the ScrollTrigger is broken until the site is refreshed. I know this is due to the component unmounting and ScrollTrigger not being able to find the elements triggering onLeave and onLeaveBack. I tried using useLocation() to make sure ScrollTrigger instantiate when the the pathname = "/" and otherwise kill() the trigger, but it didn't solve the issue.
So the question is, how do I navigate away from my landing page without having my ScrollTrigger break and require a full refresh?
Here is the structure of my ScrollTrigger:
const pages = ["radio", "shop", "music", "about", "news"];
useEffect(() => {
const backgroundSquare = document.querySelector(".home-menu-background");
pages.forEach((page) => {
gsap.to(`#home-menu-item-${page}`, {
scrollTrigger: {
trigger: `#home-menu-item-${page}`,
start: "top center",
end: "bottom center",
onEnter: () => {
backgroundSquare.style.backgroundImage = `url("${backgroundImages[page]}")`;
document.querySelector(`#home-menu-item-${page}`).classList.add("active");
},
onEnterBack: () => {
backgroundSquare.style.backgroundImage = `url("${backgroundImages[page]}")`;
document.querySelector(`#home-menu-item-${page}`).classList.add("active");
},
onLeave: () => {
document.querySelector(`#home-menu-item-${page}`).classList.remove("active");
},
onLeaveBack: () => {
document.querySelector(`#home-menu-item-${page}`).classList.remove("active");
},
},
});
});
});