Blog>
Snippets

Using Dynamic Routing

Explain with code how to implement dynamic routes that adjust based on user input or other variable data, using TanStack Router.
import { createBrowserRouter, RouterProvider, Route } from 'tanstack-router-react';
// Import your components
import UserProfile from './UserProfile';
import Home from './Home';
First, import necessary components from 'tanstack-router-react' and your custom components.
const router = createBrowserRouter([
  {
    path: '/',
    element: <Home />,
  },
  {
    // Dynamic route based on userId
    path: '/user/:userId',
    element: <UserProfile />,
  }
]);
Create a router with a dynamic route for user profiles. The ':userId' part of the path is a variable placeholder.
function App() {
  return <RouterProvider router={router} />;
}
Create the main App component that uses the RouterProvider to enable routing.
export default App;
Export the App component for use in your application.