4

I want to scroll to different parts of my page by clicking, but I don't want the URL to get updated in the address bar.

For example, I have an about section on my page, with the ID about:

<div id='about'>

By clicking a link on the page, I want to scroll to this section. I've been able to do this with both the <Link> component, and using the router, however using both, I haven't been able to do this without updating the URL.

For example, using router, I would have:

router.replace(`/#about`);

This works fine, except the URL gets updated to myurl.com/#about, where as I want to keep the URL as myurl.com.

I've tried using the second as argument to set the URL, for example:

router.replace(`/#about`, '/');

However, this just breaks the link.

Anyone have an idea how to achieve this without updating the URL? I've found no examples, and nothing useful in the docs.

Thanks to anyone who can help!

user2475306
  • 334
  • 4
  • 12
  • 1
    Maybe try this solution https://stackoverflow.com/questions/3569329/javascript-to-make-the-page-jump-to-a-specific-location -- the second answer down seems like it could work, you'd just need to 'reactify' it –  Mar 08 '22 at 16:43

2 Answers2

1

You can use next's own 'Link' component, just add the 'href' indicating which id the screen should scrooll to.

And all the styling, you put it in the 'a' tag, so it doesn't generate an error if you have a list of items.

For exemple in the navBar you put:

<Link href="#home">
   <a>Home</a>
</Lins>

And in the section, you put:

<div id="home"></div> 

If you use Styled-components look this exemple about styles, because maybe you see a error about 'Link' styles, because he can't have childrens, so just put styles in 'a':

import Link from "next/link";
export const NavLinks = styled(Link)``;

export const Links = styled.a`
 margin-right: 3rem;
 cursor: pointer;
 font-weight: 500;
 color: #3B3B51;
 font-size: 1rem;

&:last-child {
  margin-right:0;
}`;
0
export const scrollIntoTheView = (id: string) => {
    let element = document.getElementById(id) as HTMLElement;
    if (!element) return;

    element.scrollIntoView({
        behavior: "smooth",
        block: "start",
        inline: "nearest",
    });
};

You can use this function it takes the id of the HTML element, Call this function with a click of a button.