In my code, there is a special div/container that contains multiple <p/>
tags. The container has a reference called divRef
, which is initially set to null
using the useRef
function.
<div ref={divRef} style={styles.messageListContainer}>
<p>Placeholder</p>
// more <p/> tags here
</div>
The CSS styling for this container is defined as follows:
messageListContainer: {
height: '100vh`,
width: '100%',
paddingBottom: 20,
flexDirection: "column",
display: "flex",
overflow: "auto",
},
When the page loads, I want the content inside the div to be automatically scrolled to the bottom, allowing users to scroll upwards to see previous content. To achieve this without a visible scrolling animation, I refrain from using scrollIntoView
.
I attempted to implement this behavior using a useEffect
hook, but encountered an error:
Cannot read properties of null (reading 'scrollHeight')
. What could be causing this error, and how can I achieve the desired outcome?
Code snippet for setting automatic scroll at the bottom of the div:
useEffect(() => {
divRef.current.scrollTop = divRef.current.scrollHeight
}, [])