I'm attempting to set up anchor navigation in one of my page components inside my react app.
I'm trying to mimic the same functionality as seen here on draft.js where it uses sub headers as anchors (with the link icon next to it), which is also reflected in the URL.
As a reference I'm looking at http://www.tagindex.net/html/link/a_name.html
So I went ahead and tried implementing using the name attribute
<List.Item>
<a href="#createqueryschema">Create Query Schema</a>
</List.Item>
Then the subheader it should jump to
<Header>
<a name="createqueryschema">Create Query Schema</a>
<Header.Subheader style={{ marginTop: "20px", fontSize: "1rem" }}>
BLAH BLAH BLAH BLAH BLAH BLAH
</Header.Subheader>
</Header>
I'm rendering this list and subheader on a page called /overview, so in theory when I click on the item in the list it should jump to the Create Query Schema subheader AND reflect /overview#createqueryschema in the URL.
However, it is trying to navigate to page /createqueryschema. I'm not sure why/how it's trying to navigate to a new page when it should just be appending the # and the name attribute.
EDIT: It's also not jumping to the desired element
I have a codesandbox setup to further explain. Click docs on the top of the menu bar, which will take you to the page with the anchor nav. If you click any of the two anchors under the Overview section then corresponding <Header> is not scrolled to.
EDIT: UPDATED for better explanation for routing issue
I’m still having some trouble setting up an anchor element for same page navigation.
My app is already using hash router for another reason, so my base page /home/#/
Each other page would look like this /home/#/page1 /home/#/page2
For example I’m using the in-page anchor navigation on page2
I’m creating a link to the named anchor below
<List.Item>
<a href="#some-random-header">Random Header</a>
</List.Item>
Then create the named anchor using id attribute
<Header id="some-random-header">Random Header Section</Header>
When I click on the link, it tries to navigate to a new page with url /home/#/some-random-header INSTEAD of /home/#/page2#some-random-header
Normally the # is used for an Id, however id's are not used in React. What you can do is create a ref. Then you can create a method onClick to scroll to the ref when the ref is clicked
So you could try something like:
import React, { useRef } from "react";
const Component = () => {
const myRef = useRef();
const handleClick = () => {
window.scrollTo(0, myRef.current.offsetTop)
}
return (
<>
<List.Item>
<p onClick={handleClick}>Create Query Schema</p>
</List.Item>
<div name="createqueryschema" ref={myRef} >Create Query Schema</div>
</>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With