Skip to content
Source
Sign inSign up
TanStack/devtools
Open History to see the last commit

panel.tsx

56 lines1.8 KB

1import { useEffect, useRef } from 'react'
2import type { TanStackDevtoolsPluginProps } from '@tanstack/devtools'
3​
4export interface DevtoolsPanelProps extends TanStackDevtoolsPluginProps {}
5​
6/**
7 * Creates a React component that dynamically imports and mounts a devtools panel. SSR friendly.
8 * @param devtoolsPackageName The name of the devtools package to be imported, e.g., '@tanstack/devtools-react'
9 * @param importName The name of the export to be imported from the devtools package (e.g., 'default' or 'DevtoolsCore')
10 * @returns A React component that mounts the devtools
11 * @example
12 * ```tsx
13 * // if the export is default
14 * const [ReactDevtoolsPanel, NoOpReactDevtoolsPanel] = createReactPanel('@tanstack/devtools-react')
15 * ```
16 *
17 * @example
18 * ```tsx
19 * // if the export is named differently
20 * const [ReactDevtoolsPanel, NoOpReactDevtoolsPanel] = createReactPanel('@tanstack/devtools-react', 'DevtoolsCore')
21 * ```
22 */
23export function createReactPanel<
24 TComponentProps extends TanStackDevtoolsPluginProps,
25 TCoreDevtoolsClass extends {
26 mount: (el: HTMLElement, props: TanStackDevtoolsPluginProps) => void
27 unmount: () => void
28 },
29>(CoreClass: new () => TCoreDevtoolsClass) {
30 function Panel(props: TComponentProps) {
31 const devToolRef = useRef<HTMLDivElement>(null)
32 const devtools = useRef<TCoreDevtoolsClass | null>(null)
33 useEffect(() => {
34 if (devtools.current) return
35 devtools.current = new CoreClass()
36​
37 if (devToolRef.current) {
38 devtools.current.mount(devToolRef.current, props)
39 }
40​
41 return () => {
42 if (devToolRef.current) {
43 devtools.current?.unmount()
44 devtools.current = null
45 }
46 }
47 }, [props])
48​
49 return <div style={{ height: '100%' }} ref={devToolRef} />
50 }
51​
52 function NoOpPanel(_props: TComponentProps) {
53 return <></>
54 }
55 return [Panel, NoOpPanel] as const