Reputation: 1299
Issue: I need to access a URL parameter outside the component in v6.
I know I can use the useParams()
hook inside the component, But what if I needed to access a URL parameter outside the component?
This is how I used to do it in version 5:
// v5:
<Route
path = "/blog/:id"
render = {
({match:{params}}) => <Post item={ getPostById(params.id) } />
}
/>
I am accessing the :id
parameter outside the < Post />
component.
How can I write the previous code in v6?
Upvotes: 1
Views: 802
Reputation: 202917
With ({match:{params}}) => <Post item={ getPostById(params.id) } />
you've effectively written an anonymous React component that consumes a match
prop and renders your Post
component.
If you've components that can't use the useParams
hook then write a wrapper function component that reads the id
param from the useParams
hook and passes the id
along.
const PostWithIdParam = () => {
const { id } = useParams();
return <Post item={getPostById(id)} />;
};
...
<Route
path="/blog/:id"
element={<PostWithIdParam />}
/>
Upvotes: 1