乐闻世界logo
搜索文章和话题

How to set documents title per page in nextjs?

2个答案

1
2

To set page titles in Next.js, leverage the next/head module to include HTML <head> elements, such as the <title> tag. Here are the steps to set specific titles for each page in your Next.js application:

  1. Import the Head Component In your page component file, import the Head component from next/head.
jsx
import Head from 'next/head';
  1. Use the Head Component in Your Page Component Within your page component's JSX, wrap the <title> tag inside the Head component and specify your desired title.

For example, to set the homepage title to 'Home Page', you can do the following:

jsx
import Head from 'next/head'; export default function Home() { return ( <> <Head> <title>Home Page</title> </Head> {/* Page content */} </> ); }
  1. Set Different Titles for Different Pages For each page in your application, follow the same approach to set unique titles. For instance, for an About page (about.js), set the title to 'About Us':
jsx
import Head from 'next/head'; export default function About() { return ( <> <Head> <title>About Us</title> </Head> {/* About page content */} </> ); }

This ensures each page has a personalized title, enhancing user experience and SEO optimization. When the page is rendered, the browser tab will display the relevant title.

Ensure that each page component uses the Head component to guarantee distinct titles for all pages. For applications with dynamic pages or route parameters, dynamically set the title based on page content or parameters.

2024年6月29日 12:07 回复

In Next.js v13 or v14, when using the app directory, you no longer need to use the next/head component. Instead, you simply define an exported object to set the title statically in layout.js or page.js, as shown in the example below:

javascript
export const metadata = { title: "Create Next App", description: "Generated by create next app", };

Alternatively, if you need a dynamic title, use the generateMetadata function to implement the required functionality, as demonstrated in the example below:

javascript
// In this example, the generateMetadata function creates a multi-language title. export async function generateMetadata({ params: { lng } }) { const myTitle = lng === "en" ? "Hi" : "مرحبا"; return { title: myTitle, }; }

Reference Metadata based on configuration

2024年6月29日 12:07 回复

你的答案