I am working on my first Next.js project and I have a one-page website. I already have done the navigation component, but now I need to manage links.
How to add <Link /> component that will refer to elements (in my case <section>) in other components (I mean something like in pure HTML with element id: <a href="#about">About us</a>)?
Is it then possible to change the URL slug when the scroll position is on the specific element (e.g. when the user scrolls to the About us section the slug will be domain.com/about and when the user will scroll down on the same page to Contact section the URL slug will be domain.com/contact)?
CodePudding user response:
You can achieve that behavior using what you said above and it will work.
something like this codesandbox: https://codesandbox.io/s/jolly-babycat-4zoqv?file=/pages/index.js
<div>
These are the links
<Link href="#about">
<a>About</a>
</Link>
<Link href="#contact">
<a>contact</a>
</Link>
<div
style={{
width: "100%",
height: "2000px",
marginTop: 800,
background: "#ff0"
}}
>
<section ref={aboutRef} id="about" style={{ ...sectionStyle }}>
About
</section>
<section
ref={contactRef}
style={{ ...sectionStyle, background: "red" }}
id="contact"
>
Contact
</section>
</div>
</div>
