Search code examples
htmlreactjsanchor

Can I use NavLInk or Link to link to an element?


This is probably a problem of me not knowing what to search, but here's what I'm trying to accomplish:

When using traditional anchor tags I can easily link to a section <a href="#section"> by invoking the ID of the section <section id="section">.

When I try to put #section into the to attribute(?) of Link or NavLink, it does nothing. It shows the same in the browser as when I use an <a> tag - when I hover it shows "localhost:3000/#section" - but when I click it, it doesn't do anything. When I change the tag to an anchor tag w/ "href" instead of "to", it works just fine.

Should I just use anchor tags in my nav menu instead of NavLink, or am I just doing something wrong?


Solution

  • Thank you Konrad Linkowski for the answer.

    Since his answer was just a couple links, but they gave me the info I needed, I will expound here:

    github.com/remix-run/react-router/issues/394 npmjs.com/package/react-router-hash-link

    Basically, if you want to use hashtag links like I described above, you need to install react-router-hash link (npm i react-router-hash-link). Then import HashLink and/or NavHashLink (import { Hashlink, NavHashLink } from 'react-router-hash-link';) in the file you are wanting to add the links in.

    Alternatively, you can just use anchor tags (<a href....), although this is usually just reserved for links to locations outside your app, and will complicate using the active class for your nav links.