-1

I'm creating a portfolio website using React.

It is a single page website and each section of the website is its own separate component.

My navbar component has links at the top that when clicked I want the page to scroll to the corresponding section further down the page. A traditional <a href="#about">About</a> is not working. Do I need to use react-router-dom or am I just missing something?

const App = () => {

  return (
    <div className='app'>
      <Navbar />
      <Hero />
      <About />
      <Projects />
      <Footer />
    </div>
  )
}

export default App
newportkat
  • 19
  • 4
  • RRD wouldn't really help you here as it's a library for rendering routes and linking to them within a React app. Think of this more as faking a "multi-page" app. Why isn't a traditional `About` working? That's what you would use in this case. What isn't working as expected? Can you [edit] the post to include a more complete [mcve] for what you are rendering and trying to link to? – Drew Reese Jan 11 '23 at 05:24
  • You can use useRef Hook to achieve this. This may help you https://stackoverflow.com/questions/43441856/how-to-scroll-to-an-element – Muhammad Najeeb Ul Hassan Jan 11 '23 at 05:50

2 Answers2

0

You can use the refs to scroll the page to a section . Refs in react have many applications , you can read details on react official page. Here is an example to use ref for scrolling

    const Scroll = () => {
       const scrollTo = useRef();
       return (
           <div>
           <button onClick = {()=>{scrollTo.current.scrollIntoView()}></button>
             .
             .
             // Your Other divs
             .
             .
             <div ref={scrollTo}>Scrolled</div>
           </div>
       );
    }

You can use the window.scroll() for scrolling page to a coordinate

    window.scroll({top:600,left:50,behavior:'smooth'})
0

Don't know what I was doing wrong but as Drew suggested in his answer, the classic <a> tag does work as expected.

Go forth and use those tags fellow React devs!

newportkat
  • 19
  • 4