How to scroll to a Ref within a modal scree in react

1.8k Views Asked by At

I currently have multiple components within a bootstrap modal. My goal is to be able to do a window.scroll to a given component following a user action. Basically, this is what I have tried:

class App extends Component {
  constructor (props) {
    super(props);
    this.myref = React.createRef();   

  }
  
  // function that I have been trying to invoke. 
  scrollToRef = () => {
    window.scrollTo({top: this.myref.current.offsetTop, behavior: "smooth"})
  }

  render () {
     return (
     <Modal>
         <ComponentOne/>
         <ComponentTwo/>
         <ComponentThree ref={this.myref}/>
     </Modal> 
     )

  }

}

All of my components are class components. I even tried wrapping ComponentThree in a div tag if that made a difference, but no luck. Any pointers would be greatly appreciated, Thank you!

1

There are 1 best solutions below

2
95faf8e76605e973 On

window.scrollTo would pertain to the window object, therefore will attempt to scroll the window, not the <Modal> component. For this, you can have another ref attached to the <Modal>, and that is the element you would use scrollTo on. Since <ComponentThree> is already a direct child of <Modal>, you can continue using the offsetTop property but take note:

offsetTop is the number of pixels from the top of the closest relatively positioned parent element