To set a default layout for your Inertia + React (TypeScript) application, you can modify the resolve function to wrap your pages with a layout component. Here's how you can achieve this:
- Create a layout component, for example,
DefaultLayout.tsx:
// resources/js/layouts/DefaultLayout.tsx
import React from 'react';
const DefaultLayout: React.FC = ({ children }) => {
return (
<div>
<header>My App Header</header>
<main>{children}</main>
<footer>My App Footer</footer>
</div>
);
};
export default DefaultLayout;
- Modify the
resolvefunction in yourcreateInertiaAppsetup to wrap each page with theDefaultLayout:
// resources/js/app.tsx
import { createInertiaApp } from '@inertiajs/react';
import { createRoot } from 'react-dom/client';
import DefaultLayout from './layouts/DefaultLayout';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: async (name) => {
const page = (await resolvePageComponent(`./pages/${name}.tsx`, import.meta.glob('./pages/**/*.tsx'))).default;
// If the page component has a layout, use it; otherwise, use the default layout
page.layout = page.layout || ((page: React.ReactNode) => <DefaultLayout>{page}</DefaultLayout>);
return page;
},
setup({ el, App, props }) {
const root = createRoot(el);
root.render(<App {...props} />);
},
progress: {
color: '#4B5563',
},
});
In this setup, each page component can optionally define its own layout by setting a layout property. If a page does not specify a layout, it will default to using DefaultLayout. This approach provides flexibility for pages that require a different layout while maintaining a consistent default layout for the rest of the application.