Let's start talking about layouts. Our current main problem is duplication of the menu code for Posts and About pages.
First, we need a React component as the main layout. We will create a new folder resources/js/Layouts
and a React component, AppLayout.jsx
inside it.
Move the repeating code from the Posts/Index.jsx
and About.jsx
React components to the Layouts/AppLayout.jsx
React component.
resources/js/Pages/Posts/Index.jsx:
import { Link } from '@inertiajs/react'; export default function PostsIndex({ posts }) { return ( <div> <div className="mb-4"> <Link className="mr-2" href={route('posts.index')}>Posts</Link> <Link href={route('about')}>About</Link> </div> <table className="min-w-full divide-y divide-gray-200 border"> // ... </table> </div> );};
resources/js/Pages/About.jsx:
import { Link } from '@inertiajs/react'; export default function About() { return ( <div> <div className="mb-4"> <Link className="mr-2" href={route('posts.index')}>Posts</Link> <Link href={route('about')}>About</Link> </div> About us </div> );}
resources/js/Layouts/AppLayout.jsx:
import { Link } from '@inertiajs/react'; export default function AppLayout({ children }) { return ( <div> <div className="mb-4"> <Link href={route('posts.index')}>Posts</Link> <Link href={route('about')}>About</Link> </div> <main>{children}</main> </div> );}
To tell React where to add the content, we use children.
How do you use that AppLayout
layout? We must import it into the React component and surround everything with it.
resources/js/Pages/Posts/Index.jsx:
import AppLayout from '../../Layouts/AppLayout.jsx'; export default function PostsIndex({ posts }) { return ( <AppLayout> // ... </AppLayout> );};
resources/js/Pages/About.jsx:
import { Link } from '@inertiajs/react';import AppLayout from '../Layouts/AppLayout.jsx'; export default function About() { return ( <AppLayout> <div> <div className="mb-4"> <Link className="mr-2" href={route('posts.index')}>Posts</Link> <Link href={route('about')}>About</Link> </div> About us </div> </AppLayout> );}
Visually, nothing changes, but now we don't have duplicate code.
In this lesson, "along the way", let's also add a CSS class to indicate which links in the menu are active.
There are a few ways to do that. In this lesson, we will use the route()
function to check if the route is active.
resources/js/Layouts/AppLayout.jsx:
import { Link } from '@inertiajs/react'; export default function AppLayout({ children }) { return ( <div> <div className="mb-4"> <Link href={route('posts.index')}>Posts</Link> <Link href={route('about')}>About</Link> <Link className={`mr-2 ${route().current('posts.index') ? 'font-bond underline' : ''}`} href={route('posts.index')}>Posts</Link> <Link className={route().current('about') ? 'font-bond underline' : ''} href={route('about')}>About</Link> </div> <main>{children}</main> </div> );}
Now, we have one main layout with the links, and from that layout, we build all the pages in the future lessons.