Creating Dynamic Routes and Route Parameters
Illustrate how to define dynamic routes that adapt based on parameters passed in the URL, enabling personalized user experiences through URL patterns.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
Imports necessary components from 'react-router-dom' for routing.
function User({ match }) {
// Extract the userId parameter from the URL
const { userId } = match.params;
return <div>User ID: {userId}</div>;
}
Defines a User component that extracts a userId parameter from the URL.
function App() {
return (
<Router>
<Switch>
{/* Route for the home page */}
<Route path='/' exact component={Home} />
{/* Dynamic route for user, capturing the userId parameter */}
<Route path='/user/:userId' component={User} />
</Switch>
</Router>
);
}
Defines the main App component that includes a dynamic route for individual users based on the userId URL parameter.