Created
November 19, 2022 07:51
-
-
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
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 { 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