Blog>
Snippets

Dynamic Route Matching and Parameters

Showcase creating a route with dynamic segments for handling user profiles, extracting parameters from the URL to fetch and display user data.
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to='/user/john_doe'>John Doe's Profile</Link>
            </li>
            <li>
              <Link to='/user/jane_doe'>Jane Doe's Profile</Link>
            </li>
          </ul>
        </nav>
        <Route path='/user/:username' component={UserProfile} />
      </div>
    </Router>
  );
}

export default App;
This code sets up a Router with two Links and a dynamic Route. The dynamic Route uses a path parameter to match user profiles.
function UserProfile({ match }) {
  // Extract the username from the URL parameter
  const { username } = match.params;

  // Logic to fetch user data based on the username would go here
  // For demonstration, we'll simply display the username
  return (
    <div>
      <h2>User Profile</h2>
      <p>Username: {username}</p>
    </div>
  );
}
This component displays the user profile. It extracts the 'username' parameter from the URL to fetch and display user data.