Skip to content

useScrollIntoView ​

Hook that provides functionality to scroll an element into view

sensors
test coverage
Last changed: last month

Installation ​

Library
CLI
Manual
typescript
import { useScrollIntoView } from '@siberiacancode/reactuse';

Usage ​

typescript
const { trigger } = useScrollIntoView(ref);
// or
const { ref, trigger } = useScrollIntoView<HTMLDivElement>();

Demo ​

Api ​

Parameters

NameTypeDefaultNote
targetHookTarget-The target element to scroll into view
options.behavior?ScrollBehavior'smooth'The scrolling behavior
options.block?ScrollLogicalPosition'start'The vertical alignment
options.inline?ScrollLogicalPosition'nearest'The horizontal alignment

Returns

UseScrollIntoViewReturn

Parameters

NameTypeDefaultNote
options.behavior?ScrollBehavior'smooth'The scrolling behavior
options.block?ScrollLogicalPosition'start'The vertical alignment
options.inline?ScrollLogicalPosition'nearest'The horizontal alignment

Returns

UseScrollIntoViewReturn & { ref: StateRef<Target> }

Type declaration ​

typescript
import type { HookTarget } from '@/utils/helpers';

import type { StateRef } from '../useRefState/useRefState';

export interface UseScrollIntoViewOptions extends ScrollIntoViewOptions {
  /** Whether to enable the scroll into view */
  enabled?: boolean;
}

export interface UseScrollIntoViewReturn {
  /** Function to scroll element into view */
  trigger: (params?: {
    behavior?: ScrollBehavior;
    block?: ScrollLogicalPosition;
    inline?: ScrollLogicalPosition;
  }) => void;
}

export interface UseScrollIntoView {
  <Target extends Element>(
    options?: UseScrollIntoViewOptions,
    target?: never
  ): UseScrollIntoViewReturn & { ref: StateRef<Target> };

  (target: HookTarget, options?: UseScrollIntoViewOptions): UseScrollIntoViewReturn;
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin

Released under the MIT License.