Write a back to top component in React
![Write a back to top component in React Write a back to top component in React](http://up-free-imgs.azimiao.com/wp-content/uploads/2020/05/react.png)
Principle and demonstration
The Element.scrollTop property can obtain or set the number of pixels for an element's content to scroll vertically.
The scrollTop value of an element is a measure of the distance from the top of the element's content to the top of its viewport's visible content. When the content of an element does not generate a vertical scroll bar, its scrollTop value is 0.
assembly
1. Code
import React from 'react' import styled from 'styled-components' class ScrollToTopWrapper extends React.Component { constructor(props){ super(props); this.state = { hasScrolled: false } this.onScroll = this.onScroll.bind(this); } componentDidMount() { window.onscroll = this.onScroll; } onScroll = () => { if (document.documentElement.scrollTop > 100 && ! this.state.hasScrolled) { this.setState({ hasScrolled: true }) } else if (document.documentElement.scrollTop < 100 && this.state.hasScrolled) { this.setState({ hasScrolled: false }) } } scrollToTop = () => { document.documentElement.scrollTop = 0 } render() { return ( <React. Fragment> {this.state.hasScrolled && ( <ScrollToTopIconContainer onClick={this.scrollToTop}> <div>^</div> <Button>Back to the top</Button> </ScrollToTopIconContainer> )} <ScrollingWrapperContainer> {this.props.children} </ScrollingWrapperContainer> </React. Fragment> ) } } export default ScrollToTopWrapper const ScrollingWrapperContainer = styled.div` ` const ScrollToTopIconContainer = styled.div` position: fixed; bottom: 20px; left: calc(50% - 50px); z-index: 2; cursor: pointer; opacity: 0.4; text-align: center; &:hover { opacity: 1; animation: wiggle 1s ease; animation-iteration-count: 1; } @keyframes wiggle { 20% { transform: translateY(6px); } 40% { transform: translateY(-6px); } 60% { transform: translateY(4px); } 80% { transform: translateY(-2px); } 100% { transform: translateY(0); } } ` const Button = styled.div` background: black; color: white; font-family: Teko; font-size: 16px; line-height: 32px; border-radius: 15px; width: 100px; padding: 4px 2px 4px 2px; `
2. Interpretation
use
<HashRouter history={hashHistory}> <div className={classes.root}> <AppBar position="sticky"> {……} </AppBar> <ScrollToTopWrapper> <Switch> <Route exact path="/" component={……}></Route> {……} </Switch> </ScrollToTopWrapper> </div> </HashRouter>