Skip to content Skip to sidebar Skip to footer

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 scrol

Solution 1:

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 refconstructor(props) {
  super(props)
  // Add a component ref to your component. You'll use this to set scroll // position of div wrapping contentthis.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 topthis.componentRef.current.scrollTop = 0;
    });
}

render() {

  // Register your ref with wrapper divreturn (<divref={this.componentRef }>
    { this.state.alert }
    // rest contents ...
    </div>)
}

Post a Comment for "How To Set Modal Scroll To Top When It Appears In React.js"