import React from 'react';
import { useRoutes, useNavigate, useLocation } from '@openwebf/react-router';
// Page components
function Home() {
const { navigate } = useNavigate();
const location = useLocation();
return (
Home Page
Current path: {location.pathname}
);
}
function About() {
const { navigate } = useNavigate();
const location = useLocation();
return (
About Page
Current path: {location.pathname}
{location.state?.from && (
Navigated from: {location.state.from}
)}
);
}
function Users() {
const { navigate } = useNavigate();
return (
Users Page
User list would go here
);
}
function Contact() {
const { navigate } = useNavigate();
return (
Contact Page
Contact form would go here
);
}
// Main App using useRoutes hook
export default function UseRoutesExample() {
// Define routes as configuration objects
const routeConfig = [
{
path: '/',
element:
},
{
path: '/about',
element:
},
{
path: '/users',
element:
},
{
path: '/contact',
element: ,
prerender: true // This route will be pre-rendered
}
];
// Generate route elements using useRoutes
const routes = useRoutes(routeConfig);
return (
UseRoutes Example
This example demonstrates using route configuration objects instead of JSX
{routes}
);
}
// Alternative approach with dynamic route configuration
export function DynamicRoutesExample() {
const [isAuthenticated] = React.useState(true);
// Dynamic route configuration based on authentication
const routeConfig = React.useMemo(() => {
const baseRoutes = [
{ path: '/', element: },
{ path: '/about', element: }
];
if (isAuthenticated) {
return [
...baseRoutes,
{ path: '/users', element: },
{ path: '/contact', element: }
];
}
return baseRoutes;
}, [isAuthenticated]);
const routes = useRoutes(routeConfig);
return (
Dynamic Routes Example
Routes change based on authentication status
{routes}
);
}