Breadcrumb.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import React from 'react';
  2. import { Link, useLocation, useParams } from 'react-router-dom';
  3. import cn from 'classnames';
  4. import { clusterPath } from 'lib/paths';
  5. import { capitalize } from 'lodash';
  6. export interface BreadcrumbItem {
  7. label: string;
  8. href: string;
  9. }
  10. interface Props {
  11. links?: BreadcrumbItem[];
  12. }
  13. const basePathEntriesLength = clusterPath(':clusterName').split('/').length;
  14. const Breadcrumb: React.FC<Props> = () => {
  15. const location = useLocation();
  16. const params = useParams();
  17. const pathParams = React.useMemo(() => Object.values(params), [params]);
  18. const paths = location.pathname.split('/');
  19. const links = React.useMemo(
  20. () =>
  21. paths.slice(basePathEntriesLength).map((path, index) => {
  22. return !pathParams.includes(paths[basePathEntriesLength + index])
  23. ? path.split('-').map(capitalize).join(' ')
  24. : path;
  25. }),
  26. [paths]
  27. );
  28. const currentLink = React.useMemo(() => {
  29. if (paths.length < basePathEntriesLength) {
  30. return 'Dashboard';
  31. }
  32. return links[links.length - 1];
  33. }, [links]);
  34. const getPathPredicate = React.useCallback(
  35. (index: number) =>
  36. `${paths.slice(0, basePathEntriesLength + index + 1).join('/')}`,
  37. [paths]
  38. );
  39. return (
  40. <nav className="breadcrumb mb-2 pt-2" aria-label="breadcrumbs">
  41. <ul className={cn('py-3', 'px-4', { 'py-3': !links.length })}>
  42. {links.slice(0, links.length - 1).map((link, index) => (
  43. <li key={link}>
  44. <Link to={getPathPredicate(index)}>{link}</Link>
  45. </li>
  46. ))}
  47. <li
  48. className={cn('is-active', {
  49. 'is-size-4 has-text-weight-medium is-capitalized': links.length < 2,
  50. })}
  51. >
  52. <span>{currentLink}</span>
  53. </li>
  54. </ul>
  55. </nav>
  56. );
  57. };
  58. export default Breadcrumb;