I have the following div/container which simply contains multiple <p/>
tags. The container has a ref
called divRef
which is defined at the top of the code using useRef
and is initialized to null
<div ref={divRef} style={styles.messageListContainer}>
<p>Placeholder</p>
// multiple more <p/> tags here
</div>
Here is the CSS for the container:
messageListContainer: {
height: '100vh`,
width: '100%',
paddingBottom: 20,
flexDirection: "column",
display: "flex",
overflow: "auto",
},
On mount, I want to the div to automatically be at the bottom end, and then users are able to scroll up in order to see previous content. I don’t want to use scrollIntoView
as I don’t want the user to see the scrolling animation, I want the div to automatically be at the bottom end.
I try to accomplish this using the following useEffect
, however I get the error: Cannot read properties of null (reading 'scrollHeight')
. Why does this error occur, and how can I accomplish my desired behaviour?
useEffect to set the scroll at the bottom of the div:
useEffect(() => {
divRef.current.scrollTop = divRef.current.scrollHeight
}, [])