React - anchor link for onClick() with accurate offset position

0 votes
55 views
added Apr 22 in React by lcjr First Warrant Officer (11,930 points)
edited Apr 24 by lcjr
<a
  href="#similar-listing-expiry"
  className="btn btn-primary"
  onClick={(e) => {
      e.preventDefault();
      const targetElement = document.getElementById('similar-listing-expiry');
      if (targetElement) {
          const yOffset = -100; // offset after scroll
          const y = targetElement.getBoundingClientRect().top + window.pageYOffset + yOffset;
          window.scrollTo({ top: y, behavior: 'smooth' });
      }
  }}
>
  View Similar Properties 
</a>

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...