Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

navigating to a specific section of another page with React Link tag

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.

like image 907
kishor sutradhar Avatar asked Jul 08 '26 14:07

kishor sutradhar


2 Answers

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' });
  }
}, []);
like image 81
shisinbin Avatar answered Jul 10 '26 03:07

shisinbin


 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".

like image 39
Zubair Khan Avatar answered Jul 10 '26 03:07

Zubair Khan