I have react pages that are composed of sub components. I have link in footer and expected to scroll to specific div when user click on it. I have tried to hash # but its not really working. not sure how to approach this issue?
In following example I need to go OurServicesMessage when user click on . This link exist in footer component.
child component where I need to go
import React, { Fragment } from "react";
const OurServicesMessageBanner = () =>{
return(
<Fragment>
<div id="OurServicesMessage" className="service-message-banner">
//... code
</div>
</Fragment>
);
}
export default OurServicesMessageBanner;
Parent component/ page
import React, { Fragment, useEffect } from "react";
const Services = () => {
useEffect(() => {
const hash = window.location.hash;
if (hash === "#OurServicesMessage") {
const element = document.getElementById("OurServicesMessage");
if (element) {
const elementRect = element.getBoundingClientRect();
const scrollPosition = (elementRect.top + window.scrollY) + '80';
window.scrollTo({
top: scrollPosition,
behavior: 'smooth',
});
}
}
}, []);
return (
<Fragment>
<LayoutOne>
<OurServicesParallax />
<OurServicesMessageBanner />
//.. remaining code
</LayoutOne>
</Fragment>
);
};
export default Services;
footer from where the link should scroll jump from
const Footer = () => {
return(
<footer className="footer-section">
<div className="container">
<div className="col-lg-3 col-sm-12">
<Widget title="Helpful Link">
<List classes="recent-post helpful_post">
<LI>
<Link to={process.env.PUBLIC_URL + "/services#OurServicesMessage"}>Our service</Link>
</LI>
//... other link codes...
</List>
</Widget>
</div>
</div>
</footer>
app routes
export const routes = [
{ path: "/", element: <Home /> },
{ path: "/home", element: <Home /> },
{ path: "/authlogin", element: <AuthLogin /> },
{ path: "/about", element: <About /> },
{ path: "/services", element: <Services /> },
// other paths