When using React Router with dynamic parameters, it is common to need to fetch the data required to display on the page. In this blog, we will explore two ways to achieve this.

Using useParams Hook

To begin, declare the route in the following manner:

<Route path="/project/:id">
  <SingleProject />
</Route>

In this code snippet, the :id in the path represents the dynamic part of the URL, which will be accessible as the id parameter in the SingleProject component.

Next, in the SingleProject component, use the useParams hook from the react-router-dom package to access the id parameter:

import { useParams } from 'react-router-dom';

// ...

const SingleProject = () => {
  const { id } = useParams();
  
  // Fetch data using the id parameter
  
  return (
    // Render the component
  );
}

In this way, you can utilize the id parameter to filter data from an array or query a database.

Using Props

An alternative approach is to pass the props to the component using the render prop of the Route component. Here’s how you can achieve it:

<Route path="/project/:id" render={(props) => <SingleProject {...props} />} />

Inside the SingleProject component, which is responsible for displaying the data, access the parameters by destructuring match.params from the props object:

const SingleProject = (props) => {
  const { id } = props.match.params;

  // Fetch data using the id parameter

  return (
    // Render the component
  );
}

This approach is useful when you want to lookup data in your data source before rendering the component.

In some cases, you may need to obtain the parameters directly in the inline rendered routes. Here’s an example:

const posts = [
  { id: 1, title: 'First', content: 'Hello world!' },
  { id: 2, title: 'Second', content: 'Hello again!' }
];

const Post = ({ post }) => (
  <div>
    <h2>{post.title}</h2>
    {post.content}
  </div>
);

// ...

<Route exact path="/post/:id" render={({ match }) => (
  <Post post={posts.find(p => p.id === match.params.id)} />
)} />

In this case, the id parameter is used to lookup post data from the data source before rendering the Post component.