2

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!

Rayan Ahmed
  • 165
  • 2
  • 11

1 Answers1

1

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

95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
  • Thank you for your response. I am knew to frontend dev, so this might sound like a basic question. How do I do scrollTo off of modal exactly? This is what I tried: Created another ref, attached it to modal, and then tried to do scrollTo using that ref. That is not working for me. – Rayan Ahmed Jul 27 '20 at 22:28
  • Does it have a scrollbar visible? If not you can use `max-height` & `overflow` CSS properties. Basically you do the same thing in using `scrollTo` like you did with the `window`, except this time you do it on the modal element with **overflowing content (therefore has a scrollbar)**. If you wish to retain the scrolling using the `window` object, the distance to scroll has to be relative to the `window` not to the modal. In a standard implementation setting, the overflowing content probably does not belong to the main modal container immediately but to the modal inner content container. – 95faf8e76605e973 Jul 27 '20 at 22:31