Skip to content

Instantly share code, notes, and snippets.

@Tin
Last active March 25, 2017 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tin/1528a7348e2dfe272faf26b085d55e9e to your computer and use it in GitHub Desktop.
Save Tin/1528a7348e2dfe272faf26b085d55e9e to your computer and use it in GitHub Desktop.
iterate react-router config and print out all paths
// Say we have routes configuration like
const routes = [
{
"childRoutes": [
{
"path": "/"
},
{
"path": "/anonymous-landing"
},
{
"path": "/signin"
},
{
"path": "/signout"
},
{
"path": "/register"
},
{
"path": "/forgot-password"
},
{
"path": "/address-unavailable"
},
{
"path": "product/:sku"
},
{
"path": "products"
},
{
"path": "product/:sku/similar"
},
{
"path": "browse/:shelfId"
},
{
"path": "/account",
"indexRoute": {},
"childRoutes": [
{
"path": "payment-methods"
},
{
"path": "addresses"
}
]
},
{
"path": "/orders",
"indexRoute": {},
"childRoutes": [
{
"path": "/orders/:orderId"
},
{
"path": "/orders/:orderId/edit/amend"
},
{
"path": "/orders/:orderId/edit/items-not-available"
},
{
"path": "/orders/:orderId/edit/items"
}
]
},
{
"path": "/favorites"
},
{
"path": "/reservation"
},
{
"path": "/checkout",
"indexRoute": {},
"childRoutes": [
{
"path": "review"
},
{
"path": "stockup"
},
{
"path": "items-not-available"
},
{
"path": "payment"
},
{
"path": "confirmation/:orderId"
},
{
"path": "restricted-items"
}
]
},
{
"path": "/survey"
},
{
"path": "help*"
},
{
"path": "service-unavailable"
},
{
"path": "upgrade"
},
{
"path": "*"
}
]
}
];
const reactRouteReducer = ({paths, parentPath}, route) => {
const currentPath = route.path ? `${parentPath}/${route.path.replace(/^\//, '')}` : parentPath;
if (route.path) {
paths.push(currentPath);
}
if (route.childRoutes) {
route.childRoutes.reduce(reactRouteReducer, {paths, parentPath: currentPath});
}
return {paths, parentPath};
};
console.log(JSON.stringify(
{paths: routes.reduce(reactRouteReducer, {
paths: [], parentPath: ''
}).paths}, null, 2)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment