Skip to main content

useScrollIntoView

React sensor hook works like `element.scrollIntoView()

Usage

Live Editor

function Demo() {
  const targetRef = useRef<HTMLParagraphElement>(null);
  const { scrollIntoView } = useScrollIntoView(targetRef, {
    offset: 60,
  });

  return (
    <div>
      <button onClick={() => scrollIntoView({ alignment: "center" })}>
        Scroll to target
      </button>
      <div style={{ height: "50vh" }} />
      <p ref={targetRef}>Hello there</p>
    </div>
  );
}

Result
Loading...

API

useScrollIntoView

Returns

{ scrollIntoView: (animation?: UseScrollIntoViewAnimation | undefined) => void; cancel: () => void; }: A object with the following elements:

  • scrollIntoView: scroll target element into viewport
  • cancel: cancel scroll function

Arguments

ArgumentDescriptionTypeDefaultValue
targetElementdom elementBasicTarget<HTMLElement> (Required)-
paramsoptional paramsUseScrollIntoViewParams | undefined-
scrollElementscroll containerBasicTarget<HTMLElement>-

UseScrollIntoViewAnimation

PropertyDescriptionTypeDefaultValue
alignmenttarget element alignment relatively to parent based on current axis'start' | 'end' | 'center'-

UseScrollIntoViewParams

PropertyDescriptionTypeDefaultValue
onScrollFinishcallback fired after scroll() => void-
durationduration of scroll in millisecondsnumber1250
axisaxis of scroll'x' | 'y'y
easingcustom mathematical easing function(t: number) => number(t: number) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
offsetadditional distance between nearest edge and elementnumber0
cancelableindicator if animation may be interrupted by user scrollingbooleantrue
isListprevents content jumping in scrolling lists with multiple targetsboolean-

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;