If you're using react-router and looking for an easy way to navigate and scroll to an element (or just scroll without managing state in every component), I created this simple component called ScrollLink. It avoids the hassle of managing state and keeps things clean.
import React, { useEffect } from 'react';
import { Link, LinkProps, useLocation } from 'react-router-dom';
type ScrollLinkProps = LinkProps & {
id: string;
top?: number;
};
const ScrollLink: React.FC<ScrollLinkProps> = ({ to, id, top = 0, children, ...props }) => {
const location = useLocation();
const handleClick = () => {
localStorage.setItem('scrollToId', id);
};
useEffect(() => {
const savedId = localStorage.getItem('scrollToId');
if (savedId && location.pathname === to) {
const element = document.getElementById(savedId);
if (element) {
const offset = element.getBoundingClientRect().top + window.scrollY - top;
window.scrollTo({ top: offset, behavior: 'smooth' });
}
localStorage.removeItem('scrollToId');
}
}, [location]);
return (
<Link to={to} {...props} onClick={handleClick}>
{children}
</Link>
);
};
export default ScrollLink;
How to Use
Assign an id to the target element you want to scroll to. For example:
<section id="contactsID">
<!-- Your section content -->
<h2>Contact Us</h2>
<p>Feel free to reach out!</p>
</section>
Use the ScrollLink component wherever you want to link to that element, such as in a footer or navigation:
<ScrollLink to="/Contact" id="contactsID" top={70} className="flex items-center gap-2">
<p>Contacts</p>
<PiMapPinAreaLight size={20} />
</ScrollLink>
Explanation of Props
to: The path to navigate to (same as the to prop in react-router-dom's Link).
id: The ID of the element to scroll to once the page loads.
top (optional): Offset in pixels from the top of the page to the scrolled element. This is useful if you have fixed headers or navbars that would otherwise cover the element.
...props: You can also pass any other props supported by the Link component from react-router-dom, such as className, style, onClick, etc.
This approach allows you to navigate to a page and smoothly scroll to a specific element without needing to manage state across components. It’s a simple and reusable solution for scroll-based navigation in your React projects.