Skip to content

Latest commit

 

History

History
80 lines (54 loc) · 2.89 KB

route-parameters.md

File metadata and controls

80 lines (54 loc) · 2.89 KB

Route Parameters: Dynamic Routing 🎭

Welcome back! Today, we’ll explore route parameters, a powerful feature in React Router that allows you to create dynamic routes based on user input or application state. This is especially useful for displaying individual resources, such as user profiles, product details, or blog posts.

What Are Route Parameters?

Route parameters are placeholders in the URL that allow you to capture values and pass them to your components. This enables you to create routes that can respond to dynamic data.

Example: Dynamic User Profile

Let’s say we have an application where users can view their profiles. We can use route parameters to display different profiles based on the user ID in the URL.

Setting Up the Routes

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import UserProfile from './UserProfile';
import NotFound from './NotFound';

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="user/:id" element={<UserProfile />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </Router>
  );
};

export default App;

Explanation:

  • User Profile Route: The route user/:id captures the user ID from the URL. For example, visiting /user/123 will capture 123 as the user ID.
  • NotFound Route: The wildcard route (*) is used to display a Not Found page for any other routes.

Accessing Route Parameters

In the UserProfile component, we can access the route parameter using the useParams hook.

import { useParams } from 'react-router-dom';

const UserProfile = () => {
  const { id } = useParams(); // Accessing the user ID from the URL

  return (
    <div>
      <h1>User Profile</h1>
      <p>Displaying profile for user ID: {id}</p>
      {/* Here you could fetch user data using the ID */}
    </div>
  );
};

export default UserProfile;

Explanation:

  • useParams Hook: This hook returns an object of key-value pairs of the dynamic parameters in the URL. In our case, we retrieve the id.
  • Dynamic Content: You can now use the ID to fetch and display user-specific information, making your app more dynamic and interactive.

Mia: "So, if I visit /user/456, I’ll see the profile for user 456?"

Leo: "Exactly! This makes your routes flexible and user-friendly." 🌈

When to Use Route Parameters

  • Dynamic Content: Use route parameters when you need to display content that changes based on user input or selections.
  • Resource Identification: Ideal for identifying resources, such as users, products, or articles, in a URL.

Fun Fact! 🎉

You can have multiple parameters in a single route! For example, /user/:id/post/:postId would allow you to capture both user and post IDs.

Navigation

Previous: Nested Routes: Structuring Your Application | Next: Conclusion