Search code examples
javascriptreactjsscrollref

React react-scroll-to (scroll to Ref not working)


I'd like to smooth scroll to the specific ref on clicking a button. I'm trying to use 'react-scroll-to' There is a documentation about scrolling to the ref and I've tried to find the solution on here stackoverflow & github issues. But I can't find the proper solution. Please help me to figure this out.

Thanks in advance!

I prepared the codesandbox here https://codesandbox.io/s/react-scroll-to-ref-nwpq2?file=/src/index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { ScrollTo } from 'react-scroll-to'

import './styles.css'

class Child1 extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.props.scrollTo}>Scroll</button>
      </div>
    )
  }
}

class Child2 extends React.Component {
  render() {
    return (
      <div style={{ height: '500px', backgroundColor: 'blue' }}>Child 2</div>
    )
  }
}

class Example extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
  }
  render() {
    return (
      <div className="App">
        <h1>Index Component</h1>
        <ScrollTo>
          {({ scrollTo }) => {
            console.log(this.myRef)
            return (
              <Child1
                scrollTo={() =>
                  scrollTo({
                    ref: this.myRef,
                    // y: 100,
                    smooth: true
                  })
                }
              />
            )
          }}
        </ScrollTo>
        <Child2 />
        <div
          ref={this.myRef}
          style={{ height: '500px', backgroundColor: 'black' }}
        >
          Hello
        </div>
      </div>
    )
  }
}

const rootElement = document.getElementById('root')
ReactDOM.render(<Example />, rootElement)

Solution

  • As @sava mentioned, I misunderstood how the ref property of scrollTo works. By the way, Based on the @sava's answer, I've just fixed my codesandbox as scrolling to the bottom ref's offsetTop and it works smoothly.

                  <Child1
                    scrollTo={() =>
                      scrollTo({
                        y: this.myRef.current.offsetTop,
                        smooth: true
                      })
                    }
                  />
    

    https://codesandbox.io/s/react-scroll-to-ref-nwpq2?file=/src/index.js