Home > Software design >  React-Scroll - Link not working - appears as empty <a> tag in html
React-Scroll - Link not working - appears as empty <a> tag in html

Time:02-05

I'm trying to implement a smooth scroll when I click on a link in my Nav component to other components, for example this About component. I'm using react-scroll.

This is my Nav.js component.

import { Link } from "react-scroll";

const NavBar = () => {

  return (
      <div className={`${classes.navbar} ${navBarDarkLightClasses}`}>
        <Link to="about" spy={true} smooth={true} offset={50} duration={500}>
          About
        </Link>
      </div>
  );
};

export default NavBar;

And here is my About.js component that I want to link to.

const About = () => {
  return (
    <section>
      <div id="about" className={classes.image}>
        <img src={profilePhoto} alt="profile photo"/>
      </div>
    </section>
  );
};

export default About;

However. Nothing happens. When I view the html in the browser the link appears as About and includes no href as I would expect it should.

Any help greatly appreciated.

CodePudding user response:

Changes:

  • import React from "react"; is added at the top of the files
  • Components should be imported into App.js

Example:

{root-dir}/components/navBar.js:

import React from "react";
import { Link } from "react-scroll";

const NavBar = () => {
  return (
    <div>
      <Link to="about" spy={true} smooth={true} offset={50} duration={500}>
        About
      </Link>
    </div>
  );
};

export default NavBar;

{root-dir}/components/aboutSection.js:

import React from "react";

const About = () => {
  return (
    <section>
      <div id="about">
        <img src={profilePhoto} alt="profile photo"/>
      </div>
    </section>
  );
};

export default About;

App.js:

import React, { Component } from "react";
import NavBar from "./components/navBar";
import About from "./components/aboutSection";

export default class App extends Component {
  render() {
    return (
      <>
        <NavBar />
        <About />
      </>
    );
  }
}

CodePudding user response:

There's nothing wrong with your code, as far as I can see. However, maybe you have some issues with your classes and/or styling.

The link rendered shouldn't have any href. The Link component should be handling the scroll without it.

You can take a look at this working example sandbox based on your provided code. Then, maybe, you can quickly figure out the problem with your code.

  •  Tags:  
  • Related