skip to Main Content

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

2

Answers


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

    html {
      scroll-behavior: smooth !important;
    }
    
    Login or Signup to reply.
  2. 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>
    ));
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search