@k8ordo/ui

InView

Reports whether its children are in the viewport or a scroll container. Use it for lazy loading or scroll-triggered reveals.

Import

ts
import { InView } from '@k8ordo/ui';

Usage

Basic usage

Out of view

Scroll down.

Target

tsx
const [container, setContainer] = useState<HTMLElement | null>(null);
const [isInView, setIsInView] = useState(false);

<div ref={setContainer} className={styles.scroller}>
  <InView onChange={setIsInView} root={container}>
    <p>Target</p>
  </InView>
</div>

once

With once, observation stops the first time the children are in view. Leaving afterwards reports nothing.

Not seen yet

Scroll down, then back up. The badge stays.

Target

tsx
<InView once onChange={setHasBeenSeen} root={container}>
  <p>Target</p>
</InView>

Multiple children

With several elements, it is true while any of them is in view. It follows elements that mount or unmount later: when a visible element unmounts and nothing else is in view, it reports false. Until there is an element to observe, onChange is not called.

Props

children
Type: ReactNode
Default: -
onChange
Type: (isInView: boolean) => void
Default: -
once?
Type: boolean
Default: false
root?
Type: Element|null
Default: null
rootMargin?
Type: string
Default: '0px'
threshold?
Type: number
Default: 0
PropTypeDefault
childrenReactNode-
onChange(isInView: boolean) => void-
once?booleanfalse
root?Element|nullnull
rootMargin?string'0px'
threshold?number0
k8ordo

React libraries that use Baseline features without holding back.