mauricevancooten / react-anchor-link-smooth-scroll

React component for anchor links using the smooth scroll polyfill.
243 stars 31 forks source link

pragmatic call #34

Open alainib opened 3 years ago

alainib commented 3 years ago

hello

your package work very well specially the working offset. thanks for work

i'm in a case where i need to call the scroll to an element only after data is fetched. Is there a way to get a function who do that instead of AnchorLink

something like this for example ?


import { AnchorLink , scrollToAnchor} from "react-anchor-link-smooth-scroll";

fetchData( id ) {
   .....
  scrollToAnchor(id); 
}

thanks

alainib commented 3 years ago

edit: i ended with this function created based on your code, work for me

import smoothscroll from 'smoothscroll-polyfill';
smoothscroll.polyfill();

export function scrollToAnchor(id, offset = 0) {
  try {
    const $anchor = document.getElementById(id);
    const offsetTop = $anchor.getBoundingClientRect().top + window.pageYOffset;
    console.log("on scroll to anchor")
    window.scroll({
      top: offsetTop - offset,
      behavior: 'smooth'
    })
  } catch (error) {
    console.error("error in scrollToAnchor", error);
  }
}