Imdadullah Babu
Full Stack Developer
2024-02-22
Full Stack Developer
In any web application, page titles play a crucial role in search engine optimization (SEO), user experience, and branding. Next.js provides powerful app routing and client-side rendering capabilities, enabling you to set page titles dynamically based on various contexts. This blog post explores different approaches to achieve this in your Next.js app
In a Next.js application, managing page titles dynamically can greatly enhance the user experience and SEO. Whether you want to set titles based on the current URL, manually inputted titles for specific pages, or dynamically fetch titles from other sources, Next.js provides flexible solutions. In this tutorial, we'll explore various use cases and implementation methods for dynamically setting page titles in a Next.js app.
In this approach, you can dynamically set the page title globally based on the URL of the page.
For example:
To implement this, add the following code snippet to your parent or global component:
1'use client'
2import { useRouter } from 'next/router';
3import { useEffect } from "react";
4
5export default function Component() {
6 useEffect(() => {
7 const path = pathname.split("/");
8 const current = path[path.length - 1];
9 document.title =
10 pathname === "/"
11 ? "Dashboard"
12 : current.charAt(0).toUpperCase() + current.slice(1);
13 }, [pathname]);
14
15 return <Component {...pageProps} />;
16}
Explanation:
This approach demonstrates how to set page titles for individual pages based on their specific data
1'use client'
2import { useEffect } from "react";
3
4export default function Component() {
5 useEffect(() => {
6 document.title = "Page Title"
7 }, []);
8
9 return <Component {...pageProps} />;
10}
This approach retrieves page title data from an external API or other source
1import { useEffect } from 'react';
2
3export default function Home() {
4 useEffect(() => {
5 const fetchData = async () => {
6 const response = await fetch('https://example.com/api/metadata');
7 const data = await response.json();
8 document.title = data.title;
9 };
10
11 fetchData();
12 }, []);
13
14 return (
15 <div>
16 {/* Home page content */}
17 </div>
18 );
19}
© 2024 IMDOS | All right reserved