I am trying to create a chat application, whenever a new message is sent, so it should auto scroll..
But it's not working for me.
I have added an event listener to chatBox, i did console.log inside the event callback even it was not working..
I also tried like before event listener, console.log(chatBox.container) i was getting the div in the console
Here's Code :
basically, i have tried this but it's not auto scrolling
const chatBox = useRef(null); // stores the refrence of any component inside a variable
useEffect(() => {
console.log(chatBox.current);
chatBox.current.addEventListener("DOMNodeInserted", (event) => {
const { currentTarget: target } = event;
target.scroll({ top: target.scrollHeight, behavior: "smooth" });
});
}, [chatMessages]);
my div :
<div className="chat-container-header-btn" ref={chatBox}>
<MoreVertIcon />
</div>
I tried this as well from an articl :
const scrollToBottom = () => {
chatBox.current?.scrollIntoView({
behavior: "smooth",
block: "end",
inline: "nearest",
});
};
useEffect(() => {
scrollToBottom();
}, [chatMessages]);
I tried many ways and this is the only one that managed to auto-scroll a div as its content expands:
Step 1: Import the necessary references
Step 2: Inside your function component, declare your ref constant
Step 3: Inside your div container, and after its content, add a new DIV and add to it the ref you declared in the previous step:
Step 4: Define your useEffect and set it's DependencyList to your list length, using the scrollIntoView to give the scroll attributes:
Credits to Source: https://reacthustle.com/blog/react-auto-scroll-to-bottom-tutorial