Skip to content

Instantly share code, notes, and snippets.

@JorensM
Created January 15, 2024 07:18
Show Gist options
  • Save JorensM/9d68d069353aec1bb66f93776c8941d2 to your computer and use it in GitHub Desktop.
Save JorensM/9d68d069353aec1bb66f93776c8941d2 to your computer and use it in GitHub Desktop.
import useAuth from '#hooks/useAuth';
import AuthContext from '#state/AuthContext';
import { User } from '#types/User';
import { router } from 'expo-router';
import { Drawer } from 'expo-router/drawer';
import { usePathname } from 'expo-router/src/hooks';
import { useEffect, useMemo, useState } from 'react';
export const unstable_settings = {
// Ensure any route can link back to `/`
initialRouteName: 'login',
};
// Routes that should be available when user is not signed in
const guest_routes: string[] = [
'login',
'register'
]
// Routes that should be available when user is signed in
const user_routes: string[] = [
'feed',
'new-listing'
]
// Routes that are hidden from navigation
const hidden_routes: string[] = [
'index',
'edit-listing'
]
// These must be non-component functions because for some reason otherwise the drawer
// doesn't register these items
const renderDrawerItem = (name: string, label: string, hide = false, title?: string) => {
return (
<Drawer.Screen
name={name}
options={{
drawerLabel: label,
title: title || label,
drawerItemStyle: {
display: hide ? 'none' : 'flex'
}
}}
key={name}
/>
)
}
// Same as with renderDrawerItem
const renderHiddenRoute = (name: string) => {
return (
<Drawer.Screen
name={name}
options={{
drawerItemStyle: {
display: 'none'
}
}}
key={name}
/>
)
}
const CustomDrawer = () => {
const auth = useAuth()
// Check if drawer item should be hidden depending on whether
// The user is logged in or not
const shouldHideItem = (name: string) => {
if(
(user_routes.includes(name) && auth.user) ||
(guest_routes.includes(name) && !auth.user)) {
return false;
}
return true;
}
return (
<Drawer>
{/* Guest routes */}
{
[
renderDrawerItem('login', 'Login', shouldHideItem('login')),
renderDrawerItem('register', 'Register', shouldHideItem('register'))
]
}
{/* User routes */}
{
[
renderDrawerItem('new-listing', 'New Listing', shouldHideItem('new-listing')),
renderDrawerItem('feed', 'Feed', shouldHideItem('new-listing')),
]
}
{/* Hidden routes */}
{hidden_routes.map(route_name => {
return renderHiddenRoute(route_name)
})}
</Drawer>
)
}
export default function Layout() {
return (
<CustomDrawer />
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment