Route Parameters
In React Router, you can use route parameters to pass dynamic values in the route URL. These parameters can be accessed within the rendered component using the match
prop provided by React Router.
To define a route parameter, you can use :
followed by the parameter name in the path
of the Route
component. For example, let's say we want to create a dynamic route for different topics:
1<Route path="/topics/:topicId" component={Topic} />
In this example, the :topicId
is a route parameter that can match any value after the /topics/
segment in the URL. When the URL matches this pattern, the Topic
component will be rendered, and the match
prop will contain the params
object with the parameter value.
You can access the route parameter value by destructuring topicId
from match.params
. For example:
1function Topic({ match }) {
2 const { topicId } = match.params;
3 // Use the topicId to render specific content
4}
You can then use the topicId
to render specific content related to that topic.
Try running the code snippet in your own React project and navigate to different topic URLs to see how the route parameter is accessed and rendered in the Topic
component.
xxxxxxxxxx
}
// Let's assume we have a React Router setup in our application
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<div>
<h1>Welcome to AlgoDaily!</h1>
<Route exact path="/" component={Home} />
<Route path="/topics/:topicId" component={Topic} />
</div>
</Router>
);
}
function Home() {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to the home page of AlgoDaily!</p>
</div>
);
}
function Topic({ match }) {
const { topicId } = match.params;
return (