Passing parameters in routes is a fundamental aspect of building dynamic web applications. It allows developers to create flexible and reusable components that can respond to user input or application state. There are several ways to pass parameters in routes, depending on the routing library or framework being used. Below, I will outline the common methods, best practices, and potential pitfalls to avoid.
Parameters in routes can generally be categorized into two types: path parameters and query parameters.
Path parameters are part of the URL path and are typically used to identify a specific resource. For example, in a URL like /users/123, 123 is a path parameter representing a user ID.
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
return (
);
}
In the UserProfile component, you can access the userId parameter using the useParams hook:
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams();
return User ID: {userId};
}
Query parameters are appended to the URL after a question mark and can be used to filter or sort data. For example, in the URL /products?category=books&sort=asc, category and sort are query parameters.
useLocation hook:
import { useLocation } from 'react-router-dom';
function Products() {
const query = new URLSearchParams(useLocation().search);
const category = query.get('category');
const sort = query.get('sort');
return Category: {category}, Sort: {sort};
}
In summary, passing parameters in routes is crucial for creating dynamic applications. By understanding the differences between path and query parameters, following best practices, and avoiding common mistakes, developers can build robust and user-friendly applications.