How to pass query params via React Router 6

With React Router, you can create nested routes easily by passing parameters to your routes.

Install react-router to your project

npm install react-router-dom@6Code language: CSS (css)

Import Router component,  and Routes, Route, Link, Outlet  from react-router-dom

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link,
  Outlet,
} from "react-router-dom";Code language: JavaScript (javascript)

Pass the routes, route element within the router.

Pass the parameters to your route element

Then you can access it on the route by using useParams()  

When you click on the passed Link, it will take you to the corresponding route

In this example, we are fetching remote blog posts, passing the id to the remote blog item component.

import { RemoteApiBlogPostItem } from "../RemoteApiBlogPosts";
export default function BlogPosts({ posts}) {
return (
    <>
<Router>
      <div className="blog">
      <h2>Blog Posts</h2>
      <ul className="blog-posts">
        {
         posts && posts.map((post,index) => (
            <li
              key={post.id}
            >
              <Link to={`/post/${post.id}`}>{post.title.rendered</Link>}
            </li>
          ))
        }
      </ul>
      </div>
 <Routes>
        <Route path="post" element={<Post />}>
          <Route path=":id"  element={<RemoteApiBlogPostItem />} />
        </Route>
       </Routes>
    </Router>
</>
  );
}
function Post() {
  return (
    <div>
      <Outlet />
    </div>
  );
}Code language: JavaScript (javascript)

Path pattern: /post/:id

Dynamic segment here is id, so the actual URLs will be post/123, post/245, etc

So we will be using the /post URL that matches multiple routes (with post ids) 

<Outlet/> will render the matched object, the one that matches the URL parameters, id in this case. 

useParams() to get the value of id from the URL parameters.

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

export  function RemoteApiBlogPostItem() {
  const { id } = useParams();
/* data fetching */
}Code language: JavaScript (javascript)

Here is the working demo: https://reactjs-starters-api-request.netlify.app/

Repo: https://github.com/laxmariappan/reactjs-starters/tree/03-remote-api-request-lm/src

References:
https://reactrouter.com/docs/en/v6/getting-started/tutorial#reading-url-params

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *