How to have "Anchor Jumping" in React Router?
In HTML, it is easy to jump to specific section by simply adding {id} to that specific section and {#id} to the href.
<a href='#specific'>link</a>
<section id='specific'>This is the section!</h1>
Unfortunately, this method does not work in React Router. But no worries, it will be easy after you finish reading.
Let me show you how to have the anchor jumping to another page first.
Anchor jumping to another page
We will still use Link from React Router and use the hash in location object. This will make the url become "/intro#intro"
<Link to={{ pathname: "/intro", hash: "#intro" }}>Vitawind Introduction</Link>
Then we still add the id to the specific section.
<p id="intro" className="w-4/5 p-20 underline decoration-yellow-500">
Vitawind is a great package to set up your project easily. If you want
to use React, Tailwind, Typescript and Vite in your project, Vitawind is
your one-stop shop.Moreover, it provides the "creator" option to let you
simply copy the command and execute.
</p>
And we use useLocation to get the value of hash and remove the hash tag to get the id we need. (console.log(location.hash)
=> #intro) Then we check if the id exists. If yes, we can use the element method scrollIntoView to scroll to the element that has the id.
const location = useLocation();
if (location.hash) {
let elem = document.getElementById(location.hash.slice(1));
if (elem) {
elem.scrollIntoView({ behavior: "smooth" });
}
}
Now, when you click the Vitawind Introduction button in the homepage, it'll jump to the intro section in the intro page.
Anchor jumping in the same page
It is pretty much the same as jumping to another page.
First, add the id to the specific section and "#link" to href.
<a
href="#link"
className="py-20 font-semibold underline cursor-pointer hover:text-blue-500">
Vitawind
>
<a
href="https://vitawind.vercel.app/"
id="link"
className="py-20 cursor-pointer"
>
Visit Vitawind for more information
</a>
Because we have useEffect to monitor the change of location, when you click the Vitawind link, location.hash will change to #link and call the scrollIntoView function to scroll to Visit Vitawind for more information.
You can visit https://react-anchor-jumping.vercel.app/ to try.