简体   繁体   中英

Next.js - Disable jump to anchor when using router.push()

Using next 10.2 , every time we push an URL with hash to the router, next is jumping to the anchor element.

import {useRouter} from 'next/router'

router.push('/contact#about-us');

This also happens if I disable scroll

router.push('/contact#about-us', undefined, { scroll: false });

I would like to smooth scroll to the anchor element, rather than delegate this to next.js.

import React from 'react'
import {useRouter} from 'next/router'
import PropTypes from "prop-types";

const LinkSmoothScroll = ({href, className, children}) => {
  const router = useRouter()

  const linkClicked = (e) => {
    e.preventDefault();

    router
      .push(href, undefined, {scroll: false})
      .then(() => {
        const el = document.getElementById(href);

        if ( typeof el !== "undefined" ) {
          // Since header element is fixed, and document height is not being
          // affected by fixed/absolute elements, we need to consider this
          // on the margin to be applied.
          const headerHeight = document.getElementById("nav-header")?.scrollHeight || 0;
          const scrollTopY = el.top + window.scrollY - headerHeight;

          window.scrollTo({
            left: el.left,
            top: scrollTopY,
            behavior: 'smooth'
          });
        }

      });
  }

  return (
    <a href={href} className={className} onClick={linkClicked}>{children}</a>
  )
}

LinkSmoothScroll.propTypes = {
  href: PropTypes.any,
  children: PropTypes.string,
  className: PropTypes.string
}

export default LinkSmoothScroll;

I didn't found any way to disable this behavior, nor a tweak to avoid it.

A couple of thoughts.

#1 - Use CSS

html {
  scroll-behavior: smooth;
}

#2 - Don't use the target ID in the hash

Avoid the browser behavior by prefixing the ID in the hash so the matching element can't be found in the page ( #about-us becomes #prefix-about-us ). Then parse it on navigation and scroll to it with JS.

Neither approach is great in my opinion, default behaviors are best left intact if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM