use stick to bottom
1.0.0
useStickToBottom
Designed with AI chat bots in mind, powering
bolt.new
by StackBlitz
A lightweight zero-dependency React hook + Component that automatically sticks to the bottom of container and smoothly animates the content to keep it's visual position on screen whilst new content is being added.
overflow-anchor
browser-level CSS support which Safari does not support.isAtBottom
& programmatically scroll to the bottom.ResizeObserver
API to detect when content resizes.
scrollToBottom
returns a Promise<boolean>
which will resolve to true
as soon as the scroll was successful, or false
if the scroll was cancelled.<StickToBottom>
Componentimport { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom';
function Chat() {
return (
<StickToBottom className="h-[50vh] relative" resize="smooth" initial="smooth">
<StickToBottom.Content className="flex flex-col gap-4">
{messages.map((message) => (
<Message key={message.id} message={message} />
))}
</StickToBottom.Content>
<ScrollToBottom />
{/* This component uses `useStickToBottomContext` to scroll to bottom when the user enters a message */}
<ChatBox />
</StickToBottom>
);
}
function ScrollToBottom() {
const { isAtBottom, scrollToBottom } = useStickToBottomContext();
return (
!isAtBottom && (
<button
className="absolute i-ph-arrow-circle-down-fill text-4xl rounded-lg left-[50%] translate-x-[-50%] bottom-0"
onClick={() => scrollToBottom()}
/>
)
);
}
useStickToBottom
Hookimport { useStickToBottom } from 'use-stick-to-bottom';
function Component() {
const { scrollRef, contentRef } = useStickToBottom();
return (
<div style={{ overflow: 'auto' }} ref={scrollRef}>
<div ref={contentRef}>
{messages.map((message) => (
<Message key={message.id} message={message} />
))}
</div>
</div>
);
}