简体   繁体   中英

React.js keep scroll at bottom

I have a div that grows in height as an animation. Instead of growing outside of the viewable area (and user having to scroll down), I'd like the window to automatically scroll with the div height. Locking the scroll position at the bottom of the page would work.

!!This is in React!!

I've tried millions of google/SO answers, none work/ arent specific enough.

code https://github.com/coryb08/corydbaker npm install && npm start

You provided very little information, but since we know it's in React, you could use JavaScript to make sure your div is scrolled all the way to the bottom at all all times.

class FullMenu extends Component {
  constructor() {
    super()
    this.state = {
      class: "",
      div: ""
    }
    this.scrollToBottom = this.scrollToBottom.bind(this);
  }
  componentDidMount() {
    setInterval(this.scrollToBottom, 20);
  }
  scrollToBottom() {
    var scrollingElement = (document.scrollingElement || document.body); /* you could provide your scrolling element with react ref */
    scrollingElement.scrollTop = scrollingElement.scrollHeight;
  }
  render() {
    return (
      <div id="FullMenu">
        {this.state.div}
        <div id="triangleDiv">
          <img
            className={this.state.class}
            onClick={() => {
              this.setState({ class: "bounce" })
              let that = this
              setTimeout(function() {
                that.setState({
                  class: "",
                  div: <div className="menuDiv" />
                })
              }, 1000)
            }}
            src={triangle}
            id="triangle"
          />
        </div>
      </div>
    )
  }
}

Note that above solution keeps the window scrolled at all times. If you wanted to scroll it only during animation, then you should use react's CSSTransitionGroup and use clearInterval to stop this behavior in transitionEnd lifecycle hook.

You can use CSS alone all you have to do is set the div styling

display: flex;
flex-direction: column-reverse

this should flip the div scroll and position it at the bottom

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM