Sign in
Topics
Dynamic routing is a part of modern web development, we can create flexible and interactive user experience. In React the useParams hook from react-router-dom package is used to access URL parameters and render dynamic content based on the current route. This article will go into the details of useParams hook and show how to use it in dynamic routing with examples and screenshots.
Dynamic routing allows components to render based on the current URL path, enabling the creation of multi-view applications without full page reloads. React Router, a standard library for routing in React applications, provides the tools necessary to implement dynamic routing seamlessly.
In React Router, dynamic segments in route paths are defined using the colon (:) prefix. These segments act as placeholders for variable parts of the URL, known as URL parameters. For instance:
1<Route path="/user/:userId" component={UserProfile} />
In this example, :userId
is a dynamic segment that captures the value in the URL following /user/
, allowing the UserProfile component to render content specific to that userId.
The useParams hook is a function provided by react-router-dom that returns an object of key/value pairs from the current URL's dynamic parameters. It enables functional components to access these parameters directly, promoting cleaner and more readable code.
1import { useParams } from 'react-router-dom'; 2 3const params = useParams();
Here, params is an object containing the URL parameters defined in the route path.
To illustrate the practical application of the useParams hook, consider a scenario where we need to display details of a specific product based on the productId present in the URL.
First, define a route with a dynamic segment in your main application component:
1import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; 2import ProductDetail from './ProductDetail'; 3 4function App() { 5 return ( 6 <Router> 7 <Switch> 8 <Route path="/product/:productId" component={ProductDetail} /> 9 </Switch> 10 </Router> 11 ); 12} 13 14export default App;
In this setup, the path string /product/:productId
specifies that any URL matching this pattern should render the ProductDetail component.
Within the ProductDetail functional component, use the useParams hook to retrieve the productId from the URL:
1import { useParams } from 'react-router-dom'; 2 3function ProductDetail() { 4 const { productId } = useParams(); 5 6 // Fetch product data based on productId 7 // ... 8 9 return ( 10 <div> 11 <h1>Product ID: {productId}</h1> 12 {/* Render product details */} 13 </div> 14 ); 15} 16 17export default ProductDetail;
By destructuring the productId from the object returned by useParams, you can utilize this value to fetch and display the corresponding product data.
In scenarios where multiple parameters are required, define them in the route path and access them using useParams. For example:
1<Route path="/category/:categoryId/product/:productId" component={ProductDetail} />
1import { useParams } from 'react-router-dom'; 2 3function ProductDetail() { 4 const { categoryId, productId } = useParams(); 5 6 // Fetch data based on categoryId and productId 7 // ... 8 9 return ( 10 <div> 11 <h1>Category ID: {categoryId}</h1> 12 <h2>Product ID: {productId}</h2> 13 {/* Render product details */} 14 </div> 15 ); 16} 17 18export default ProductDetail;
In this example, both categoryId and productId are extracted from the URL, allowing for more granular data fetching and rendering.
To better understand how routes with dynamic parameters are matched, consider the following diagram illustrating the process:
This flowchart demonstrates that when a user navigates to a URL like /category/5/product/42
, React Router matches it to the defined route, extracts the parameters, and renders the appropriate component.
To showcase a real-world application, let's implement a component that fetches product data from an API using the productId from the URL.
1<Route path="/product/:productId" component={ProductDetail} />
1import { useParams } from 'react-router-dom'; 2import { useEffect, useState } from 'react'; 3 4function ProductDetail() { 5 const { productId } = useParams(); 6 const [product, setProduct] = useState(null); 7 8 useEffect(() => { 9 // Replace with your API call 10 fetch(`https://api.example.com/products/${productId}`) 11 .then(response => response.json()) 12 .then(data => setProduct(data)); 13 }, [productId]); 14 15 if (!product) { 16 return <div>Loading...</div>; 17 } 18 19 return ( 20 <div> 21 <h1>{product.name}</h1> 22 <p>{product.description}</p> 23 <p>Price: ${product.price}</p> 24 </div> 25 ); 26} 27 28export default ProductDetail;
In this component:
• The useParams hook retrieves the productId from the URL.
• The useEffect hook performs an API call to fetch the product data whenever the productId changes.
• The component renders the product details once the data is fetched.
Using useParams in React makes working with dynamic routes easier and better. By getting URL params in functional components you can create flexible and interactive experiences. useParams makes code more readable and keeps routing logic clean which is inline with modern React practices. Using useParams makes managing dynamic routes more simple and organized.
All you need is the vibe. The platform takes care of the product.
Turn your one-liners into a production-grade app in minutes with AI assistance - not just prototype, but a full-fledged product.