Dynamic Breadcrumb in NextJS - Kevin Uriel Fonseca
A breadcrumb or breadcrumb trail is a graphical control element used as a navigational aid in user interfaces and on web pages. It allows users to keep track and maintain awareness of their locations within programs, documents, or websites. The term is a reference to the trail of bread crumbs left by Hansel and Gretel in the German fairy tale of the same name. Wikipedia.
import { useEffect, useState } from 'react'import Link from 'next/link'const BreadCrumbs = ({ router }) => { // Capitalize const convertBreadcrumb = (string) => { return string .replace(/-/g, ' ') .replace(/oe/g, 'ö') .replace(/ae/g, 'ä') .replace(/ue/g, 'ü') .toUpperCase() } // Set State const [breadcrumbs, setBreadcrumbs] = useState(null) // Make it run on reload useEffect(() => { const routePath = router.asPath.split('/') routePath.shift() const pathArray = routePath.map((path, i) => { return { text: path, href: '/' + routePath.slice(0, i + 1).join('/'), } }) setBreadcrumbs(pathArray) }, [router]) // Run it every time there's a change in router // If undefined, return null if (!breadcrumbs) { return null } return breadcrumbs.map((breadcrumb, index) => { return ( <Link key={index} href={breadcrumb.href} passHref> <a>{convertBreadcrumb(breadcrumb.text)}</a> </Link> ) })}export default BreadCrumbs/*** ASSUMING THERES A PAGE, YOU CAN IMPORT THIS COMPONENT* AND MAKE SURE TO PASS THE ROUTER PARAMETER.**/import { withRouter } from "next/router";import BreadCrumb from 'YOUR_FOLDER/BreadCrumbs';const Index = ({router}) => { return <> <BreadCrumb router={router} /> <p>CONTENT</p> </>};export default withRouter(Index);
Remember to check my previous blogs.
NOTE: Remember that by wrapping your page with the withRouter HOC
will enable you to use the router object in your page, thats why you also need to call the router in your page parameter and from there pass said object to the <BreadCrumbs router={router} />
component.
Bye Bye! 🙂
SIDEBAR