How to access url parameters in React Js

Last updated : Jul 30, 2023 12:00 AM

The useParams hook from react-router-dom allows us to access the URL parameters in React Js. Let's see how to do that.

Below is the standard routing code for a simple application. Make sure you use the React router version 6 to work with this example.

<BrowserRouter>
  <Routes>
      <Route path="/" element={<App />} />
      <Route path="/home/:day" element={<Home />} />
      <Route path="contact/:dept" element={<Contact />} />
  </Routes>
</BrowserRouter>

The routes for Home and Contact components contain a placeholder for a URL parameter pass into the component.

<Route path="/home/:day" element={<Home />} />
<Route path="contact/:dept" element={<Contact />} />

The syntax to pass the url parameter is
/home/Friday, /home/Saturday etc... The below is the full code example on how to attach the parameter to the url.

import { Link } from "react-router-dom";
export const App = () => {
  return(
      <div style={{padding: 30}}>
        <h2>React Router</h2>
        <p>URL parameters in React Js</p>
        <div>
            <button className="button green"><Link to="/home/Friday">Home | Friday</Link></button>
            <button className="button green"><Link to="/home/Saturday">Home | Saturday</Link></button>
        </div>
        <div>
            <button className="button red"><Link to="/contact/Customer">Contact | Customer</Link></button>
            <button className="button red"><Link to="/contact/Vendor">Contact | Vendor</Link></button>
        </div>
      </div>
     )
  }
export default App
Figure 1 : Passing url parameters in React JS
Figure 1 : Passing url parameters in React JS
Retrieving URL parameters with useParams

The React JS component can receive the URL parameter with the useParams hook. The code const {day} = useParams() deconstructs the params object and retrieves the day param.

import { useParams } from "react-router-dom";
const Home = () =>{
  const {day} = useParams();
  return(
    <div style={{padding: 30}}>
      <div className="comp">
        <h1>Home Component</h1>
        <p>Finally it's {day}</p>
      </div>
    </div>
  )
}
export default Home
Figure 2 : Accessing url parameters in React JS example 1
Figure 2 : Accessing url parameters in React JS example 1
The Contact component's const {day} = useParams() deconstructs the params object and retrieves the dept param.
import { useParams } from "react-router-dom"
const Contact = () => {
  const {dept} = useParams();
  return(
    <div style={{padding: 30}}>
      <div className="comp">
        <h1>Contact Component</h1>
        <p>Contacting : {dept}</p>
      </div>
    </div>
  )
 }
 export default Contact
Figure 3 : Accessing url parameters in React JS example 2
Figure 3 : Accessing url parameters in React JS example 2
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...