-
Notifications
You must be signed in to change notification settings - Fork 2
/
Meta.tsx
63 lines (46 loc) · 1.6 KB
/
Meta.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
51
52
53
54
55
56
57
58
59
60
61
62
63
import { useLayoutEffect, FC } from 'react'
export type MetaProps = {
title?: string
description?: string
image?: string
}
const PROPS_TO_NAMES = {
title: 'og:title',
description: 'description',
image: 'og:image'
}
const titleElement = document.head.getElementsByTagName('title')[0]
const initialTitle = titleElement.textContent!
const createMetaElement = (name: string, content: string) => {
const element = document.createElement('meta')
element.setAttribute('name', name)
element.setAttribute('property', name)
element.setAttribute('content', content)
document.head.insertBefore(element, titleElement)
return element
}
createMetaElement('og:type', 'website')
const ogURL = createMetaElement('og:url', window.location.href)
const Meta: FC<MetaProps> = ({ title = initialTitle, description = '', image = '' }) => {
const props = { title, description, image }
useLayoutEffect(() => {
document.title = title
ogURL.setAttribute('content', window.location.href)
for (const prop in props) {
const metaElement = document.head.querySelector(`meta[name="${PROPS_TO_NAMES[prop]}"]`)
metaElement
? metaElement.setAttribute('content', props[prop])
: createMetaElement(PROPS_TO_NAMES[prop], props[prop])
}
return () => {
document.title = initialTitle
ogURL.setAttribute('content', '')
for (const prop in props) {
const element = document.head.querySelector(`meta[name="${PROPS_TO_NAMES[prop]}"]`)!
element.setAttribute('content', '')
}
}
}, [title, description, image])
return null
}
export default Meta