How can I set dynamically the number for useNavigation hook?

Viewed 26

I'm trying to write a react Breadcrumbs component which automatically sets the needed number for go back navigation in react-router-dom.

I have an array with pathnames, it's length can be 2 or more. All items are links which go back on several steps except the last one

users(goes two pages back) / name(goes on the previous page) / type(inactive)

I decided to use useNavigation hook in react-router-dom to go back.

// This is my array, for instance
const pathnames = ['users', 'name', 'type'];

So I need a function/method which will look like this.

pathTokens.map((item, index, arr) => {
 if (item !== arr[arr.length - 1]) {
   return <BreadcrumbsItem action ={() => navigate(numberOfStepsBack)} content={item}/>
 } else {
   return <BreadcrumbsItem content={item}/>
 }
});
1 Answers

If I understand your question correctly you want to compute the number of back navigations to allow per breadcrumb segment.

Given:

  • const pathnames = ['users', 'name', 'type'];
  • users (goes two pages back, -2) / name (goes on the previous page, -1) / type (inactive, 0)

Use the equation index + 1 - pathnames.length to compute the number of back navigations per mapped breadcrumb segment.

Segment index equation: index + 1 - pathnames.length goBack
users 0 0 + 1 - 3 -2
name 1 1 + 1 - 3 -1
type 2 2 + 1 - 3 0

Applied to your mapping function:

pathTokens.map((item, index, arr) => {
  const numberOfStepsBack = index + 1 - arr.length;
  const action = () => navigate(numberOfStepsBack);
  return (
    <BreadcrumbsItem
      {...numberOfStepsBack ? { action } : {}}
      content={item}
    />
  );
});
Related