A React hook that keeps a scrollable element at the bottom.
Typical scenario:
- web IM chat
- ai chat bot
npm i react-stay-at-bottom
import { useStayAtBottom } from 'react-stay-at-bottom'
function MessageList({
children,
messages,
}: {
children: React.ReactNode
messages: string[]
}) {
const scrollRef = useRef<HTMLDivElement>(null)
const { stayAtBottom, stopAtBottom, scrollToBottom, atBottom, scroll }
= useStayAtBottom(scrollRef)
return <div ref={scrollRef}>{children}</div>
}
Type: React.RefObject<HTMLElement>
Description: a ref to the scrollable element.
Type: Object
Description: an object controlling the behavior of the hook:
Type: (scrollElement: HTMLElement) => void
Description: a function that replace the default scroll handler.
Type: boolean
default: true
Description: Whether to automatically stay at the bottom when the scrollable element is scrolled.
Type: boolean
default: false
Description: Whether to stay at the bottom when the component is mounted.
Type: number | 'default'
Default: 'default'
('default' is equivalent to 2)
Description: The scroll threshold to determine if the scrollable element is at the bottom.
Notes:
-
Why is the default value
2
?- See MDN documentation - scrollHeight
- When set to
'default'
, thescrollTopMax
will be used to calculate the offset
-
What is
scrollTopMax
?
Type: () => void
Description: A function that keeps the scrollable element at the bottom.
Type: () => void
Description: A function that stops the scrollable element from being kept at the bottom.
Type: (behavior?: ScrollOptions['behavior']) => void
Description: A function that scrolls the scrollable element to the bottom.
Type: boolean
Description: A boolean indicating whether the scrollable element is at the bottom.
Type: (behavior?: ScrollOptions['behavior']) => void
Description: A function that scrolls the scrollable element to the bottom.
MIT