Skip to content

Commit

Permalink
add ClientOnly component
Browse files Browse the repository at this point in the history
  • Loading branch information
usk94 committed Nov 21, 2023
1 parent dc12493 commit 3a6b450
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions vike-react/renderer/ClientOnly.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export { ClientOnly }

import React, { ComponentType } from 'react'
import { ReactNode, Suspense, lazy, useEffect, useState } from 'react'

type ClientOnlyProps<T extends {}> = {
component: () => Promise<{ default: React.ComponentType<T> }>
componentProps: T
fallback: ReactNode
}

function ClientOnly<T extends {}>({ component, componentProps, fallback }: ClientOnlyProps<T>) {
const [Component, setComponent] = useState<ComponentType<any> | null>(null)

useEffect(() => {
const loadComponent = () => {
const Component = lazy(() =>
component()
.then((LoadedComponent) => {
return { default: () => <LoadedComponent.default {...componentProps} /> }
})
.catch((error) => {
console.error('Component loading failed:', error)
return { default: () => <p>Error loading component</p> }
})
)
setComponent(Component)
}

loadComponent()
}, [component])

return <Suspense fallback={fallback}>{Component ? <Component /> : null}</Suspense>
}

0 comments on commit 3a6b450

Please sign in to comment.