Our application doesn't have a Meta Title, and there are no title in the Blade layout. How do we pass different title to individual pages?
To add title or any meta tag, Inertia has a Head
component. First, we must import this Head
component into the page component. Then, we can use this component to add a title.
resources/js/Pages/Posts/Index.jsx:
import AppLayout from '../../Layouts/AppLayout.jsx';import { Head } from '@inertiajs/react'; export default function PostsIndex({ posts }) { return ( <AppLayout> <Head> <title>Posts</title> </Head> // ... </AppLayout> );};
We can see the title on the posts page.
If you have only a title, you can make it shorter.
resources/js/Pages/Posts/Index.jsx:
import AppLayout from '../../Layouts/AppLayout.jsx';import { Head } from '@inertiajs/react'; export default function PostsIndex({ posts }) { return ( <AppLayout> <Head title="Posts" /> // ... </AppLayout> );};
The same goes for the About page.
resources/js/Pages/About.jsx:
import AppLayout from '../Layouts/AppLayout.jsx';import { Head } from '@inertiajs/react'; export default function About() { return ( <AppLayout> <Head title="About" /> <div> About us </div> </AppLayout> );}
Also, there are cases when you have the project name in your title, but some part of that is dynamic. For example, posts - inertia course
. You can define that global repeating title directly in the resources/js/app.jsx
.
resources/js/app.jsx:
import './bootstrap'; import { createInertiaApp } from '@inertiajs/react'import { createRoot } from 'react-dom/client' createInertiaApp({ title: (title) => `${title} - Inertia Course`, resolve: name => { const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true }) return pages[`./Pages/${name}.jsx`] }, setup({ el, App, props }) { createRoot(el).render(<App {...props} />) }, progress: { color: '#f00', showSpinner: true, },})