Hello i have following piece of code:
'use client';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
import { useParams } from 'next/navigation';
export default function Navbar() {
const containerRef = useRef() as any;
const [selectedSection, setSelectedSection] = useState('');
useEffect(() => {
const handleHashChange = () => {
setSelectedSection(window.location.hash);
};
window.addEventListener('hashchange', () => {
console.log('called');
handleHashChange();
});
handleHashChange(); // Initial call to set the state based on the current hash
return () => {
window.removeEventListener('hashchange', handleHashChange);
};
}, []);
console.log(selectedSection);
const tl = gsap.timeline({ paused: true });
const { contextSafe } = useGSAP(
() => {
tl.to(containerRef.current, {
width: 150
})
.to('.link', {
opacity: 1,
background: 'inherit',
overflow: 'visible',
border: 'none',
stagger: { each: 0.2 }
})
.to('.label', { opacity: 1, stagger: { each: 0.2 } }, '<');
},
{ scope: containerRef }
);
const handleMouseEnter = contextSafe(() => {
tl.play();
});
const handleMouseLeave = contextSafe(() => {
tl.reverse();
});
return (
<nav
ref={containerRef}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
className='fixed flex flex-col transform top-1/2 -translate-y-1/2 gap-6 bg-black left-0 rounded-r-xl border px-1 py-3 border-red-500'
>
<Link
href='#sec1'
className={`link w-3 h-3 rounded-full border border-red-500 overflow-x-hidden ${
selectedSection === '#sec1' ? 'bg-red-500' : 'bg-black'
}`}
>
<span className='label opacity-0'>Sec1</span>
</Link>
<Link
href='#sec2'
className={`link w-3 h-3 rounded-full border border-red-500 overflow-x-hidden ${
selectedSection === '#sec2' ? 'bg-red-500' : 'bg-black'
}`}
>
<span className='label opacity-0'>Sec2</span>
</Link>
<Link
href='#sec3'
className={`link w-3 h-3 rounded-full border border-red-500 overflow-x-hidden ${
selectedSection === '#sec3' ? 'bg-red-500' : 'bg-black'
}`}
>
<span className='label opacity-0'>Sec3</span>
</Link>
<Link
href='#sec4'
className={`link w-3 h-3 rounded-full border border-red-500 overflow-x-hidden ${
selectedSection === '#sec4' ? 'bg-red-500' : 'bg-black'
}`}
>
<span className='label opacity-0'>Sec4</span>
</Link>
<Link
href='#sec5'
className={`link w-3 h-3 rounded-full border border-red-500 overflow-hidden ${
selectedSection === '#sec5' ? 'bg-red-500' : 'bg-black'
}`}
>
<span className='label opacity-0'>Sec5</span>
</Link>
</nav>
);
}
And everything works good if useEffect is comment in, but once is comment out useGsap is not executing,
any idea why is happening and how to prevent it?