From 3a6b4503c6528b52676b5e8d24cd6cf83f058990 Mon Sep 17 00:00:00 2001 From: Yusaku Date: Wed, 22 Nov 2023 08:46:10 +0900 Subject: [PATCH] add ClientOnly component --- vike-react/renderer/ClientOnly.tsx | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 vike-react/renderer/ClientOnly.tsx diff --git a/vike-react/renderer/ClientOnly.tsx b/vike-react/renderer/ClientOnly.tsx new file mode 100644 index 00000000..98a536bd --- /dev/null +++ b/vike-react/renderer/ClientOnly.tsx @@ -0,0 +1,34 @@ +export { ClientOnly } + +import React, { ComponentType } from 'react' +import { ReactNode, Suspense, lazy, useEffect, useState } from 'react' + +type ClientOnlyProps = { + component: () => Promise<{ default: React.ComponentType }> + componentProps: T + fallback: ReactNode +} + +function ClientOnly({ component, componentProps, fallback }: ClientOnlyProps) { + const [Component, setComponent] = useState | null>(null) + + useEffect(() => { + const loadComponent = () => { + const Component = lazy(() => + component() + .then((LoadedComponent) => { + return { default: () => } + }) + .catch((error) => { + console.error('Component loading failed:', error) + return { default: () =>

Error loading component

} + }) + ) + setComponent(Component) + } + + loadComponent() + }, [component]) + + return {Component ? : null} +}