react-stay-at-bottom
v1.1.5
Published
A React hook that keeps a scrollable element at the bottom.
Downloads
548
Maintainers
Readme
react-stay-at-bottom
A React hook that keeps a scrollable element at the bottom.
Typical scenario:
- web IM chat
- ai chat bot
Install
npm i react-stay-at-bottom
Usage
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>
}
Live Demo
Parameters
scrollRef
(Required):
Type: React.RefObject<HTMLElement>
Description: a ref to the scrollable element.
options
(Optional):
Type: Object
Description: an object controlling the behavior of the hook:
handleScroll
:
Type: (scrollElement: HTMLElement) => void
Description: a function that replace the default scroll handler.
autoStay
:
Type: boolean
default: true
Description: Whether to automatically stay at the bottom when the scrollable element is scrolled.
initialStay
:
Type: boolean
default: false
Description: Whether to stay at the bottom when the component is mounted.
scrollThreshold
(Optional):
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
?
Return
stayAtBottom
:
Type: () => void
Description: A function that keeps the scrollable element at the bottom.
stopAtBottom
:
Type: () => void
Description: A function that stops the scrollable element from being kept at the bottom.
scrollToBottom
:
Type: (behavior?: ScrollOptions['behavior']) => void
Description: A function that scrolls the scrollable element to the bottom.
atBottom
:
Type: boolean
Description: A boolean indicating whether the scrollable element is at the bottom.
scroll
:
Type: (behavior?: ScrollOptions['behavior']) => void
Description: A function that scrolls the scrollable element to the bottom.
Similar Projects
License
MIT