Docs
useAutoScroll

Use the useAutoScroll hook to automatically scroll an element into view when it is focused, with optional parameters for behavior and block alignment.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-auto-scroll

Usage

"use client"
 
import * as React from "react"
 
import useAutoScroll from "@/hooks/use-auto-scroll"
 
export function Component() {
  const [items, setItems] = React.useState(["Item 1"])
  const listRef = useAutoScroll(true, [items])
 
  const addItem = () => setItems([...items, `Item ${items.length + 1}`])
 
  return (
    <div>
      <ul ref={listRef} className="h-40 overflow-y-auto border">
        {items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
      <button onClick={addItem}>Add Item</button>
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
enabledbooleanWhether to enable the scroll behavior.trueNo
depsReact.DependencyListDependencies for the effect.[]No
optionsAutoScrollOptionsOptions for the scroll behavior.{}Yes
options.smoothScrollbooleanWhether to enable smooth scrolling.trueYes
options.scrollThresholdnumberThe scroll threshold in pixels.0Yes

Return Values

NameTypeDescription
refReact.RefObject<T | null>A ref to the element that should be scrolled into view.