Skip to content

Instantly share code, notes, and snippets.

@NuroDev
Created November 19, 2022 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NuroDev/9c5ba89b37b5edc191492f51d0f13223 to your computer and use it in GitHub Desktop.
Save NuroDev/9c5ba89b37b5edc191492f51d0f13223 to your computer and use it in GitHub Desktop.
🧠 Define head ─ Next.js 13 utility function, based on `next-seo` to generate head elements based on provided props
import { type ReactNode } from 'react';
interface NextHeadProps {
params?: Record<string, string | number | boolean>;
}
interface HeadProps {
description?: string;
title?: string;
titleTemplate?: `%s${string}`;
}
function BaseHead({
description = 'A basic application description',
title = 'Hello World',
titleTemplate = '%s | My Application',
}: HeadProps) {
return (
<>
{title && <title>{titleTemplate ? titleTemplate.replace('%s', title) : title}</title>}
{description && <meta name="description" content={description} />}
<link rel="icon" type="image/png" href="/favicon.png" />
<meta name="theme-color" content="#f9fafb" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</>
);
}
export function defineHead<TProps extends HeadProps = HeadProps>(
options: TProps | ((props: NextHeadProps) => TProps),
children?: ReactNode,
): (props: NextHeadProps) => JSX.Element {
if (typeof options === 'function')
return ({ params }) =>
(function Head(): JSX.Element {
return (
<>
<BaseHead {...options({ params })} />
{children}
</>
);
})();
return function Head() {
return (
<>
<BaseHead {...options} />
{children}
</>
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment