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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay