TanStackT
TanStack2y ago
3 replies
verbal-lime

Unable to change the title dynamically per page

This is probably a stupid question, but I'm not sure how to dynamically change the <title> aspect of the main html file. Doing it like something below does work however it's a messy implementation. Any ideas?

_root.tsx
import * as React from 'react'
import {createRootRoute, Link, Outlet, ScrollRestoration, useRouterState} from '@tanstack/react-router'
import '../index.css'

export const Route = createRootRoute({
    component: RootComponent,
    notFoundComponent: () => {
        return <NotFoundComponent />
    },
})

function RootComponent() {
    return (
        <RootDocument>
            <Outlet />
        </RootDocument>
    )
}

function RootDocument({children}: { children: React.ReactNode }) {
    return (
        <Html>
            {children}
            <ScrollRestoration />
        </Html>
    )
}

function Html({children}: { children: React.ReactNode }) {
    const breadcrumbs = useRouterState({
        select: (state) => {
            return state.matches
                .map((match) => ({
                    title: match.meta?.find((tag) => tag.title)?.title,
                    path: match.pathname,
                }))
                .filter((crumb) => Boolean(crumb.title));
        },
    });

    const breadcrumb = breadcrumbs.at(0);

    return (
        <html lang="en">
        <head>
            <meta charSet="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>
                {breadcrumb?.title ? `${breadcrumb.title} - ` : 'GlassHost - Transparent, Reliable, Affordable Hosting'}
            </title>
        </head>
        <body>
            <div id="app" className="h-screen">{children}</div>
            <script type="module" src="/src/index.tsx"></script>
        </body>
        </html>
    )
}
Was this page helpful?