Blog>
Snippets

Dynamic Route Generation Based on User Roles

Show how to dynamically generate routes in TanStack Router based on user roles using context.
import React, { useContext, useMemo } from 'react';
import { useRoutes, Navigate } from 'react-router-dom';
import { AuthContext } from './AuthContext';
import Dashboard from './Dashboard';
import AdminPanel from './AdminPanel';
import LoginPage from './LoginPage';
Import necessary modules and components. AuthContext is a created context that holds user authentication and role information.
const RouteSelector = () => {
  const { user } = useContext(AuthContext);

  const routes = useMemo(() => ({
    // Common route for all users
    '/login': () => <LoginPage />, 
    // Route conditionally rendered based on user role
    '/dashboard': () => user.role === 'admin' ? <AdminPanel /> : <Dashboard />,
    // Redirect unrecognized routes to login or dashboard based on authentication
    '*': () => user.loggedIn ? <Navigate to='/dashboard' /> : <Navigate to='/login' />
  }), [user]);

  const element = useRoutes(Object.keys(routes).map(path => ({ path, element: routes[path]() })));

  return element;
};
RouteSelector component uses user context to dynamically generate routes. useMemo hook ensures the routes configuration is recalculated only when user data changes. useRoutes hook generates route elements based on the defined configuration.
export default RouteSelector;
Exports the RouteSelector component for use in the application.