@ehsaneha/react-inview
v1.0.0
Published
react-inview – A lightweight React hook to detect when elements enter or leave the viewport using the Intersection Observer API.
Maintainers
Readme
@ehsaneha/react-inview
React hook to detect when an element enters or leaves the viewport using the Intersection Observer API.
Features
- Easily track element visibility in the viewport
- Supports root margin and threshold configuration
- Optional
onceflag to trigger visibility callback only once - New
disabledprop to toggle observation on and off dynamically - Lightweight and TypeScript-ready
Installation
npm install @ehsaneha/react-inviewor
yarn add @ehsaneha/react-inviewUsage
Basic usage
import React from "react";
import useInView from "@ehsaneha/react-inview";
function Example() {
const [ref, isVisible] = useInView({ threshold: 0.5 });
return (
<div ref={ref} style={{ minHeight: "150px" }}>
{isVisible ? "Visible" : "Not visible"}
</div>
);
}API
useInView(props?: InViewOptionalProps): [React.RefObject<T>, boolean]
props(optional): Configuration optionsrootMargin(string): Margin around the root. Default"0px"threshold(number | number[]): Threshold(s) at which to trigger. Default0once(boolean): Whether to disconnect observer after first visibility. Defaultfalsedisabled(boolean): Whether to disable the observer. Defaultfalse
Returns a tuple with:
ref: React ref to assign to the element to observeisVisible: Boolean indicating whether the element is currently visible
useInViewStateless(onChange, props?)
Stateless version that accepts a callback instead of returning state.
Testing
Tests are written using Jest and React Testing Library Hooks.
npm testMocks the Intersection Observer API to verify:
- Observation starts and stops correctly
disabledtoggling works dynamicallyonceflag disconnects observer after first visibility event
License
This package is licensed under the MIT License. See LICENSE for more information.
Feel free to modify or contribute to this package!
