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

HeadContent.dev.tsx

50 lines1.5 KB

1'use client'
2​
3import * as React from 'react'
4import { DEV_STYLES_ATTR } from '@tanstack/router-core'
5import { Asset } from './Asset'
6import { useRouter } from './useRouter'
7import { useHydrated } from './ClientOnly'
8import { useTags } from './headContentUtils'
9import type { HeadContentProps } from './HeadContent'
10​
11/**
12 * Render route-managed head tags (title, meta, links, styles, head scripts).
13 * Place inside the document head of your app shell.
14 *
15 * Development version: filters out dev styles link after hydration and
16 * includes a fallback cleanup effect for hydration mismatch cases.
17 *
18 * @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management
19 */
20export function HeadContent(props: HeadContentProps) {
21 const tags = useTags(props.assetCrossOrigin)
22 const router = useRouter()
23 const nonce = router.options.ssr?.nonce
24 const hydrated = useHydrated()
25​
26 // Fallback cleanup for hydration mismatch cases
27 // Runs when hydration completes to remove any orphaned dev styles links from DOM
28 React.useEffect(() => {
29 if (hydrated) {
30 document
31 .querySelectorAll(`link[${DEV_STYLES_ATTR}]`)
32 .forEach((el) => el.remove())
33 }
34 }, [hydrated])
35​
36 // Filter out dev styles after hydration
37 const filteredTags = hydrated
38 ? tags.filter(
39 (tag) => tag.tag !== 'link' || tag.attrs?.[DEV_STYLES_ATTR] !== true,
40 )
41 : tags
42​
43 return (
44 <>
45 {filteredTags.map((tag) => (
46 <Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} nonce={nonce} />
47 ))}
48 </>
49 )