javascriptcssreactjssingle-page-applicationreact-scroll

Clicking on Navbar not Smooth Scrolling (installed react-scroll)


What am I doing wrong with this react-scroll? I want to click on the navbar link and smooth scroll to the corresponding section on the same page. However, clicking the nav items doesn't do anything. Can somebody help me with why this is not working?

I ran npm install react-scroll.

App.js

import './App.css';
import React from 'react';

import Navbar from './components/Navbar/Navbar';
import About from './components/About/About';
import Skills from './components/Skills/Skills';

function App() {
  return (
    <React.Fragment>
      <header>
        <Navbar />
      </header>
      <main>
        <About id='about' />
        <Skills id='skills' />
      </main>
    </React.Fragment>
  );
}

export default App;

Navbar.js

import { Link as LinkScroll } from 'react-scroll';

const Navbar = () => {
  return (
    <nav> 
      <LinkScroll
        activeClass='active'
        to='about'
        spy={true}
        smooth={true}
        offset={-70}
        duration={500}
      >
        About
      </LinkScroll>
      <LinkScroll
        activeClass='active'
        to='skills'
        spy={true}
        smooth={true}
        offset={-70}
        duration={500}
      >
        Skills
      </LinkScroll>
    </nav>
  );
};

export default Navbar;

Solution

  • Remove id from Component tags:

    <main>
        <About />
        <Skills />
    </main>
    

    Then add these id in the root tab for these components. Supposing your component is:

    import React from "react";
    
    export default ({ name }) => (
      <div id="skills" style={{ height: "500px" }}>
        <h1>Hello {name}!</h1>
      </div>
    );