`ClientOnly` fallback

I found this code for a client that only runs on the client
function ClientOnly(props: { children: JSX.Element }) {
const [ getRender, setRender ] = createSignal()
onMount(() => setRender(() => props.children))
return getRender as any as JSX.Element
}
function ClientOnly(props: { children: JSX.Element }) {
const [ getRender, setRender ] = createSignal()
onMount(() => setRender(() => props.children))
return getRender as any as JSX.Element
}
but how can I get it to render a fallback?
3 Replies
thetarnav
thetarnav14mo ago
you can modify the implementation like this:
function ClientOnly(props: { children: JSX.Element, fallback?: JSX.Element }) {
const [mounted, setMounted] = createSignal(false)
onMount(() => setRender(true))
return <Show when={mounted()} fallback={props.fallback}>{props.children}</Show>
}
function ClientOnly(props: { children: JSX.Element, fallback?: JSX.Element }) {
const [mounted, setMounted] = createSignal(false)
onMount(() => setRender(true))
return <Show when={mounted()} fallback={props.fallback}>{props.children}</Show>
}
or use isHydrated from solid-primitives to do this anywhere:
return <>{isHydrated() ? <Client/> : <Fallback/>}</>
return <>{isHydrated() ? <Client/> : <Fallback/>}</>
https://primitives.solidjs.community/package/lifecycle#ishydrated you may want to combine clientonly with lazy and Suspense for code splitting too
Samual 🦢
Samual 🦢14mo ago
oo isHydrated() is cool, thanks what advantages does code splitting have in this context?
thetarnav
thetarnav14mo ago
if some code is client-only than it's probably not critical enough to be loaded as soon as possible so code splitting will let the main bundle be downloaded and executed faster
Want results from more Discord servers?
Add your server
More Posts