Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing a URL parameter outside the element in react-router-v6

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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?

>Solution :

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 />}
/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading