I have a div that has scrolling enabled for that div. I have some elements in it, when the user starts to scroll I want an element to disappear and when scrolling stops I want it to show up again.
How can I do this
<div className="container"/> <div>Hide me on scrolling</div> <div>Always show </div> </div> .container{ flex: 1 1 80%; display: flex; flex-wrap: wrap; width: calc(100vw - 110px); height: calc(100vh - 75px); overflow-y: auto; min-width: 500px; display: flex; justify-content: center; z-index: 1; }
Advertisement
Answer
There is not real scrolling state in the browser; the scrolling event occurs, and then it’s done.
You could set a piece of state called e.g. isScrolling
to true
when the scrolling event occurs, and then set a timeout to set it back to false
after the last time it was scrolled.
Example
class App extends React.Component { timeout = null; state = { isScrolling: false }; componentDidMount() { window.addEventListener("scroll", this.onScroll); } componentWillUnmount() { window.removeEventListener("scroll", this.onScroll); } onScroll = () => { this.setState({ isScrolling: true }); clearTimeout(this.timeout); this.timeout = setTimeout(() => { this.setState({ isScrolling: false }); }, 200); }; render() { return ( <div style={{ height: 5000, overflowY: "scroll" }}> <div style={{ paddingTop: 50 }}> {this.state.isScrolling ? "Hidden" : "Shown"} </div> </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>