DEV Community

Cover image for React Router: Get the current route
collegewap
collegewap

Posted on • Originally published at codingdeft.com

React Router: Get the current route

Have you started using React Router for navigation in React and want to know how to access the current route, URL parameters, query parameters, etc? You are at the right place.

Project set up

First, let's create a react app using the following command:

npx create-react-app react-router-current-route
Enter fullscreen mode Exit fullscreen mode

Now let's install react-router-dom and history packages inside it:

npm i react-router-dom history
Enter fullscreen mode Exit fullscreen mode

Now in index.js import BrowserRouter component from React router and wrap the App component within it.

import React from "react"
import ReactDOM from "react-dom/client"
import "./index.css"
import App from "./App"

import { BrowserRouter } from "react-router-dom"

const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
)
Enter fullscreen mode Exit fullscreen mode

In the App.js, create routes to 4 different pages and add links to them as shown below:

import { Link, Route, Routes } from "react-router-dom"

function App() {
  return (
    <div className="App">
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="dashboard">Dashboard</Link>
          </li>
          <li>
            <Link to="search?term=phones">Search</Link>
          </li>
          <li>
            <Link to="order/12345">Order Details</Link>
          </li>
        </ul>
      </nav>
      <Routes>
        <Route path="/" element={<Home />}></Route>
        <Route path="dashboard" element={<Dashboard />}></Route>
        <Route path="search" element={<Search />}></Route>
        <Route path="order/:orderId" element={<OrderDetails />}></Route>
      </Routes>
    </div>
  )
}

function Home() {
  return <div>Home</div>
}

function Dashboard() {
  return <div>Dashboard</div>
}

function Search() {
  return <div>Search</div>
}

function OrderDetails() {
  return <div>Order Details</div>
}

export default App
Enter fullscreen mode Exit fullscreen mode

In the above code, we have:

  • Dashboard page, where we will be accessing the current route.
  • Search page with query parameter
  • Order details page with URL parameter

Accessing current route

React router exports a hook called useLocation, which contains information about the URL.

We can access the current path as shown below:

function Dashboard() {
  const location = useLocation()
  return <div>Location: {location.pathname}</div> // 👉 Location: /dashboard
}
Enter fullscreen mode Exit fullscreen mode

Accessing the Query parameters

The useLocation hook returns the query parameter inside the search property. However it will be in the format: ?a=b&c=d.
We can pass it to URLSearchParams to parse it.

function useQuery() {
  // Use the URLSearchParams API to extract the query parameters
  // useLocation().search will have the query parameters eg: ?foo=bar&a=b
  return new URLSearchParams(useLocation().search)
}

function Search() {
  const query = useQuery()
  const term = query.get("term")

  return <div>Search term: {term}</div> // 👉 Search term: phones
}
Enter fullscreen mode Exit fullscreen mode

Accessing the URL parameters

If you want to access the URL parameters like order id, invoice id, etc, first you need to define it in the route:

<Route path="order/:orderId" element={<OrderDetails />}></Route>

Now if you access the path /order/12345, useParams() hook will return the orderId in the Order Details component:

function OrderDetails() {
  const { orderId } = useParams()
  return <div>Order Details: {orderId}</div> // 👉 Order Details: 12345
}
Enter fullscreen mode Exit fullscreen mode

Complete code

You can to refer the following complete code for all the examples:

import { Routes, Route, Link, useParams, useLocation } from "react-router-dom"

function App() {
  return (
    <div className="App">
      {" "}
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="dashboard">Dashboard</Link>
          </li>
          <li>
            <Link to="search?term=phones">Search</Link>
          </li>
          <li>
            <Link to="order/12345">Order Details</Link>
          </li>
        </ul>
      </nav>
      <Routes>
        <Route path="/" element={<Home />}></Route>
        <Route path="dashboard" element={<Dashboard />}></Route>
        <Route path="search" element={<Search />}></Route>
        <Route path="order/:orderId" element={<OrderDetails />}></Route>
      </Routes>
    </div>
  )
}

function Home() {
  return <div>Home</div>
}

function Dashboard() {
  const location = useLocation()

  return <div>Location: {location.pathname}</div>
}

function useQuery() {
  // Use the URLSearchParams API to extract the query parameters
  // useLocation().search will have the query parameters eg: ?foo=bar&a=b
  return new URLSearchParams(useLocation().search)
}

function Search() {
  const query = useQuery()
  const term = query.get("term")

  return <div>Search term: {term}</div>
}

function OrderDetails() {
  const { orderId } = useParams()
  return <div>Order Details: {orderId}</div>
}

export default App
Enter fullscreen mode Exit fullscreen mode

Top comments (0)