简体   繁体   中英

Render a div in React with an initial scrollTop value set

I have a React component which is rendering a div . However I want this div to be rendered such that it's initially scrolled all the way to the bottom.

I know this can be achieved by using a ref and setting the scrollTop property in componentDidMount (or in useEffect ), but this causes a flicker when the div is initially rendered.

If the div is rendered with the scrollTop property already set on the DOM Element, then the flicker will not occur.

React does not support a scrollTop property for the div . So is there any way to set an initial scrollTop value before the component is mounted?

You can use the useLayoutEffect hook to run some logic synchronously after all DOM mutations. These updates will be flushed synchronously, before the browser has a chance to paint.

 const { useRef, useLayoutEffect } = React; function App() { const ref = useRef(null); useLayoutEffect(() => { ref.current.scrollTop = ref.current.scrollHeight; }, []); return ( <div ref={ref} style={{ height: 100, overflowY: "scroll" }} > <div style={{ height: 1000 }} /> <div>Foo</div> </div> ); } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div> 

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