(null);
// Always render on server
@@ -55,6 +78,7 @@ function LazyHydrate(props: Props) {
on = [],
children,
didHydrate, // callback for hydration
+ listenOnEl,
...rest
} = props;
@@ -74,7 +98,7 @@ function LazyHydrate(props: Props) {
useIsomorphicLayoutEffect(() => {
// No SSR Content
- if (!childRef.current.hasChildNodes()) {
+ if (!childRef.current?.hasChildNodes()) {
setHydrated(true);
}
}, []);
@@ -84,7 +108,7 @@ function LazyHydrate(props: Props) {
const cleanupFns: VoidFunction[] = [];
function cleanup() {
while (cleanupFns.length) {
- cleanupFns.pop()();
+ cleanupFns.pop()!();
}
}
function hydrate() {
@@ -97,13 +121,14 @@ function LazyHydrate(props: Props) {
}
if (whenIdle) {
- // @ts-ignore
- if (requestIdleCallback) {
- // @ts-ignore
- const idleCallbackId = requestIdleCallback(hydrate, { timeout: 500 });
+ if (window.requestIdleCallback) {
+ const idleCallbackId = window.requestIdleCallback(hydrate, {
+ timeout: 500
+ });
cleanupFns.push(() => {
- // @ts-ignore
- cancelIdleCallback(idleCallbackId);
+ if (window.cancelIdleCallback) {
+ window.cancelIdleCallback(idleCallbackId);
+ }
});
} else {
const id = setTimeout(hydrate, 2000);
@@ -116,7 +141,7 @@ function LazyHydrate(props: Props) {
let events = Array.isArray(on) ? on.slice() : [on];
if (whenVisible) {
- if (io && childRef.current.childElementCount) {
+ if (io && childRef.current?.childElementCount) {
// As root node does not have any box model, it cannot intersect.
const el = childRef.current.children[0];
io.observe(el);
@@ -130,23 +155,28 @@ function LazyHydrate(props: Props) {
}
}
- events.forEach(event => {
- childRef.current.addEventListener(event, hydrate, {
- once: true,
- capture: true,
- passive: true
- });
- cleanupFns.push(() => {
- childRef.current.removeEventListener(event, hydrate, { capture: true });
+ const elToListenOn = listenOnEl || childRef.current;
+ if (elToListenOn) {
+ events.forEach(event => {
+ elToListenOn.addEventListener(event, hydrate, {
+ once: true,
+ capture: true,
+ passive: true
+ });
+ cleanupFns.push(() => {
+ elToListenOn.removeEventListener(event, hydrate, {
+ capture: true
+ });
+ });
});
- });
+ }
return cleanup;
}, [hydrated, on, ssrOnly, whenIdle, whenVisible, didHydrate, promise]);
if (hydrated) {
if (noWrapper) {
- return children;
+ return <>{children}>;
}
return (
@@ -164,6 +194,6 @@ function LazyHydrate(props: Props) {
/>
);
}
-}
+};
export default LazyHydrate;
diff --git a/tsconfig.json b/tsconfig.json
index ccbdd31..e5310cf 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -4,6 +4,7 @@
"declaration": true,
"declarationDir": "./types",
"emitDeclarationOnly": true,
- "jsx": "preserve"
+ "jsx": "preserve",
+ "strict": true
}
}