In Next.js 13 with the new app directory routing activated, it's very simple to set a dynamic HTML title to each individual route.
Case 1: Make the URL of a blog post the HTML title value.
Folder hierarchy: ./app/post/[postUrl]/page.tsx
Just add another file, called "head.tsx" and add a React boiler plate like this (in VS Code, typing "rfce" + tab will create this for you):
import React from 'react'function head() { return ( <div>head</div> ) }
export default head
Now, to destructure the parameters and make the TypeScript compiler happy at the same time, change the code to be:
import React from 'react'function head({ params }: { params: { postUrl: string } }) { return ( <> <title>{params.postUrl}</title> </> ) }
export default head
The title will now be "next-js-13-how-to-set-dynamic-html-head-titles" in our case, which does not look good yet. It would be nicer to have each first letter in upper case and to remove the "-" characters:
import React from 'react'function head({ params }: { params: { postUrl: string } }) {
const array = params.postUrl.split("-");
const upperCaseWords = array.map(word => { return
${word[0].toUpperCase()}${word.slice(1)}
}); const titleString =Be Sure Blog | ${upperCaseWords.join(" ")}
;return ( <> <title>{titleString}</title> </> ) }
export default head
Done! The title is now "Be Sure Blog | Next Js 13 How To Set Dynamic Html Head Titles"