Last active
February 12, 2023 04:47
-
-
Save Tim-W-James/2b9bb80d65091bb2d554aaa751aa2e41 to your computer and use it in GitHub Desktop.
React useDocumentMeta Custom Hook #hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect } from "react"; | |
/** | |
* Set the document meta attributes | |
* | |
* @param {string} title - meta title | |
* @param {string} description - meta description | |
*/ | |
const useDocumentMeta = ( | |
title?: string, | |
description?: string, | |
canonical?: string | |
) => { | |
useEffect(() => { | |
document.title = title | |
? `${title}${TITLE_SEPARATOR}${PRIMARY_TITLE}` | |
: `${PRIMARY_TITLE}${TITLE_SEPARATOR}${DEFAULT_SUB_TITLE}`; | |
const descriptionRef = document.querySelector("meta[name='description']"); | |
descriptionRef && | |
descriptionRef.setAttribute( | |
"content", | |
description ? description : DEFAULT_DESCRIPTION | |
); | |
const canonicalRef = document.querySelector("link[rel='canonical']"); | |
canonicalRef && canonical && canonicalRef.setAttribute("href", canonical); | |
}, [canonical, description, title]); | |
}; | |
export default useDocumentMeta; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment