2

I am using next/Link but smooth scrolling is not working but when i use anchor tag it is working properly while using anchor tag page is reloading but next/link doesnt load page whenever path changes

Css

html {
  scroll-behavior: smooth;
}

index.js

{
navItems.map((item, index) => (
    <Link key={index} href={item.href} passHref legacyBehavior>
          <a className="w-full px-4 py-4 -ml-4 text-gray-500 rounded-md dark:text-gray-300 hover:text-gradient focus:text-gradient focus:bg-indigo-100 dark:focus:bg-gray-800 focus:outline-none dark:focus:bg-neutral-700"
              aria-label="Toggle Menu"
              onClick={handleOpen}
           >
              {item.name}
           </a>
     </Link>
))}

Need smooth scrolling with next/link

Azeem Khan
  • 95
  • 5
  • Please don't put a link inside a link, it's semantically incorrect. According to [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#technical_summary): *"Permitted content: no descendant may be interactive content or an `a` element"* – Reyno Aug 07 '23 at 10:57

2 Answers2

0

To fix this issue you have to add !important in the CSS and it will fix the issue.

html {
  scroll-behavior: smooth !important;
}
Rok Benko
  • 14,265
  • 2
  • 24
  • 49
0

As you're already using react I'd suggest you to use the scroll option from the Link component.

import Link from 'next/link';

// ...

navItems.map((item, index) => (
  <Link key={index} href={item.href} scroll={false}>
    <a
      onClick={(e) => {
        e.preventDefault();
        const href = item.href.split('#')[1];
        const element = document.getElementById(href);
        if (element) {
          window.scrollTo({
            top: element.offsetTop,
            behavior: 'smooth',
          });
        }
      }}
      className="w-full px-4 py-4 -ml-4 text-gray-500 rounded-md dark:text-gray-300 hover:text-gradient focus:text-gradient focus:bg-indigo-100 dark:focus:bg-gray-800 focus:outline-none dark:focus:bg-neutral-700"
      aria-label="Toggle Menu"
      onClick={handleOpen}
    >
      {item.name}
    </a>
  </Link>
));

MaikeruDev
  • 1,075
  • 1
  • 19