I am new to react. I have a route with react router that takes :id
as parameter, how do I match this using react-router-dom useLocation.
basically path can be posts
or post/21
how do I match post/21 to render a component, I want to render a seperate component if I
am on the detail page
{path === 'post/:id' ? <PostDetail /> : <Posts /> }
but use location returns posts/1
which I can't use to match the post detail
summary
Any path that matches: post/:id
CodePudding user response:
Typically you will use a Switch
component with a set of Route
components. Each Route
takes a path prop that is used for matching.
import React from 'react';
import { BrowserRouter, Switch, Route, useRouteMatch } from 'react-router-dom';
const App = (props) => {
return (
<BrowserRouter>
<Switch>
<Route path="/post/:id">
<PostDetail />
</Route>
<Route path="/post">
<Posts />
</Route>
</Switch>
</BrowserRouter>
);
};
Components that are children of a Route
can use the useRouteMatch
hook to access path params.
const PostDetail = (props) => {
const match = useRouteMatch();
return <h1>{match.params.id}</h1>;
};