Jordan
Jordan

Reputation: 1121

React - Navigation that will smooth scroll to section of the page

So I'm trying to create a navigation for my single page app that will smooth scroll down to the section of the page.

I want to have my navigation at the top of the page with links that when a user clicks, will smooth scroll them down to the section of the page. I'd also like it so if the user goes directly to the link website.com/about for example, it will smooth scroll to the section the same way as if you clicked about on the navigation component.

I understand how the react-router-dom works for routing pages, but I'm confused on how to make it work for this particular purpose.

Could this be achieved with HashRouter?

Here's the code I currently have:

function Header() {
  return (
    <>
      <Link to="/">Hero</Link>
      <Link to="/">About</Link>
      <Link to="/">Contact</Link>
    </>
  );
}

function Hero() {
  return (
    <section>
      <h1>Hero Section</h1>
    </section>
  );
}

function About() {
  return (
    <section>
      <h1>About Section</h1>
    </section>
  );
}

function Contact() {
  return (
    <section>
      <h1>Contact Section</h1>
    </section>
  );
}

export default function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Header />
        <Hero />
        <About />
        <Contact />
      </BrowserRouter>
    </div>
  );
}

I'm also providing a CodeSandBox, forks are appretiated! :)

Upvotes: 5

Views: 21226

Answers (3)

Luigi Dalle Aste
Luigi Dalle Aste

Reputation: 1

Just add following property to your index.css :

scroll-behavior: smooth;

Upvotes: 0

Julian
Julian

Reputation: 657

To allow the link to update in the address bar, use the answer from @Abdullah Abid but change the <a> tags to <link> and the href to to.

See my ammendment to Abdullah's Sandbox Here

Upvotes: 1

Abdullah Abid
Abdullah Abid

Reputation: 1661

What you could do is use an anchor tag instead of Link from react-router-dom and have an id on the sections. when the anchor tag is clicked scroll to the corresponding section

 <a
  href="/"
  onClick={e => {
  let hero = document.getElementById("hero");
  e.preventDefault();  // Stop Page Reloading
  hero && hero.scrollIntoView();
  }}
  >
  Hero
  </a>

  // Rest of Code 

  function Hero() {
   return (
    <section id="hero">
      <h1>Hero Section</h1>
    </section>
   );
  }

and to scroll to a section using a url path you would have to get the extract the path from url and scroll to the section that has that specific path as an id

  useEffect(() => {
    let url = window.location.href.split("/");
    let target = url[url.length - 1].toLowerCase();
    let element = document.getElementById(target);
    element && element.scrollIntoView({ behavior: "smooth", block: "start"});
  }, []);

CodeSandbox here

Hope This Helps

Upvotes: 14

Related Questions