code-share/renderer/client-only.tsx

39 lines
834 B
TypeScript
Raw Permalink Normal View History

2024-02-22 12:14:58 +00:00
import React, { useEffect, useState } from "react";
import type { ReactNode } from "react";
type ClientOnlyProps = {
children: ReactNode;
2024-02-22 19:49:13 +00:00
fallback?: () => JSX.Element | null;
2024-02-22 12:14:58 +00:00
};
const ClientOnly = ({ children, fallback }: ClientOnlyProps) => {
const [isMounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (typeof window === "undefined") {
2024-02-22 19:49:13 +00:00
return fallback ? fallback() : null;
2024-02-22 12:14:58 +00:00
}
2024-02-22 19:49:13 +00:00
if (isMounted) {
return children;
}
return fallback ? fallback() : null;
2024-02-22 12:14:58 +00:00
};
export const withClientOnly = <T extends unknown>(
Component: React.ComponentType<T>,
2024-02-22 19:49:13 +00:00
fallback?: () => JSX.Element | null
2024-02-22 12:14:58 +00:00
): React.ComponentType<T> => {
return (props: any) => (
<ClientOnly fallback={fallback}>
<Component {...props} />
</ClientOnly>
);
};
export default ClientOnly;