Open History to see the last commit
1import * as Solid from 'solid-js'
2β
3export interface ClientOnlyProps {
4 /**
5 * The children to render when the JS is loaded.
6 */
7 children: Solid.JSX.Element
8 /**
9 * The fallback component to render if the JS is not yet loaded.
10 */
11 fallback?: Solid.JSX.Element
12}
13β
14/**
15 * Render the children only after the JS has loaded client-side. Use an optional
16 * fallback component if the JS is not yet loaded.
17 *
18 * @example
19 * Render a Chart component if JS loads, renders a simple FakeChart
20 * component server-side or if there is no JS. The FakeChart can have only the
21 * UI without the behavior or be a loading spinner or skeleton.
22 *
23 * ```tsx
24 * return (
25 * <ClientOnly fallback={<FakeChart />}>
26 * <Chart />
27 * </ClientOnly>
28 * )
29 * ```
30 */
31export function ClientOnly(props: ClientOnlyProps) {
32 const hydrated = useHydrated()
33 return (
34 <Solid.Show when={hydrated()} fallback={props.fallback ?? null}>
35 <>{props.children}</>
36 </Solid.Show>
37 )
38}
39β
40/**
41 * Return a boolean indicating if the JS has been hydrated already.
42 * When doing Server-Side Rendering, the result will always be false.
43 * When doing Client-Side Rendering, the result will always be false on the
44 * first render and true from then on. Even if a new component renders it will
45 * always start with true.
46 *
47 * @example
48 * ```tsx
49 * // Disable a button that needs JS to work.
50 * const hydrated = useHydrated()
51 * return (
52 * <button type="button" disabled={!hydrated()} onClick={doSomethingCustom}>
53 * Click me
54 * </button>
55 * )
56 * ```
57 * @returns True if the JS has been hydrated already, false otherwise.
58 */
59export function useHydrated(): Solid.Accessor<boolean> {
60 const [hydrated, setHydrated] = Solid.createSignal(false)
61 Solid.onMount(() => {
62 setHydrated(true)
63 })
64 return hydrated
65}