Skip to content

Instantly share code, notes, and snippets.

@Tim-W-James
Last active February 12, 2023 04:47
Show Gist options
  • Save Tim-W-James/2b9bb80d65091bb2d554aaa751aa2e41 to your computer and use it in GitHub Desktop.
Save Tim-W-James/2b9bb80d65091bb2d554aaa751aa2e41 to your computer and use it in GitHub Desktop.
React useDocumentMeta Custom Hook #hooks
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