-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeta.component.tsx
50 lines (44 loc) · 1.48 KB
/
meta.component.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { useRouterState } from '@tanstack/react-router'
import { Fragment } from 'react'
import { Helmet } from 'react-helmet-async'
import { useTranslation } from 'react-i18next'
import { type MetaProps } from './meta.types'
export const Meta = ({ titleTemplate }: MetaProps) => {
const state = useRouterState()
const { t } = useTranslation()
const matches = [...state.matches].reduce<Array<{ id: string; meta: MetaObject[] }>>((matches, match) => {
if (
typeof match.routeContext === 'object' &&
'meta' in match.routeContext &&
typeof match.routeContext.meta === 'function'
) {
matches.push({
id: match.id,
meta: match.routeContext.meta(t, match.loaderData as any),
})
}
return matches
}, [])
return (
<Helmet titleTemplate={titleTemplate}>
{matches.map(({ id, meta }) => {
return (
<Fragment key={id}>
{meta.map((tag) => {
if ('title' in tag) {
return <title key={tag.title}>{tag.title}</title>
}
if ('name' in tag) {
return <meta key={`${tag.name}|${tag.content}`} name={tag.name} content={tag.content} />
}
if ('property' in tag) {
return <meta key={`${tag.property}|${tag.content}`} property={tag.property} content={tag.content} />
}
return <Fragment key={tag} />
})}
</Fragment>
)
})}
</Helmet>
)
}