Render the <head /> element dynamically in Next.js

Xiaoru Li
InstructorXiaoru Li
Share this video with your friends

Social Share Links

Send Tweet

Next.js treats single-file components in the /pages/ directory as pages, so we need to work around this abstraction to access and modify the <head> element of the page. In this lesson, we will learn how to render the <head> element dynamically with a constantly updated title in Next.js 9, and see how this feature can be helpful for loading custom fonts.

Instructor: [0:00] Here we have a custom hook that simulates a marquee scrolling text effect. To render this constantly updated text to the title of this web page, we need to first get access to the head elements in the document object of the page by importing a special head component from next/head.

[0:21] Now, we can dynamically override the title element of the page inside a head component. Here we go. Notice that we're also allowed to use multiple head components. We can consider that the children of these head components will simply merge together.

[0:42] For example, we can add a meta tag for the description of this page. Here, we can see with the DevTools, all the header elements are properly injected to the page.