### Start Development Server Source: https://docs.keenthemes.com/metronic-react/guides/adding-new-page Run the development server to test the new page. ```bash npm run dev ``` -------------------------------- ### Implementing Login Source: https://docs.keenthemes.com/metronic-react/guides/authentication Example of handling user login via the auth context. ```javascript const { login, loading } = useAuthContext(); // Start login process when form is submitted const handleLogin = async (email, password) => { try { await login(email, password); // Redirect happens automatically } catch (error) { // Handle error } }; ``` -------------------------------- ### Install Project Dependencies Source: https://docs.keenthemes.com/metronic-react/getting-started/installation Use npm to install all required project dependencies. The --force flag is recommended to handle peer dependency warnings. ```bash npm install --force ``` -------------------------------- ### Start Development Server Source: https://docs.keenthemes.com/metronic-react/getting-started/installation Launch the local development server and access the application via the specified URL. ```bash npm run dev ``` ```text http://localhost:5173/metronic/tailwind/react/ ``` -------------------------------- ### Build for Production Source: https://docs.keenthemes.com/metronic-react/guides/deployment Commands to navigate to the project directory, install dependencies, and generate optimized production files in the dist folder. ```bash # Navigate to your project directory cd metronic-tailwind-react/typescript/vite # Install dependencies (if needed) npm install # Build for production npm run build ``` -------------------------------- ### Install Updated Dependencies Source: https://docs.keenthemes.com/metronic-react/guides/custom-auth Run this command to synchronize your local node_modules with the updated package.json. ```bash npm install ``` -------------------------------- ### Protecting Routes and Content Source: https://docs.keenthemes.com/metronic-react/guides/authentication Examples for securing routes and conditionally rendering UI components. ```javascript // Routes are already protected in routing configuration // }> // } /> // ``` ```javascript function AdminAction() { const { isAdmin, currentUser } = useAuthContext(); if (!currentUser) return null; return ( <> {isAdmin && } ); } ``` -------------------------------- ### Authentication Routes Setup Source: https://docs.keenthemes.com/metronic-react/guides/routing Defines routes for authentication, including login, register, and forgot password pages, wrapped in an AuthLayout. ```typescript // src/auth/auth-routing.tsx import { lazy } from 'react'; import { Routes, Route, Navigate } from 'react-router-dom'; import { AuthLayout } from '@/layouts/auth/layout'; const LoginPage = lazy(() => import('@/pages/auth/login-page')); const RegisterPage = lazy(() => import('@/pages/auth/register-page')); const ForgotPasswordPage = lazy(() => import('@/pages/auth/forgot-password-page')); export function AuthRouting() { return ( }> } /> } /> } /> } /> ); } ``` -------------------------------- ### Fetch Products with React Query Source: https://docs.keenthemes.com/metronic-react/guides/providers Use `useQuery` to fetch and display a list of products. Handles loading and error states automatically. Requires `fetchProducts` function and React Query setup. ```javascript import { useQuery } from '@tanstack/react-query'; import { fetchProducts } from '@/api/products'; function ProductList() { const { data, isLoading, error } = useQuery({ queryKey: ['products'], queryFn: fetchProducts }); if (isLoading) return
Loading...
; if (error) return
Error: {error.message}
; return ( ); } ``` -------------------------------- ### Page Structure Example Source: https://docs.keenthemes.com/metronic-react/getting-started/starter-kits Illustrates the organization of page components within the Metronic React project, specifically showing the structure for different layouts. ```tree pages/ ├── layout-1/ # Layout 1 pages │ └── page.tsx # Dashboard page ├── layout-2/ # Layout 2 pages │ └── page.tsx # Dashboard page └── ... # Other layouts (3-14) ``` -------------------------------- ### Toggle Theme with next-themes Source: https://docs.keenthemes.com/metronic-react/guides/providers Use the `useTheme` hook from `next-themes` to get the current theme and a function to set it. This example shows a simple button to toggle between 'dark' and 'light' themes. ```tsx import { useTheme } from 'next-themes'; function ThemeToggle() { const { theme, setTheme } = useTheme(); return ( ); } ``` -------------------------------- ### Configure Dashboard Layouts in Routes Source: https://docs.keenthemes.com/metronic-react/guides/layouts Use these examples to wrap specific routes with Demo1, Demo2, or Demo3 layouts in your React Router configuration. ```typescript // Using Demo1 Layout in your routes import { Demo1Layout } from '@/layouts/demo1/layout'; }> } /> } /> ``` ```typescript // Using Demo2 Layout in your routes import { Demo2Layout } from '@/layouts/demo2/layout'; }> } /> ``` ```typescript // Using Demo3 Layout in your routes import { Demo3Layout } from '@/layouts/demo3/layout'; }> } /> ``` -------------------------------- ### Main Router Setup in Metronic React Source: https://docs.keenthemes.com/metronic-react/guides/routing Sets up the main router using BrowserRouter and Suspense for lazy loading. The basename prop should match the vite.config.ts base configuration. ```typescript // src/routing/app-routing.tsx import { Suspense } from 'react'; import { BrowserRouter, useRoutes } from 'react-router-dom'; import { AppRoutingSetup } from './app-routing-setup'; import TopBarProgress from 'react-top-loading-bar'; import { useProgress } from '@/hooks/use-progress'; const Routing = () => { const { progress } = useProgress(); const routes = useRoutes(AppRoutingSetup()); return ( <> Loading...}> {routes} ); }; export function AppRouting() { return ( ); } ``` -------------------------------- ### Define Protected Route Source: https://docs.keenthemes.com/metronic-react/guides/adding-new-page Example of nesting a route within the authentication wrapper. ```jsx }> }> } /> ``` -------------------------------- ### Nginx Reverse Proxy Configuration Source: https://docs.keenthemes.com/metronic-react/guides/deployment Example Nginx location block and corresponding environment variable for deploying behind a reverse proxy. ```nginx location /metronic/tailwind/react { alias /path/to/your/dist; try_files $uri $uri/ /metronic/tailwind/react/index.html; } ``` ```bash VITE_BASE_URL=/metronic/tailwind/react ``` -------------------------------- ### Get Resolved Theme Source: https://docs.keenthemes.com/metronic-react/guides/providers Access the current theme state to apply conditional styling. ```javascript const { resolvedTheme } = useTheme(); const textColor = resolvedTheme === 'dark' ? 'text-white' : 'text-black'; ``` -------------------------------- ### Remove Unused Scripts from package.json Source: https://docs.keenthemes.com/metronic-react/guides/custom-auth Example of auth-related scripts to remove from your package.json file if they are no longer needed. ```json // Remove these if they exist: "create-demo-user": "tsx scripts/create-demo-user.js", "debug-auth": "tsx scripts/debug-auth.js" ``` -------------------------------- ### Define New Language Translations Source: https://docs.keenthemes.com/metronic-react/guides/internationalization Create a JSON file for a new language (e.g., 'fr.json') containing key-value pairs for all translatable strings used in the application. This example shows basic authentication-related translations. ```json // src/i18n/messages/fr.json { "AUTH.LOGIN.TITLE": "Connexion", "AUTH.LOGIN.BUTTON": "Se connecter", // Other translations... } ``` -------------------------------- ### Configure Environment Variables Source: https://docs.keenthemes.com/metronic-react/getting-started/installation Initialize the environment file and define the required API and theme configuration variables. ```bash cp .env.example .env ``` ```bash # API Configuration VITE_APP_BASE_LAYOUT_CONFIG_KEY=metronic-react-demo1-8150 VITE_APP_API_URL=https://preview.keenthemes.com/hero-api/api VITE_APP_VERSION=v9.2.0 VITE_APP_THEME_NAME=Metronic ``` -------------------------------- ### Project Structure Overview Source: https://docs.keenthemes.com/metronic-react/getting-started/starter-kits This outlines the directory structure for the Metronic React starter kit, showing the organization of components, pages, routing, and utilities. ```tree src/ ├── components/ # UI Components │ ├── layouts/ # Demo layouts (1-14) │ └── ui/ # Base UI components ├── pages/ # Page components │ ├── layout-1/ # Layout 1 pages │ ├── layout-2/ # Layout 2 pages │ └── ... # Other layouts ├── routing/ # Routing configuration ├── providers/ # React providers ├── hooks/ # Custom hooks ├── lib/ # Utilities └── App.tsx # Main app component ``` -------------------------------- ### Build for Production Source: https://docs.keenthemes.com/metronic-react/getting-started/installation Compile the project for production deployment into the dist directory. ```bash npm run build ``` -------------------------------- ### Create Page Directory Source: https://docs.keenthemes.com/metronic-react/guides/adding-new-page Use the command line to create the directory structure for the new page component. ```bash mkdir -p src/pages/example ``` -------------------------------- ### Basic React Query Usage Source: https://docs.keenthemes.com/metronic-react/guides/providers Demonstrates a basic `useQuery` hook to fetch data. Ensure `fetchUsers` is defined and accessible. ```javascript const { data } = useQuery({ queryKey: ['users'], queryFn: fetchUsers }); ``` -------------------------------- ### Register New User Source: https://docs.keenthemes.com/metronic-react/guides/authentication Register a new user account with email, password, and optional first and last names. ```javascript const { register } = useAuthContext(); // Register user await register( email, password, passwordConfirmation, firstName, // optional lastName // optional ); ``` -------------------------------- ### Select Theme - React Source: https://docs.keenthemes.com/metronic-react/guides/dark-mode Provide options to select between 'light', 'dark', and 'system' themes using the `useTheme` hook. ```javascript function ThemeSelector() { const { theme, setTheme } = useTheme(); return ( ); } ``` -------------------------------- ### Get Path Parameters with React Router Source: https://docs.keenthemes.com/metronic-react/guides/providers Extracts URL parameters like `userId` from the current route. Requires `useParams` hook from `react-router-dom`. ```javascript import { useParams } from 'react-router-dom'; const { userId } = useParams(); ``` -------------------------------- ### Check RTL Status with useLanguage Hook Source: https://docs.keenthemes.com/metronic-react/guides/rtl Use the `useLanguage` hook to get the `isRTL` function and conditionally apply classes for RTL-specific styling. ```javascript import { useLanguage } from '@/providers/i18n-provider'; function RTLAwareComponent() { const { isRTL } = useLanguage(); return (

This component adapts to the text direction

); } ``` -------------------------------- ### View Project Structure Source: https://docs.keenthemes.com/metronic-react/getting-started/installation Overview of the directory layout for the Metronic React project. ```text src/ ├── assets/ # Static assets (images, fonts, etc.) ├── auth/ # Authentication related files ├── components/ # Reusable UI components │ └── ui/ # Base UI components (Card, Button, etc.) ├── hooks/ # Custom React hooks ├── i18n/ # Internationalization files ├── layouts/ # Layout components (Demo1, Demo2, etc.) ├── lib/ # Utility libraries ├── pages/ # Page components organized by section ├── providers/ # React context providers ├── routing/ # Routing configuration └── App.tsx # Main application component ``` -------------------------------- ### Route and Location Management with React Router Source: https://docs.keenthemes.com/metronic-react/guides/providers Utilizes `useLocation` to get the current pathname and `useNavigate` for programmatic navigation. Useful for breadcrumbs or back buttons. ```javascript import { useLocation, useNavigate } from 'react-router-dom'; function BreadcrumbNav() { const { pathname } = useLocation(); const navigate = useNavigate(); return ( ); } ``` -------------------------------- ### Environment Configuration Source: https://docs.keenthemes.com/metronic-react/guides/authentication Required environment variables for Supabase integration. ```text VITE_SUPABASE_URL=your_supabase_url VITE_SUPABASE_ANON_KEY=your_supabase_anon_key ``` -------------------------------- ### Registration Source: https://docs.keenthemes.com/metronic-react/guides/authentication Register a new user with email, password, and optional first/last name. ```APIDOC ## Registration ### Description Register a new user. ### Method ```javascript const { register } = useAuthContext(); // Register user await register( email, password, passwordConfirmation, firstName, // optional lastName // optional ); ``` ``` -------------------------------- ### Perform Login with Auth Context Source: https://docs.keenthemes.com/metronic-react/guides/providers Initiate the login process by calling the `login` function obtained from `useAuthContext`, passing the user's email and password. ```javascript const { login } = useAuthContext(); await login(email, password); ``` -------------------------------- ### Create a Custom React Context Provider and Hook Source: https://docs.keenthemes.com/metronic-react/guides/providers Follow this pattern to create your own custom provider. It involves defining context, a custom hook for consumption, and the provider component itself. Ensure the hook includes error handling for cases where it's used outside the provider. ```javascript import { createContext, useContext, useState } from 'react'; const CounterContext = createContext({ count: 0, increment: () => {} }); export const useCounter = () => useContext(CounterContext); export function CounterProvider({ children }) { const [count, setCount] = useState(0); const increment = () => setCount(count + 1); return ( {children} ); } function Counter() { const { count, increment } = useCounter(); return (

Count: {count}

); } ``` -------------------------------- ### Settings Management Source: https://docs.keenthemes.com/metronic-react/guides/providers Retrieve settings or update them with temporary or persistent storage. ```javascript const { getOption } = useSettings(); const headerFixed = getOption('layout.header.fixed'); ``` ```javascript const { setOption } = useSettings(); setOption('layout.sidebar.minimized', true); ``` ```javascript const { storeOption } = useSettings(); storeOption('theme.darkMode', true); ``` -------------------------------- ### Authentication File Structure Source: https://docs.keenthemes.com/metronic-react/guides/authentication Overview of the directory structure for the authentication system. ```text src/auth/ ├── adapters/ # Authentication backend adapters │ └── supabase-adapter.ts # Supabase implementation ├── context/ # Context definitions │ └── auth-context.ts # Auth context interface ├── forms/ # Authentication form components ├── layouts/ # Auth page layouts ├── lib/ # Helper utilities │ ├── helpers.ts # Token management │ └── models.ts # Type definitions ├── pages/ # Auth pages (login, register, etc.) ├── providers/ # Context providers │ └── supabase-provider.tsx # Supabase auth implementation ├── auth-context.ts # Context export file ├── auth-routes.tsx # Auth routes definition ├── auth-routing.tsx # Auth routing component └── require-auth.tsx # Protected route component ``` -------------------------------- ### Troubleshoot Build Errors Source: https://docs.keenthemes.com/metronic-react/getting-started/installation Commands to clear existing modules and reinstall dependencies when encountering build issues. ```bash rm -rf node_modules npm install --force ``` -------------------------------- ### Perform Registration with Auth Context Source: https://docs.keenthemes.com/metronic-react/guides/providers Register a new user by calling the `register` function from `useAuthContext`, providing email, password, and password confirmation. ```javascript const { register } = useAuthContext(); await register(email, password, passwordConfirmation); ``` -------------------------------- ### Settings Provider Usage Source: https://docs.keenthemes.com/metronic-react/guides/providers Read and update application settings with persistence. ```javascript import { useSettings } from '@/providers/settings-provider'; function LayoutSettings() { const { getOption, storeOption } = useSettings(); const isCollapsed = getOption('sidebar.collapsed'); return (
); } ``` -------------------------------- ### Login Methods Source: https://docs.keenthemes.com/metronic-react/guides/authentication Supports email/password authentication and social logins via adapters. ```APIDOC ## Login Methods ### Description Supports email/password authentication and social logins via adapters. ### Email/Password Login ```javascript const { login } = useAuthContext(); // Login with email/password await login(email, password); ``` ### Social Login ```javascript import { SupabaseAdapter } from '@/auth/adapters/supabase-adapter'; // Social login (provider: 'google', 'github', 'facebook', 'twitter', 'discord', 'slack') await SupabaseAdapter.signInWithOAuth(provider); ``` ``` -------------------------------- ### Login with Email/Password Source: https://docs.keenthemes.com/metronic-react/guides/authentication Authenticate users by providing their email and password. ```javascript const { login } = useAuthContext(); // Login with email/password await login(email, password); ``` -------------------------------- ### Theme Selector Source: https://docs.keenthemes.com/metronic-react/guides/providers Implement a dropdown to switch between light, dark, and system themes. ```javascript const { setTheme } = useTheme(); ``` -------------------------------- ### Social Login with Supabase Adapter Source: https://docs.keenthemes.com/metronic-react/guides/providers Initiate a social login flow (e.g., Google) using the `SupabaseAdapter` by calling its `signInWithOAuth` method with the desired provider. ```javascript import { SupabaseAdapter } from '@/auth/adapters/supabase-adapter'; SupabaseAdapter.signInWithOAuth('google'); ``` -------------------------------- ### Setting up Nested Routes with Layouts Source: https://docs.keenthemes.com/metronic-react/guides/routing Organize related routes using nested routes. The parent route renders a layout component, and the `Outlet` component within the layout renders the child route's element. Use `index` for the default child route. ```javascript // In app-routing-setup.tsx }> } /> } /> } /> // In SettingsLayout component import { Outlet } from 'react-router-dom'; function SettingsLayout() { return (
); } ``` -------------------------------- ### Implement Demo1 Layout Component Source: https://docs.keenthemes.com/metronic-react/guides/layouts The Demo1 layout component structure, including sidebar, header, and footer integration. ```typescript // src/layouts/demo1/layout.tsx import { Helmet } from "react-helmet-async"; import { useMenu } from '@/hooks/use-menu'; import { MENU_SIDEBAR } from '@/config/menu.config'; import { Outlet } from 'react-router-dom'; import { Sidebar } from "./components/sidebar"; import { Footer } from "./components/footer"; import { Header } from "./components/header"; import { useIsMobile } from "@/hooks/use-mobile"; import { useSettings } from "@/providers/settings-provider"; import { useEffect } from "react"; export function Demo1Layout() { const isMobile = useIsMobile(); const { getCurrentItem } = useMenu(); const item = getCurrentItem(MENU_SIDEBAR); const { settings, setOption } = useSettings(); useEffect(() => { // Set current layout setOption('layout', 'demo1'); }, [setOption]); // CSS classes and side effects... return ( <> {item?.title} {!isMobile && }
); }; ``` -------------------------------- ### Create a Custom Layout Source: https://docs.keenthemes.com/metronic-react/guides/layouts Define a new layout structure by importing necessary components and using an Outlet for dynamic content. ```typescript // src/layouts/custom-layout/layout.tsx import { Outlet } from 'react-router-dom'; import { Header } from './components/header'; import { Sidebar } from './components/sidebar'; import { Footer } from './components/footer'; export function CustomLayout() { return (
); } ``` -------------------------------- ### Set Environment Variable for Base URL Source: https://docs.keenthemes.com/metronic-react/guides/deployment Defines the base path in the .env.production file for subdirectory or root deployments. ```bash # For subdirectory deployment VITE_BASE_URL=/metronic/tailwind/react # For root deployment VITE_BASE_URL=/ ``` -------------------------------- ### Use CSS Logical Properties for RTL Source: https://docs.keenthemes.com/metronic-react/guides/rtl Implement custom CSS using logical properties like `paddingInlineStart` and `marginInlineEnd` for robust RTL support. ```css // In your CSS or CSS-in-JS const styles = { container: { paddingInlineStart: '1rem', marginInlineEnd: '0.5rem', textAlign: 'start' } }; ``` -------------------------------- ### Define Page Component Source: https://docs.keenthemes.com/metronic-react/guides/adding-new-page Create the React component file using the required UI components and Helmet for SEO. ```typescript // src/pages/example/example-page.tsx import React from 'react'; import { Helmet } from 'react-helmet-async'; import { Card, CardHeader, CardContent, CardTitle, CardDescription } from '@/components/ui/card'; export function ExamplePage() { return ( <> Example Page | Metronic

Example Page

Card Title This is a description of the card.

This is an example page content.

); } ``` -------------------------------- ### Configure Authentication Layouts in Routes Source: https://docs.keenthemes.com/metronic-react/guides/layouts Wrap authentication-related routes with the AuthLayout component. ```typescript // Using Auth Layout in your routes import { AuthLayout } from '@/layouts/auth/layout'; }> } /> } /> ``` -------------------------------- ### Authentication State in Components Source: https://docs.keenthemes.com/metronic-react/guides/authentication Using authentication state to toggle UI elements. ```javascript function ProfileButton() { const { auth, loading } = useAuthContext(); if (loading) return ; return auth ? : ; } ``` -------------------------------- ### Configure Main Application Routing Source: https://docs.keenthemes.com/metronic-react/guides/layouts Apply layouts globally by nesting routes within layout components using the React Router Outlet pattern. ```typescript // src/routing/app-routing-setup.tsx import { ReactElement } from 'react'; import { Navigate, Route, Routes } from 'react-router'; import { DefaultPage } from '@/pages/dashboards'; import { RequireAuth } from '@/auth/require-auth'; import { Demo3Layout } from '@/layouts/demo3/layout'; import { ErrorRouting } from '@/errors/error-routing'; import { AuthRouting } from '@/auth/auth-routing'; const AppRoutingSetup = (): ReactElement => { return ( }> }> } /> {/* Other protected routes... */} } /> } /> } /> ); }; ``` -------------------------------- ### Remove Auth Adapters and Providers Source: https://docs.keenthemes.com/metronic-react/guides/custom-auth Remove the Supabase-specific auth adapter and provider files. ```bash rm -f src/auth/adapters/supabase-adapter.ts rm -f src/auth/providers/supabase-provider.tsx ``` -------------------------------- ### Demo3 Layout Component Source: https://docs.keenthemes.com/metronic-react/guides/routing Provides a consistent UI structure for routes using Header, Sidebar, and Footer components. Renders child routes using Outlet. ```typescript // src/layouts/demo3/layout.tsx import { Outlet } from 'react-router-dom'; import { Header } from './components/header'; import { Sidebar } from './components/sidebar'; import { Footer } from './components/footer'; export function Demo3Layout() { return (
); } ``` -------------------------------- ### Create API Client with Token Handling Source: https://docs.keenthemes.com/metronic-react/guides/custom-auth An API client that automatically includes the authorization token in requests and handles token expiration by redirecting to the login page. ```typescript const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000'; export const apiClient = { async request(endpoint: string, options: RequestInit = {}) { const auth = JSON.parse(localStorage.getItem('auth') || '{}'); const token = auth?.access_token; const config: RequestInit = { ...options, headers: { 'Content-Type': 'application/json', ...(token && { Authorization: `Bearer ${token}` }), ...options.headers, }, }; const response = await fetch(`${API_BASE_URL}${endpoint}`, config); if (response.status === 401) { // Token expired, redirect to login localStorage.removeItem('auth'); window.location.href = '/auth/signin'; return; } return response; }, }; ``` -------------------------------- ### Social Login with Supabase Adapter Source: https://docs.keenthemes.com/metronic-react/guides/authentication Facilitate social logins using providers like Google, GitHub, or Facebook via the Supabase adapter. ```javascript import { SupabaseAdapter } from '@/auth/adapters/supabase-adapter'; // Social login (provider: 'google', 'github', 'facebook', 'twitter', 'discord', 'slack') await SupabaseAdapter.signInWithOAuth(provider); ``` -------------------------------- ### Use Viewport Hook Source: https://docs.keenthemes.com/metronic-react/guides/hooks Monitor viewport dimensions (height and width) with automatic updates on window resize. Import from '@/hooks/use-viewport'. ```typescript import { useViewport } from '@/hooks/use-viewport'; function ResponsiveComponent() { const [height, width] = useViewport(); return (

Viewport Dimensions

Width

{width}px

Height

{height}px

); } ``` -------------------------------- ### Use useIntl Hook for Dynamic Content Source: https://docs.keenthemes.com/metronic-react/guides/internationalization The useIntl hook provides access to formatMessage and formatDate methods for dynamic or programmatic translation. ```typescript import { useIntl } from 'react-intl'; function ProfileCard({ username, joinDate }) { const intl = useIntl(); const formattedDate = intl.formatDate(joinDate, { year: 'numeric', month: 'long', day: 'numeric' }); const welcomeMessage = intl.formatMessage( { id: 'PROFILE.WELCOME' }, { username } ); return (

{welcomeMessage}

{intl.formatMessage({ id: 'PROFILE.JOIN_DATE' })}: {formattedDate}

); } ``` -------------------------------- ### Implement clipboard copying with useCopyToClipboard Source: https://docs.keenthemes.com/metronic-react/guides/hooks Provides a copy-to-clipboard function and tracks the success state. The timeout option defines how long the 'copied' state persists. ```typescript import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'; function CopyableText({ text }) { const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000, // Reset after 2 seconds onCopy: () => console.log('Text copied!') }); return (
{text}
); } ``` -------------------------------- ### Toggle RTL Mode for Testing Source: https://docs.keenthemes.com/metronic-react/guides/rtl Provide a button to toggle between RTL and LTR languages using the `changeLanguage` function from `useLanguage` for quick testing. ```javascript function RTLTester() { const { isRTL, changeLanguage, I18N_LANGUAGES } = useLanguage(); const rtlLanguage = I18N_LANGUAGES.find(lang => lang.direction === 'rtl'); const ltrLanguage = I18N_LANGUAGES.find(lang => lang.direction === 'ltr'); return ( ); } ``` -------------------------------- ### Defining Dynamic Routes with Parameters Source: https://docs.keenthemes.com/metronic-react/guides/routing Define dynamic routes using path parameters like `:id`. In the component, use the `useParams` hook to access these parameters. This is useful for displaying specific resource details. ```javascript // In app-routing-setup.tsx } /> // In ProfilePage component import { useParams } from 'react-router-dom'; function ProfilePage() { const { id } = useParams(); // Use the id parameter return
Profile ID: {id}
; } ``` -------------------------------- ### Navigate Programmatically with React Router Source: https://docs.keenthemes.com/metronic-react/guides/providers Provides functions to navigate between routes. Can navigate to a specific path or go back one step in history. Requires `useNavigate` hook. ```javascript import { useNavigate } from 'react-router-dom'; const navigate = useNavigate(); // Navigate to a new page navigate('/dashboard'); // Go back one step navigate(-1); ``` -------------------------------- ### Implement Auth-Branded Layout in Routes Source: https://docs.keenthemes.com/metronic-react/guides/layouts Use the AuthBrandedLayout component to wrap authentication-related routes. ```typescript // Using Auth-Branded Layout in your routes import { AuthBrandedLayout } from '@/layouts/auth-branded/layout'; }> } /> ``` -------------------------------- ### Route Configuration with Metadata Source: https://docs.keenthemes.com/metronic-react/guides/routing Define route configurations as an array of objects, including `meta` properties for custom data like titles and breadcrumbs. This allows for centralized route management and easy access to route-specific information. ```javascript // src/routing/routes.ts export const routes = [ { path: '/', element: , meta: { title: 'Dashboard', breadcrumb: 'Home' } }, { path: '/profile', element: , meta: { title: 'User Profile', breadcrumb: 'Profile' } } ]; ``` ```javascript // Example usage in a component import { useLocation } from 'react-router-dom'; import { routes } from '@/routing/routes'; function PageTitle() { const location = useLocation(); const route = routes.find(r => r.path === location.pathname); const title = route?.meta?.title || 'Metronic'; return

{title}

; } ``` -------------------------------- ### Implement Auth Layout Component Source: https://docs.keenthemes.com/metronic-react/guides/layouts The Auth layout component, which sets the page background image based on current settings. ```typescript // src/layouts/auth/layout.tsx import { Outlet } from 'react-router-dom'; import { toAbsoluteUrl } from '@/lib/helpers'; import { useSettings } from '@/providers/settings-provider'; import { useEffect } from 'react'; export function AuthLayout() { const { setOption } = useSettings(); // Set current layout useEffect(() => { setOption('layout', 'demo1'); }, [setOption]); return ( <>
); }; ``` -------------------------------- ### Hardcode Base URL in Config Source: https://docs.keenthemes.com/metronic-react/guides/deployment Alternative method to define the base path directly within the Vite configuration file. ```typescript export default defineConfig({ base: '/your-custom-path', // ... rest of config }); ``` -------------------------------- ### Remove Script Files Source: https://docs.keenthemes.com/metronic-react/guides/custom-auth Command to remove unused authentication script files from the project directory. ```bash rm -f scripts/create-demo-user.js rm -f scripts/debug-auth.js ``` -------------------------------- ### Format Dates and Numbers with React Intl Source: https://docs.keenthemes.com/metronic-react/guides/internationalization Utilize the `useIntl` hook from React Intl to format numbers as currency and dates into a readable format based on the current locale. Ensure transactions data includes `id`, `description`, `amount`, and `date` fields. ```typescript import { useIntl } from 'react-intl'; function TransactionList({ transactions }) { const intl = useIntl(); return (
    {transactions.map((transaction) => (
  • {transaction.description} {intl.formatNumber(transaction.amount, { style: 'currency', currency: 'USD' })} {intl.formatDate(transaction.date, { year: 'numeric', month: 'short', day: 'numeric' })}
  • ))}
); } ``` -------------------------------- ### Implement Language Selector with RTL Support Source: https://docs.keenthemes.com/metronic-react/guides/rtl Create a language selector using the `useLanguage` hook, allowing users to switch languages and automatically adapting the UI for RTL if needed. ```javascript function LanguageSelector() { const { changeLanguage, currenLanguage, I18N_LANGUAGES } = useLanguage(); return ( ); } ``` -------------------------------- ### Configure Layout Settings Dynamically Source: https://docs.keenthemes.com/metronic-react/guides/layouts Use the useSettings hook to modify layout configurations like sidebar state at runtime. ```typescript import { useSettings } from '@/providers/settings-provider'; function YourComponent() { const { settings, setOption } = useSettings(); // Toggle sidebar collapse const toggleSidebar = () => { setOption('layouts.demo1.sidebarCollapse', !settings.layouts.demo1.sidebarCollapse); }; return ( ); } ``` -------------------------------- ### Create Dynamic Route Page Source: https://docs.keenthemes.com/metronic-react/guides/adding-new-page Implement a page that accepts dynamic parameters using the useParams hook. ```typescript // src/pages/example/dynamic-page.tsx import { useParams } from 'react-router-dom'; export function DynamicExamplePage() { const { id } = useParams(); return (

Dynamic Page

Viewing item with ID: {id}

); } ``` ```typescript // In the AppRoutingSetup component } /> ``` -------------------------------- ### Update Sidebar Navigation Source: https://docs.keenthemes.com/metronic-react/guides/adding-new-page Add the new page link to the sidebar menu configuration. ```typescript // src/layouts/demo3/components/sidebar-menu.tsx import { BarChart3, FileText, // Add this import // ... other icons } from 'lucide-react'; export function SidebarMenu() { const items: Item[] = [ { icon: BarChart3, path: '/', title: 'Dashboard' }, { icon: FileText, path: '/example', title: 'Example Page' }, // ... other items ]; return ( // ... existing render code ); } ``` -------------------------------- ### Managing User Profiles Source: https://docs.keenthemes.com/metronic-react/guides/authentication Accessing and updating user profile information. ```javascript // Display user info const { currentUser } = useAuthContext(); const userName = currentUser?.fullname || `${currentUser?.first_name} ${currentUser?.last_name}`; // Update profile const { updateProfile } = useAuthContext(); await updateProfile({ first_name: "Updated", last_name: "Name" }); ``` -------------------------------- ### I18n Provider Usage Source: https://docs.keenthemes.com/metronic-react/guides/providers Manage language switching and RTL direction within a component. ```javascript import { useLanguage } from '@/providers/i18n-provider'; import { FormattedMessage } from 'react-intl'; function Header() { const { currenLanguage, changeLanguage, isRTL } = useLanguage(); return (

); } ``` -------------------------------- ### Configure Base URL in Vite Source: https://docs.keenthemes.com/metronic-react/guides/deployment Sets the base path for assets and routing in vite.config.ts using an environment variable. ```typescript import { defineConfig } from 'vite'; export default defineConfig({ plugins: [react(), tailwindcss()], base: process.env.VITE_BASE_URL || '/', // ... rest of config }); ``` -------------------------------- ### Create Custom Auth Provider Source: https://docs.keenthemes.com/metronic-react/guides/custom-auth Implement a new AuthProvider in src/auth/auth-provider.tsx to manage user state and mock authentication logic. ```typescript 'use client'; import { createContext, useContext, useState, useEffect, ReactNode, } from 'react'; interface User { id: string; email: string; name: string; avatar?: string; } interface AuthContextType { user: User | null; login: (email: string, password: string) => Promise; logout: () => void; isLoading: boolean; isAuthenticated: boolean; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null); const [isLoading, setIsLoading] = useState(true); // Check for existing session on mount useEffect(() => { const savedUser = localStorage.getItem('auth-user'); if (savedUser) { setUser(JSON.parse(savedUser)); } setIsLoading(false); }, []); const login = async (email: string, password: string): Promise => { setIsLoading(true); // Mock authentication - replace with your API call await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate API delay if (email === 'demo@kt.com' && password === 'demo123') { const mockUser: User = { id: '1', email: 'demo@kt.com', name: 'Demo User', avatar: '/media/avatars/300-2.png', }; setUser(mockUser); localStorage.setItem('auth-user', JSON.stringify(mockUser)); setIsLoading(false); return true; } setIsLoading(false); return false; }; const logout = () => { setUser(null); localStorage.removeItem('auth-user'); }; const isAuthenticated = !!user; return ( {children} ); } export function useAuth() { const context = useContext(AuthContext); if (context === undefined) { throw new Error('useAuth must be used within an AuthProvider'); } return context; } ``` -------------------------------- ### Basic React Query Mutation Source: https://docs.keenthemes.com/metronic-react/guides/providers Updates user data using `useMutation`. Invalidates the 'users' query on successful mutation to refetch data. Requires `updateUser` and `queryClient`. ```javascript const { mutate } = useMutation({ mutationFn: updateUser, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['users'] }); } }); // Call the mutation mutate(updatedUser); ``` -------------------------------- ### Auth Context Source: https://docs.keenthemes.com/metronic-react/guides/authentication The `useAuthContext` hook provides access to authentication state and methods like login, register, logout, and password management. ```APIDOC ## Auth Context ### Description The `useAuthContext` hook provides access to authentication state and methods. ### Usage ```javascript import { useAuthContext } from '@/auth/auth-context'; // Inside your component const { currentUser, // Current user data auth, // Auth tokens loading, // Auth loading state isAdmin, // Admin status login, // Login method register, // Registration method logout, // Logout method requestPasswordReset, // Password reset request resetPassword, // Password reset resendVerificationEmail, // Resend verification email updateProfile, // Update user profile getUser, // Get current user data verify // Verify auth state } = useAuthContext(); ``` ``` -------------------------------- ### Manage navigation state with useMenu Source: https://docs.keenthemes.com/metronic-react/guides/hooks Facilitates menu state management, including active path detection and breadcrumb generation for nested menu structures. ```typescript import { useMenu } from '@/hooks/use-menu'; import { MenuItem } from '@/config/types'; function NavigationMenu() { const { isActive, hasActiveChild, getBreadcrumb } = useMenu(); // Example menu items const menuItems: MenuItem[] = [ { title: 'Dashboard', path: '/dashboard', icon: 'HomeIcon' }, { title: 'Users', path: '/users', icon: 'UsersIcon', children: [ { title: 'User List', path: '/users/list' }, { title: 'User Profile', path: '/users/profile' } ] }, { title: 'Settings', path: '/settings', icon: 'SettingsIcon' } ]; // Get current breadcrumb const breadcrumb = getBreadcrumb(menuItems); return (

Navigation Menu

    {menuItems.map((item) => (
  • {item.title}
    {item.children && (
      {item.children.map((child) => (
    • {child.title}
    • ))}
    )}
  • ))}

Current Breadcrumb:

{breadcrumb.map((item, index) => (
{index > 0 && /} {item.title}
))}
); } ```