UNPKG

7.42 kBTypeScriptView Raw
1import * as React from 'react';
2
3type State = {
4 inView: boolean;
5 entry?: IntersectionObserverEntry;
6};
7/**
8 ## Render props
9
10 To use the `<InView>` component, you pass it a function. It will be called
11 whenever the state changes, with the new value of `inView`. In addition to the
12 `inView` prop, children also receive a `ref` that should be set on the
13 containing DOM element. This is the element that the IntersectionObserver will
14 monitor.
15
16 If you need it, you can also access the
17 [`IntersectionObserverEntry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry)
18 on `entry`, giving you access to all the details about the current intersection
19 state.
20
21 ```jsx
22 import { InView } from 'react-intersection-observer';
23
24 const Component = () => (
25 <InView>
26 {({ inView, ref, entry }) => (
27 <div ref={ref}>
28 <h2>{`Header inside viewport ${inView}.`}</h2>
29 </div>
30 )}
31 </InView>
32 );
33
34 export default Component;
35 ```
36
37 ## Plain children
38
39 You can pass any element to the `<InView />`, and it will handle creating the
40 wrapping DOM element. Add a handler to the `onChange` method, and control the
41 state in your own component. Any extra props you add to `<InView>` will be
42 passed to the HTML element, allowing you set the `className`, `style`, etc.
43
44 ```jsx
45 import { InView } from 'react-intersection-observer';
46
47 const Component = () => (
48 <InView as="div" onChange={(inView, entry) => console.log('Inview:', inView)}>
49 <h2>Plain children are always rendered. Use onChange to monitor state.</h2>
50 </InView>
51 );
52
53 export default Component;
54 ```
55 */
56declare class InView extends React.Component<IntersectionObserverProps | PlainChildrenProps, State> {
57 node: Element | null;
58 _unobserveCb: (() => void) | null;
59 constructor(props: IntersectionObserverProps | PlainChildrenProps);
60 componentDidMount(): void;
61 componentDidUpdate(prevProps: IntersectionObserverProps): void;
62 componentWillUnmount(): void;
63 observeNode(): void;
64 unobserve(): void;
65 handleNode: (node?: Element | null) => void;
66 handleChange: (inView: boolean, entry: IntersectionObserverEntry) => void;
67 render(): React.ReactNode;
68}
69
70/**
71 * React Hooks make it easy to monitor the `inView` state of your components. Call
72 * the `useInView` hook with the (optional) [options](#options) you need. It will
73 * return an array containing a `ref`, the `inView` status and the current
74 * [`entry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry).
75 * Assign the `ref` to the DOM element you want to monitor, and the hook will
76 * report the status.
77 *
78 * @example
79 * ```jsx
80 * import React from 'react';
81 * import { useInView } from 'react-intersection-observer';
82 *
83 * const Component = () => {
84 * const { ref, inView, entry } = useInView({
85 * threshold: 0,
86 * });
87 *
88 * return (
89 * <div ref={ref}>
90 * <h2>{`Header inside viewport ${inView}.`}</h2>
91 * </div>
92 * );
93 * };
94 * ```
95 */
96declare function useInView({ threshold, delay, trackVisibility, rootMargin, root, triggerOnce, skip, initialInView, fallbackInView, onChange, }?: IntersectionOptions): InViewHookResponse;
97
98/**
99 * What should be the default behavior if the IntersectionObserver is unsupported?
100 * Ideally the polyfill has been loaded, you can have the following happen:
101 * - `undefined`: Throw an error
102 * - `true` or `false`: Set the `inView` value to this regardless of intersection state
103 * **/
104declare function defaultFallbackInView(inView: boolean | undefined): void;
105/**
106 * @param element - DOM Element to observe
107 * @param callback - Callback function to trigger when intersection status changes
108 * @param options - Intersection Observer options
109 * @param fallbackInView - Fallback inView value.
110 * @return Function - Cleanup function that should be triggered to unregister the observer
111 */
112declare function observe(element: Element, callback: ObserverInstanceCallback, options?: IntersectionObserverInit, fallbackInView?: boolean | undefined): () => void;
113
114type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
115type ObserverInstanceCallback = (inView: boolean, entry: IntersectionObserverEntry) => void;
116interface RenderProps {
117 inView: boolean;
118 entry: IntersectionObserverEntry | undefined;
119 ref: React.RefObject<any> | ((node?: Element | null) => void);
120}
121interface IntersectionOptions extends IntersectionObserverInit {
122 /** The IntersectionObserver interface's read-only `root` property identifies the Element or Document whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. If the `root` is null, then the bounds of the actual document viewport are used.*/
123 root?: Element | Document | null;
124 /** Margin around the root. Can have values similar to the CSS margin property, e.g. `10px 20px 30px 40px` (top, right, bottom, left). */
125 rootMargin?: string;
126 /** Number between `0` and `1` indicating the percentage that should be visible before triggering. Can also be an `array` of numbers, to create multiple trigger points. */
127 threshold?: number | number[];
128 /** Only trigger the inView callback once */
129 triggerOnce?: boolean;
130 /** Skip assigning the observer to the `ref` */
131 skip?: boolean;
132 /** Set the initial value of the `inView` boolean. This can be used if you expect the element to be in the viewport to start with, and you want to trigger something when it leaves. */
133 initialInView?: boolean;
134 /** Fallback to this inView state if the IntersectionObserver is unsupported, and a polyfill wasn't loaded */
135 fallbackInView?: boolean;
136 /** IntersectionObserver v2 - Track the actual visibility of the element */
137 trackVisibility?: boolean;
138 /** IntersectionObserver v2 - Set a minimum delay between notifications */
139 delay?: number;
140 /** Call this function whenever the in view state changes */
141 onChange?: (inView: boolean, entry: IntersectionObserverEntry) => void;
142}
143interface IntersectionObserverProps extends IntersectionOptions {
144 /**
145 * Children expects a function that receives an object
146 * contain an `inView` boolean and `ref` that should be
147 * assigned to the element root.
148 */
149 children: (fields: RenderProps) => React.ReactNode;
150}
151/**
152 * Types specific to the PlainChildren rendering of InView
153 * */
154type PlainChildrenProps = IntersectionOptions & {
155 children?: React.ReactNode;
156 /**
157 * Render the wrapping element as this element.
158 * This needs to be an intrinsic element.
159 * If you want to use a custom element, please use the useInView
160 * hook to manage the ref explicitly.
161 * @default `'div'`
162 */
163 as?: keyof JSX.IntrinsicElements;
164 /** Call this function whenever the in view state changes */
165 onChange?: (inView: boolean, entry: IntersectionObserverEntry) => void;
166} & Omit<React.HTMLProps<HTMLElement>, "onChange">;
167/**
168 * The Hook response supports both array and object destructing
169 */
170type InViewHookResponse = [
171 (node?: Element | null) => void,
172 boolean,
173 IntersectionObserverEntry | undefined
174] & {
175 ref: (node?: Element | null) => void;
176 inView: boolean;
177 entry?: IntersectionObserverEntry;
178};
179
180export { InView, type InViewHookResponse, type IntersectionObserverProps, type IntersectionOptions, type ObserverInstanceCallback, type PlainChildrenProps, defaultFallbackInView, observe, useInView };