Skip to content

useScrollIntoView ​

Hook that provides functionality to scroll an element into view

sensors
low
test coverage
Last changed: 7 days ago

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
target?HookTargetwindowThe target element to scroll into view
options.immediately?booleantrueWhether to scroll immediately
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.immediately?booleantrueWhether to scroll immediately
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 immediately the scroll into view */
  immediately?: 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.