简体   繁体   中英

Anchor Tag in Next.js

I'm tryin got use an anchor tag in Next.js

I don't get any console errors when I set it up and click the link, but the page does not jump to the id tag.

This issue on github suggests that people need to figure out a lot of custom code to use anchors. That can't be right.

I have:

const links = [
    { label: 'Solutions', href: '#solutions', id: 'solutions' },
    
  ]

 <NavLink.Desktop key={index} href={link.href} id={link.id}>
            {link.label}
          </NavLink.Desktop>

I get no errors, but the page does not jump to the label that has an id of 'solutions'.

Does anyone know how to solve this, or where to go for ideas on how - it can't be intented that complex custom code is required to use an anchor tag?

As said by @juliomalves in the comments, you have to specify the id attribute in the element in which you have to navigate to. Not on the anchor tag.

The id for the anchor should be set on the element you want to link to, not on the link itself.

The below code works for me in Next.js -

export default function Home() {
  return (
    <div>
      <a href="#secion">Click</a>

      <section
        style={{ marginTop: "1000px", marginBottom: "1000px" }}
        id="secion"
      >
        <h1>Test</h1>
      </section>
    </div>
  );
}

Your code should go like this -

const links = [{ label: 'Solutions', href: '#solutions', id: 'solutions' }]

<NavLink.Desktop 
     key={index} 
     href={link.href}
     // id={link.id} - This is wrong, as you're referring to the same element
>
   {link.label}
</NavLink.Desktop>

// Rather set the id attribute in a separate div/section element
<div id={link.id}>
   <h2>Solutions</h2>
</div>

maybe try

const links = [
{ label: 'Solutions', href: '#solutions', id: 'solutions' },

 ]

<NavLink.Desktop key={index} href={links[0].href} id={links[0].id}>
        {link.label}
</NavLink.Desktop>

since you only have 1 element in the links array, if you have multiple just map through the array

It is possible to scroll to anchor programatically using Router.push:

import { useRouter } from 'next/router'

const Foo = () => {
  const { push } = useRouter()

  const handleClick = () => {
    push("#blah")
  }

  return (
    <div>
      <button onClick={handleClick}>Scroll</button>
      <div>Foo</div>
      <div>Bar</div>
      <div id="blah">Blah</div>
    </div>
  )
}

Next.js recognises that you are passing something that is not a link to a new page and will concat it (in the example #blah ) to the end of the URL.

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