close

How to scroll to an element?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to scroll to an element? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to scroll to an element?

  1. How to scroll to an element?

    to scroll to an element this worked for me this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })

  2. scroll to an element

    to scroll to an element this worked for me this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })

Method 1

this worked for me

this.anyRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })

I wanted to expand on this based on the comments.

const scrollTo = (ref) => {
  if (ref && ref.current /* + other conditions */) {
    ref.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

<div ref={scrollTo}>Item</div>

Method 2

Something like this should work:

handleScrollToElement(event) {
  const tesNode = ReactDOM.findDOMNode(this.refs.test)
  if (some_logic){
    window.scrollTo(0, tesNode.offsetTop);
  }
}

render() {

  return (
    <div>
      <div ref="test"></div>
    </div>)
}

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment