Persistent Layouts in Inertiajs: How to Create and Use Them?
Persistent layouts in Inertia.js is a feature that allows you to create and use shared components or layouts across multiple pages without having to re-render them on each request. This can help improve the performance of your application by reducing the number of requests and the amount of data that needs to be sent over the network.
To create and use persistent layouts in Inertia.js, follow these steps:
- Create a shared component or layout:
First, create a component or layout that you want to use as a persistent layout. This component should contain the HTML, CSS, and JavaScript that you want to reuse across multiple pages. For example, you might create a SharedLayout.js
file that contains a header, footer, and sidebar.
// SharedLayout.js
import React from 'react';
const SharedLayout = ({ children }) => {
return (
<div className="container">
<header className="header">Header</header>
<aside className="sidebar">Sidebar</aside>
<main className="content">{children}</main>
<footer className="footer">Footer</footer>
</div>
);
};
export default SharedLayout;
- Wrap your pages in the persistent layout:
Next, wrap each page component that you want to use with the persistent layout in a new component that renders both the layout and the page. For example, you might create a Page.js
file that accepts a children
prop and renders the SharedLayout
component with the page component as its children.
// Page.js
import React from 'react';
import SharedLayout from './SharedLayout';
const Page = ({ component: PageComponent, props }) => {
return (
<SharedLayout>
<PageComponent {...props} />
</SharedLayout>
);
};
export default Page;
- Define routes with the persistent layout:
Finally, define your routes in routes.js
file with the Page
component instead of the page component directly. This will ensure that the persistent layout is rendered for each page.
// routes.js
import React from 'react';
import { Link, route } from '@inertiajs/react';
import Page from './Page';
const HomePage = () => <Page component={require('../Pages/Home').default} />;
export default function () {
return (
<div className="app">
<header className="navbar">
<Link href="/">Home</Link>
</header>
<main className="content">
<HomePage />
</main>
</div>
);
}
With these steps, you have created and used a persistent layout in Inertia.js. The layout will only be fetched once when the application is first loaded, and then reused for all subsequent requests to pages that use the layout. This can help improve the performance of your application by reducing the number of requests and the amount of data that needs to be sent over the network.