Hi,
I’m building a chat app and I want to make sure that the user always sees the bottom of the list of messages.
<IonContent ref={this.messagesRef}>
and then I call this function from a few places
scrollToBottom = () => {
if (!this.messagesRef || !this.messagesRef.current) return;
//window.scrollTo(0, this.messagesRef.current.offsetTop)
this.messagesRef.current.scrollToBottom();
//scrollIntoView({ behavior: "smooth" });
console.log("ScrollToTheBottom");
}
But when I do this I get the following error:
TypeError: this.messagesRef.current.scrollToBottom is not a function
What am I doing wrong here?
Thanks!
const scrollToBottom = () => {
let list = document.querySelector("ion-content");
return list && list.scrollToBottom();
};
This is what I have done.
Thanks @aaronksaunders .
I tried that but it did not work because scrollToBottom
does not exist on the element. I must be missing something simple.
It looks like using ``setTimeout is the only way around this problem. I call
scheduleScrollToBottom at the end of
componentDidMount` and every time a new message gets either entered by the user or received from the server.
messagesRef
relates to an empty div
at the bottom of the screen.
scheduleScrollToBottom = () => {
setTimeout(this.scrollToBottom, 5000);
}
scrollToBottom = () => {
if (!this.messagesRef || !this.messagesRef.current) return;
this.messagesRef.current.scrollIntoView({ behavior: "smooth" });
}
see this example in codesandbox on how to scroll to a specific item in a list
ionic-react-scroll-to-list-item by aaronksaunders using @ionic/react, @ionic/react-router, react, react-dom, react-router, react-router-dom, react-scripts
Thanks. So this means scrollToBottom
doesn’t work in React?
I have the exact problem. scrollToTop works with React, but scrollToBottom doesn’t work
Check my latest comment here for a dirty quickfix…:
The method scrollToBottom with React doesn’t work at all… Only ScrollToTop works with Ionic React…
Quick and dirty fix:
function getContent() {
return document.querySelector('ion-content#chat-content');
}
function scrollToBottom() {
const container = getContent();
if(container) container.scrollToPoint(0, 99999);
}
the point i you really are not scrolling to the bottom, you are scrolling to the last message entered in the list… that i why I believed the solution i provided made sense