icd2k3/react-router-breadcrumbs-hoc

How to map props of Component into breadcrumb title ?

Closed this issue · 5 comments

Hi There

this is amazing component I have been used, however I have a question how to get the props into breadcrumb text

e.g: users/:id , I have object in props let say {id:1, name:'john'}
I expect it should be users/john

Thanks

Hey @pmd30011991 this should be done within custom breadcrumb component (let's assume you're using redux with a userReducer)

const PureUserBreadcrumb = ({ firstName }) => <span>{firstName}</span>;

const mapStateToProps = (nextState, nextOwnProps) => ({
  firstName: nextState.userReducer.usersById[nextOwnProps.match.params.id].firstName,
});

export default connect(mapStateToProps)(PureUserBreadcrumb);

^ Each breadcrumb component is passed match as a prop. match comes directly from react-router api here. You can then use match.params.[id_name] to get the actual value.

Once you have that value you can use it to pull/render data however you need.

Putting it all together...

import React from 'react';
import { NavLink } from 'react-router-dom';
import { withBreadcrumbs } from 'react-router-breadcrumbs-hoc';
import UserBreadcrumb from './UserBreadcrumb';

const routes = [
  { path: 'users', breadcrumb: 'Users' },
  { path: 'users/:userId', breadcrumb: UserBreadcrumb},
];

const Breadcrumbs = ({ breadcrumbs }) => (
  <div>
    {breadcrumbs.map(({ breadcrumb, path, match }) => (
      <span key={path}>
        <NavLink to={match.url}>
          {breadcrumb}
        </NavLink>
        <span>/</span>
      </span>
    ))}
  </div>
);

For the above example, if my redux store has...
userReducer: { usersById: { 1: { firstName: 'John' } } }
and pathname is /users/1 the final display would be users / John.

Also, if you need to pass additional props (outside of match) into your breadcrumb components you could use this method:

{
  path: 'Something',
  breadcrumb: props => <SomeComponent additional="prop" {...props} />,
}

If neither of these suggestions solve your use case, please let me know and I can think about how to make it more flexible!

thanks.
what is compose module you are using ?

Never mind I can use connect instead of compose. can you help me understand what is difference between compose & connect ?

const ProjectOverviewBreadcrumb = (props) => <span>{props.project.name}</span>
const mapStateToProps = state => ({
    project: state.project.currentProject || {}
})

export default connect(
    mapStateToProps
  )(ProjectOverviewBreadcrumb)

@pmd30011991 oops, that was a typo - you're right, it should be connect not compose. I edited my answer above