A breadcrumb is a list that shows the hierarchical structure of a website.
Installing it will help you understand where your users are on your website.
Breadcrumb navigation – CSS: Cascading Style Sheets | MDN
This time, we will explain how to create a breadcrumb list using Remix.
How to implement
In Remix, you can create breadcrumbs for nested routes by using a combination of useMatches
,定数handle
, and Linkコンポーネント
.
The specific steps are as follows:
1. Define a "定数handle
" that returns Linkコンポーネント
on the page where you want to add a breadcrumb list.
For example, if a route exists in app/routes/parent.tsx
and app/routes/parent.children.tsx
, export it as follows:
Example: app/routes/parent.tsx
import { Link, Outlet } from "@remix-run/react" ;
// ...
export const handle = {
// The key name can be anything, but we'll call it breadcrumnb because it's easy to understand.
// The value passed to "to" is the path name to itself, and any display name can be given (here it is Parent Page)
breadcrumb : () => < Link to = "/parent" > Parent Page </ Link >
}
Example: app/routes/parent.children.tsx
import { Link } from "@remix-run/react" ;
// ...
export const handle = {
breadcrumb : () => < Link to = "/parent/children" > Children list page </ Link >
}
2. Add a component that uses useMatches
to get定数handle
you defined and display the contents in the form of a breadcrumb list.
For example, create a file called app/components/breadcrumb.tsx
and create a component like the one below.
Example: app/components/breadcrumb.tsx
import { useMatches } from "@remix-run/react"
export const Breadcrumb = () => {
const matches = useMatches()
return (
<ol style= {{ listStyle: "none" }} >
{
matches
.filter( (match) => match.handle?.breadcrumb)
.map( (match, index) => {
const separator = index === 0 ? null : ">"
return (
<li key={index} style= {{ display: "inline-block" }} >
{separator && <span style= {{ padding: "0 10px" }} >{separator}</span>}
{match.handle.breadcrumb(match)}
</li>
)
})
}
</ol>
)
}
3. Call the Breadcrumb component in a nested route parent component
For example, if you want to display breadcrumbs in app/routes/parent.tsx
and app/routes/parent.children.tsx
, write the following in app/routes/parent.tsx
.
Example: app/routes/parent.tsx
import { Breadcrumb } from "~/components/breadcrumb" ;
// ...
export default function Parent ( ) {
return (
<div>
<header>
{/* Display the added component (there is no particular meaning in enclosing it in a header tag) */}
< Breadcrumb />
</ header >
{/* ... */}
</ div >
)
}
// ...
The official documentation also explains how to create a breadcrumb list as an example of using useMatches, so be sure to check that out too.