Material-UI Breadcrumb Integration with react-router

本秂侑毒 提交于 2021-01-07 06:03:17

问题


I'm trying to use the Material-UI breadcrumb with react-router. How can I programatically detect the current route.

On the Material-UI website there is an example on how to use it but it requires the usage of a static breadcrumbNameMap. I already tried to split the pathname by using the HOC "withRouter" but it doesn't work.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Breadcrumbs, Link, Paper, Typography} from "@material-ui/core";

import { withRouter } from "react-router-dom";

import { useTranslation } from "../Translate";

const useStyles = makeStyles(theme => ({
    root: {
        justifyContent: "center",
        flexWrap: "wrap",
    },
    paper: {
        padding: theme.spacing(1, 2),
    },
}));

const breadcrumbNameMap = {
    "/inbox": "Inbox",
    "/inbox/important": "Important",
    "/trash": "Trash",
    "/spam": "Spam",
    "/drafts": "Drafts",
};

function SimpleBreadcrumbs(props) {
    const classes = useStyles();
    console.log("Breadcrumbs", props);
    const { location } = props;
    const pathnames = location.pathname.split("/").filter(x => x);
    console.log("pathnames", pathnames);

    return (
        <div className={classes.root}>
            <Paper elevation={0} className={classes.paper}>
                <Breadcrumbs aria-label="Breadcrumb">
                    <Link color="inherit" href="/">
                        Home
                    </Link>
                    {pathnames.map((value, index) => {
                        const last = index === pathnames.length - 1;
                        const to = `/${pathnames
                            .slice(0, index + 1)
                            .join("/")}`;

                        console.log("last", last, "to", to);

                        const path = value.split("-");
                        console.log("path", path);
                        // Convert first char of string to uppercase
                        path.forEach((item, i) => {
                            // Only capitalize starting from the second element
                            if (i > 0) {
                                path[i] =
                                    path[i].charAt(0).toUpperCase() +
                                    path[i].slice(1);
                            }
                        });

                        // return (
                        //     <Typography color="textPrimary" key={to}>
                        //         {useTranslation(path.join(""))}
                        //     </Typography>
                        // );

                        // // return (
                        // //     <Typography color="textPrimary" key={to}>
                        // //         {pathnames[to]}
                        // //     </Typography>
                        // // );

                        return last ? (
                            <Typography color="textPrimary" key={to}>
                                {breadcrumbNameMap[to]}
                            </Typography>
                        ) : (
                            <Link color="inherit" to={to} key={to}>
                                {useTranslation(path.join(""))}
                            </Link>
                        );
                    })}
                </Breadcrumbs>
            </Paper>
        </div>
    );
}

export default withRouter(SimpleBreadcrumbs);

If the URL in my browser points to "http://example.com/level1/level2", I would expected the output of the breadcrumb to be:

Home / Level1 / Level2

If the URL in the browser would be "http://example.com/level1/", I would expect:

Home / Level 1

The translation can also be added later. I included it for showing my final expected result.


回答1:


You need breadcrumbNameMap only if labels on breadcrumbs are different then the link URLs (e.g. path '/level1' is displayed as 'Level 1' in the breadcrumb.

Here is a modified version of Material UI Breadcrumb example integrated with react router.

Try it out complete program here https://codesandbox.io/s/dark-architecture-sgl12?fontsize=14

https://sgl12.codesandbox.io/level1/level2

import React from 'react';
import Breadcrumbs from '@material-ui/core/Breadcrumbs';
import Typography from '@material-ui/core/Typography';
import { Link as RouterLink } from 'react-router-dom';
import { Route, BrowserRouter as Router } from 'react-router-dom';

function SimpleBreadcrumbs() {
  return <Route>
    {({ location }) => {
      const pathnames = location.pathname.split('/').filter(x => x);
      return (
        <Breadcrumbs aria-label="Breadcrumb">
          <RouterLink color="inherit" to="/">
            Home
            </RouterLink>
          {pathnames.map((value, index) => {
            const last = index === pathnames.length - 1;
            const to = `/${pathnames.slice(0, index + 1).join('/')}`;

            return last ? (
              <Typography color="textPrimary" key={to}>
                {value}
              </Typography>
            ) : (
                <RouterLink color="inherit" to={to} key={to}>
                  {value}
                </RouterLink>
              );
          })}
        </Breadcrumbs>
      );
    }}
  </Route>

}

export default function App() {
  return <div>
    <Router>
      <SimpleBreadcrumbs />

      <Route path='/' exact component={Home}></Route>
      <Route path='/level1' exact component={Level1}></Route>
      <Route path='/level1/level2' exact component={Level2}></Route>

    </Router>
  </div>
}



回答2:


I've edited Meera's great code to solve some of the problems I was facing: I wanted title-cased links rather than lower-cased. I've added useLocation hook, and made few other changes.

import React from 'react'
import { useLocation, Link as RouterLink } from 'react-router-dom'
import { Breadcrumbs, Typography, Link } from '@material-ui/core'

function toTitleCase(str) {
  return str.replace(/\b\w+/g, function (s) {
    return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase()
  })
}

export default function () {
  let location = useLocation()
  const pathnames = location.pathname.split('/').filter((x) => x)

  return (
    <Breadcrumbs aria-label='Breadcrumb'>
      <Link color='inherit' component={RouterLink} to='/'>
        Home
      </Link>
      {pathnames.map((value, index) => {
        const last = index === pathnames.length - 1
        const to = `/${pathnames.slice(0, index + 1).join('/')}`

        return last ? (
          <Typography color='textPrimary' key={to}>
            {toTitleCase(value)}
          </Typography>
        ) : (
          <Link color='inherit' component={RouterLink} to='/' key={to}>
            {toTitleCase(value)}
          </Link>
        )
      })}
    </Breadcrumbs>
  )
}



回答3:


I decided to post a separate answer instead of a comment to your code, Meera. Thank you for your help. I modified the body part of the map function and added the capability to translate. Sadly, it is not working for me with the react hooks feature, so thats why i converted it into a class component.

My component does now look like this:

import React, { PureComponent } from "react";
import * as PropTypes from "prop-types";
import { Breadcrumbs, Link, Paper, Typography } from "@material-ui/core";
import { connect } from "react-redux";
import { Route, Link as RouterLink } from "react-router-dom";

import { LanguageActions } from "../../redux/actions";

/**
 * This component has to be a class component to be able
 * to translate the path values dynamically.
 * React hooks are not working in this case.
 */
class SimpleBreadcrumbs extends PureComponent {
    render = () => {
        const { translate } = this.props;
        const LinkRouter = props => <Link {...props} component={RouterLink} />;

        return (
            <Paper elevation={0} style={{ padding: "8px 16px" }}>
                <Route>
                    {({ location }) => {
                        const pathnames = location.pathname
                            .split("/")
                            .filter(x => x);
                        return (
                            <Breadcrumbs aria-label="Breadcrumb">
                                <LinkRouter
                                    color="inherit"
                                    component={RouterLink}
                                    to="/"
                                >
                                    Home
                                </LinkRouter>
                                {pathnames.map((value, index) => {
                                    const last = index === pathnames.length - 1;
                                    const to = `/${pathnames
                                        .slice(0, index + 1)
                                        .join("/")}`;

                                    // Split value so the string can be transformed and parsed later.
                                    const path = value.split("-");
                                    // Convert first char of string to uppercase.
                                    path.forEach((item, i) => {
                                        // Only capitalize starting from the second element.
                                        if (i > 0) {
                                            path[i] =
                                                path[i]
                                                    .charAt(0)
                                                    .toUpperCase() +
                                                path[i].slice(1);
                                        }
                                    });

                                    return last ? (
                                        <Typography
                                            color="textPrimary"
                                            key={to}
                                        >
                                            {translate(path.join(""))}
                                        </Typography>
                                    ) : (
                                        <LinkRouter
                                            color="inherit"
                                            to={to}
                                            key={to}
                                        >
                                            {translate(path.join(""))}
                                        </LinkRouter>
                                    );
                                })}
                            </Breadcrumbs>
                        );
                    }}
                </Route>
            </Paper>
        );
    };
}

// To be able to translate every breadcrumb step,
// translations have to be passed down to this component.
// Otherwise the component does not get notified
// if user decides to switch language
const connector = connect(
    ({ translations }) => ({ translations }),
    dispatch => ({
        translate: key => dispatch(LanguageActions.translate(key)),
    })
);

SimpleBreadcrumbs.propTypes = {
    translate: PropTypes.func,
};

SimpleBreadcrumbs.defaultProps = {
    translate: () => {},
};

export default connector(SimpleBreadcrumbs);


来源:https://stackoverflow.com/questions/56489498/material-ui-breadcrumb-integration-with-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!