DEV Community

Tejendra Singh Rajawat
Tejendra Singh Rajawat

Posted on

Scroll to specific element in react using useRef

I have a firebase group chat ui and it have a search functionality in it. but when i click on search result then i want to go to that specific element (list element in my case). for that example i am using react hooks called useRef which take current element and we can get get it anywhere in our code .

import React, { useRef } from 'react'
const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop) 
// General scroll to element function 
const ScrollDemo = () => { const myRef = useRef(null) 
const executeScroll = () => scrollToRef(myRef)
return ( <> 
<div ref={myRef}>I wanna be seen</div> 
<button onClick={executeScroll}> Click to scroll </button>
 </> )}
Enter fullscreen mode Exit fullscreen mode

here, now when i click on button then it will look for div with myRef and our view scroll to that div.
for reference in my code i have given github link -
github

Top comments (0)