Rifat
Rifat

Reputation: 1888

react scroll to a component without react router and with most basic code

I have multiple sections in a web page. Need to scroll to one of the components on button click. Router of ref is overkill or is not neccessary since it just need to scroll to a section of the page.

Tried this :

// on return function
<Button onClick={() =>
                    document
                      .getElementsByClassName("scrollhere")
                      .scrollIntoView() //error not a function.
                  }
                >
                Go to Download Section
</Button>

<Section1/> // Section is equivalent of div 
<Section2/>
<Section3 className="scrollhere"/>
<Section4 id="downloadSection"/>

How to scroll at a certain point with most basic code?

Upvotes: 1

Views: 54

Answers (1)

Ron B.
Ron B.

Reputation: 1540

Utilize the useRef hook to refer to an element and then scroll to it.

Something like that

const elementRef = useRef();


//Later in the code
<button onClick={() => elementRef.current.scrollIntoView()}/>
<div className="scrollhere" ref={elementRef}/>

Read more about useRef here

Upvotes: 4

Related Questions