Search code examples
reactjsnext.js

How target DOM with next.js useRef in map


// next.js code 
export default function Header() {
  const pp = useRef(null);
  const pp2 = useRef(null);

  function show() {
    pp.current.classList.add("right-0");
    pp.current.classList.remove("-right-2/3");
    pp2.current.classList.add("animation")
  }
  function close() {
    pp.current.classList.remove("right-0");
    pp.current.classList.add("-right-2/3");
  }
  let pagename: string = usePathname();
  let ll = links.map((e, i) => {
    return (
      <Link 
        ref={pp2}
        className="font-bold text-2xl hover:opacity-50"
        key={e.name}
        href={e.href}
      >
        {e.name}
      </Link>
    );  
});

this navbar i can't upload all code but i am using tailwind on my project, the problem here when i click on hamburger icon call show function and animation only work on the last link element

// css code
.animation {
  animation-name: shop-animation;
  animation-duration: 1s;
  animation-delay: 0.1s;
}
@keyframes shop-animation {
  0% {
    opacity: 0;
    transform: translate(0px, 10px);
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

this css animation no more


Solution

  • You have this one pp2 ref that you are passing to all links in your map, hence at the end, the last one only is in pp2. You could use use an array ref, like so:

    export default function Header() {
      const pp = useRef(null);
      const pp2 = useRef([]);
    
      function show() {
        pp.current.classList.add("right-0");
        pp.current.classList.remove("-right-2/3");
        pp2.current.forEach((e) => {
          e.classList.add("animation");
        });
      }
      function close() {
        pp.current.classList.remove("right-0");
        pp.current.classList.add("-right-2/3");
      }
      let pagename: string = usePathname();
      let ll = links.map((e, i) => {
        return (
          <Link
            ref={(el) => {
              pp2.current[i] = el;
            }}
            className="font-bold text-2xl hover:opacity-50"
            key={e.name}
            href={e.href}
          >
            {e.name}
          </Link>
        );
      });