let's say I have a button called 'contact me' on the header. when I click on the button it will redirect me to the contact section of the home page even though I am on the other page.
how will I set this up with react Link tag? i try to use it like this
<Link to="/#contactsec" > contact Me <Link>
it redirects me to the home page but I do not go to the contactsec of the home page.
how I can do this.
Use a useEffect hook to grab the identifier (the portion of the URL after the '#' symbol), locate an element with the same ID on the page, and then smoothly scroll to it if it exists.
useEffect(() => {
const href = window.location.href.substring(
window.location.href.lastIndexOf('#') + 1
);
const element = document.getElementById(href);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}, []);
const navigate = useNavigate();
const navigateToContact = () => {
navigate("/");
setTimeout(() => {
const contactSection = document.getElementById("contact");
if (contactSection) {
contactSection.scrollIntoView({ behavior: "smooth" });
}
}, 100); // Delay for smoother scroll
};
//button
<button onClick={navigateToContact}>Contact us</button>
By using this approach, when the button is clicked, it will redirect to the home page and smoothly scroll to the section with the ID "contact".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With