Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to use ref with Next.js for a Link and an <a>?

I'm trying to animate the elements of a menu with GSAP.

I'm using hooks like useRef and it works fine with the <a> elements which are links to an external website but not for the <Link> elements for internal routes.

Menu:

<nav>
    <ul>
        <li>
            <Link
              onMouseEnter={e => handleHover(e)}
              onMouseOut={e => handleHoverExit(e)}
              ref={line1} href="/nouveautes"> Nouveautés</Link>
        </li>
        <li>
            <Link
              onMouseEnter={e => handleHover(e)}
              onMouseOut={e => handleHoverExit(e)} ref={line2} href="/catalogue"> Catalogue</Link>
        </li>
        <li>
            <a
               onMouseEnter={e => handleHover(e)}
               onMouseOut={e => handleHoverExit(e)} ref={line3} 
               href="https://shop.paradisepapers.fr/"> Diffusion</a>
        </li>
        <li>
            <Link
              onMouseEnter={e => handleHover(e)}
              onMouseOut={e => handleHoverExit(e)} ref={line4} 
              href="/contacts"> Contacts</Link>
        </li>
        <li>
            <a
              onMouseEnter={e => handleHover(e)}
              onMouseOut={e => handleHoverExit(e)} ref={line5} 
              href="https://cmeditions.us17.list-manage.com/subscribe/post?u=385cdf2c81c2f3bdd2ff1583e&amp;id=fa0ff0c34e"> Newsletter</a>
        </li>
    </ul>
</nav>

The GSAP functions:

const handleHover = e => {
    gsap.to(e.target, {
      duration: 0.3,
      y: 3,
      skewX: 4,
      ease: 'power3.inOut'
    });
};

const handleHoverExit = e => {
    gsap.to(e.target, {
      duration: 0.3,
      y: -3,
      skewX: 0,
      ease: 'power3.inOut'
    });
}

useRef:

let line1 = useRef();
let line2 = useRef();
let line3 = useRef();
let line4 = useRef();
let line5 = useRef();
like image 351
Rom-888 Avatar asked Oct 21 '25 04:10

Rom-888


1 Answers

next/link component still requires you to pass a child element to it. You can add <a>'s as children to your <Link>'s, then apply the ref and callbacks to them.

<nav>
    <ul>
        <li>
            <Link href="/nouveautes">
                <a onMouseEnter={e => handleHover(e)} onMouseOut={e => handleHoverExit(e)} ref={line1}>
                    Nouveautés
                </a>
            </Link>
        </li>
        <!-- remaining code -->
    </ul>
</nav>
like image 74
juliomalves Avatar answered Oct 23 '25 20:10

juliomalves