Defining Masked Routes with TanStack Router
Demonstrate the creation of SEO-friendly masked routes using TanStack Router, including dynamic parameterized routes that cater to user-friendly URL structures.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router-dom';
import UserProfile from './UserProfile';
import Home from './Home';
// Define routes using createBrowserRouter
const router = createBrowserRouter([
{
path: '/',
element: <Home />,
children: [
// Masked dynamic route for user profiles
{
path: 'user/:userId',
element: <UserProfile />,
loader: async ({ params }) => {
// Assuming fetchUserById is an async function returning user data
return fetchUserById(params.userId);
}
}
]
}
]);
This code creates a browser router with a home route and a dynamic child route for user profiles. The dynamic route is masked as 'user/:userId', providing a user-friendly URL. It uses an asynchronous loader to fetch user data based on the userId parameter.
import { createRoot } from 'react-dom/client';
// Assuming you have an App component where the RouterProvider is used
function App() {
return (
<RouterProvider router={router} />
);
}
// Render the App component to the DOM
const root = createRoot(document.getElementById('root'));
root.render(<App />);
This code snippet illustrates how to render the App component that utilizes RouterProvider with the configured router. It wraps the App component's content with the RouterProvider, passing the created router as a prop to manage the routing logic.