Skip to content

A React hook that keeps a scrollable element at the bottom.

License

Notifications You must be signed in to change notification settings

shlroland/react-stay-at-bottom

Repository files navigation

react-stay-at-bottom

A React hook that keeps a scrollable element at the bottom.

Typical scenario:

  • web IM chat
  • ai chat bot

NPM Version

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

Open in StackBlitz

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:

  1. Why is the default value 2?

  2. 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

About

A React hook that keeps a scrollable element at the bottom.

Resources

License

Stars

Watchers

Forks

Packages

No packages published