vadersfather
vadersfather

Reputation: 9389

Scroll to element in React

I have a ref on all the large section headers on a page. The page is very long and renders well passed 100vh. The section that is scrollable is a fairly nested div, also with a ref. Given the refs of the section headers, and the ref of the inner container (can't use window.scrollTo etc.) how can would I build a "on click, go to section".

<div>
  <div>
    <button onClick={ // navigate to section }>Navigate</button>
  </div>
  <div>
    <div ref="inner_content">
      <h2 ref="section1">Section 1</h2>
      <h2 ref="section2">Section 2</h2>
      <h2 ref="section3">Section 3</h2>
    </div>
  </div>
</div>

// on navigate, I've tried things like this which have made the page scroll, but I can't understand which scroll/height properties I would need to access to pinpoint where the view should scroll too
this.refs.inner_content.scrollTop(this.refs.section1.getBoundingClientRect().top)

I have been unable to find a consistent way to do this using scrollTop and getBoundingClientRects().top on the section refs.

Upvotes: 0

Views: 912

Answers (1)

WitVault
WitVault

Reputation: 24140

I think you can use old approach to navigate to a section from a link e.g.

This is the section where I want to navigate

<div id="section1">
 This is section 1
</div>

and on anchor link I provide

 <a href="#section1">Section 1</a>

Upvotes: 1

Related Questions