Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set modal scroll to top when it appears in React.js

I made a modal windows using react-bootstrap-sweetalert lib. It contains long list of contents, so I allowed overflow:scroll. What the problem is, when modal open, it doesn't scroll to top. And scroll to unknown position, so I need to scroll to top manually.

This is simple code

basicAlert = () => {
   this.setState({
        alert: (
          <div>
           // long list table
          </div>)
   });
}
hideAlert = () => {
   this.setState({
      alert: null
   });
}
render() {
   return (
     {this.state.alert}
     // rest contents ...
   )
}

Any advice will be big help for me. Thanks

like image 755
Nomura Nori Avatar asked Oct 19 '25 14:10

Nomura Nori


1 Answers

You could create a ref to an element in your component that wraps the scrollable content, and then use this ref to set scrollTop to 0 of the corresponding DOM element, when content is displayed in your modal.

So for instance, the following additions/adjustments to your component should achieve what you need:

// Add a constructor to create the ref
constructor(props) {
  super(props)
  // Add a component ref to your component. You'll use this to set scroll 
  // position of div wrapping content
  this.componentRef = React.createRef();

}

basicAlert = () => {
  this.setState({
    alert: (
      <div>
      // long list table
      </div>)
     }, () => {

      // After state has been updated, set scroll position of wrapped div
      // to scroll to top
      this.componentRef.current.scrollTop = 0;
    });
}

render() {

  // Register your ref with wrapper div
  return (<div ref={ this.componentRef }>
    { this.state.alert }
    // rest contents ...
    </div>)
}
like image 86
Dacre Denny Avatar answered Oct 22 '25 02:10

Dacre Denny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!