diff --git a/src/App.tsx b/src/App.tsx index 824db1c..1523e6f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -50,22 +50,12 @@ const App = () => { return `${appPublicRoutes.login}?callbackPath=${callbackPathEncoded}` } - const publicRoutesList = recursiveRouteRenderer({ - routes: publicRoutes, - renderConditionCallback: (r) => { - if (authState?.loggedIn) { - if (!r.hiddenWhenLoggedIn) { - return true - } - } else { - return true - } - - return false - } + // Hide route only if loggedIn and r.hiddenWhenLoggedIn are both true + const publicRoutesList = recursiveRouteRenderer(publicRoutes, (r) => { + return !authState.loggedIn || !r.hiddenWhenLoggedIn }) - const privateRouteList = recursiveRouteRenderer({ routes: privateRoutes }) + const privateRouteList = recursiveRouteRenderer(privateRoutes) return ( diff --git a/src/routes/index.tsx b/src/routes/index.tsx index 56c5970..9f811d5 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -41,42 +41,45 @@ export const getProfileRoute = (hexKey: string) => export const getProfileSettingsRoute = (hexKey: string) => appPrivateRoutes.profileSettings.replace(':npub', hexToNpub(hexKey)) +/** + * Helper type allows for extending react-router-dom's **RouteProps** with generic type + */ type CustomRouteProps = T & Omit & { children?: Array> } -interface CustomRoutes { - routes?: CustomRouteProps[] - renderConditionCallback?: (route: CustomRouteProps) => boolean -} - -type PublicRouteProps = CustomRouteProps<{ - hiddenWhenLoggedIn?: boolean -}> - -export function recursiveRouteRenderer({ - routes, - renderConditionCallback = () => true -}: CustomRoutes) { +/** + * This function maps over nested routes with optional condition for rendering + * @param {CustomRouteProps[]} routes - routes list + * @param {RenderConditionCallbackFn} renderConditionCallbackFn - render condition callback (default true) + */ +export function recursiveRouteRenderer( + routes?: CustomRouteProps[], + renderConditionCallbackFn: (route: CustomRouteProps) => boolean = () => + true +) { if (!routes) return null + // Callback allows us to pass arbitrary conditions for each route's rendering + // Skipping the callback will by default evaluate to true (show route) return routes.map((route, index) => - renderConditionCallback(route) ? ( + renderConditionCallbackFn(route) ? ( - {recursiveRouteRenderer({ - routes: route.children, - renderConditionCallback - })} + {recursiveRouteRenderer(route.children, renderConditionCallbackFn)} ) : null ) } +type PublicRouteProps = CustomRouteProps<{ + hiddenWhenLoggedIn?: boolean +}> + export const publicRoutes: PublicRouteProps[] = [ { path: appPublicRoutes.landingPage,