2

I have a version of a webpage that uses the following style of scrollspy:

https://getbootstrap.com/docs/4.0/components/scrollspy/#item-1-1

"When successfully implemented, your nav or list group will update accordingly, moving the .active class from one item to the next based on their associated targets."

When the element with certain ID is on the screen it activates the Navlink and highlights it. I have translated it to a React App and have imported from 'react-router-hash-link'. Since I have done that, the scrollspy which highlights the nav link when the id (#) is on the screen no longer works. Is there a solution to using to simulate this scrollspy functionality with this component?

https://www.npmjs.com/package/react-router-hash-link

1 Answers1

0

Check out react-ui-scrollspy it is very easy to use.

When the element with certain ID is on the screen it will highlight the navitem containing corresponding data-to-scrollspy-id.

It will also append your URL with #<id>.

Full disclosure: I maintain this package.

  1. In your navigation component
<div>
  <p data-to-scrollspy-id="first">Section 1</p>
  <p data-to-scrollspy-id="second">Section 2</p>
</div>
  1. Wrap the elements you want to spy on in the <ScrollSpy> component.
import ScrollSpy from "react-ui-scrollspy";

<ScrollSpy>
  <div id="first">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut dolores
    veritatis doloremque fugit. Soluta aperiam atque inventore deleniti,
    voluptatibus non fuga eos magni natus vel, rerum excepturi expedita.
    Tempore, vero!
  </div>
  <div id="second">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut dolores
    veritatis doloremque fugit. Soluta aperiam atque inventore deleniti,
    voluptatibus non fuga eos magni natus vel, rerum excepturi expedita.
    Tempore, vero!
  </div>
</ScrollSpy>
  1. Write styles for when the navigation element which is active in your index.css
.active-scroll-spy {
  background-color: yellowgreen;
  border-radius: 15px;
}
Hussain Pettiwala
  • 1,406
  • 8
  • 16