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
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
The React JS component can receive the URL parameter with the useParams hook.
The code
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
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