Skip to main content

URL Params

To use URL params, react-router-dom provides a custom hook we can utilize. Check out this code:

File: src/App.js


import { BrowserRouter, Routes, Route } from "react-router-dom"
import Menu from "./views/Menu"
import Home from "./views/Home"
import Blog from "./views/Blog"
import Contact from "./views/Contact"
import Path from "./views/Path"

import NotFound from "./views/NotFound"


const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Menu />}>
<Route index element={<Home />} />
<Route path="/blog" element={<Blog />} />
<Route path="/contact" element={<Contact />} />
<Route path="/data/:slug/:id" element={ <Path /> } />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</BrowserRouter>
);

}

export default App

As you can see we reference the <Path> component on the slug: /data/:slug/:id where the semicolon indicates a variable. In Path.js we can destructure this from the hook:

File: src/views/Path.js

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

const Path = () => {

const { id, slug } = useParams()

return(
<div><h1>{ slug } : { id }</h1></div>
)
}

export default Path

And based upon this structure, we could fire a useEffect hook to fetch the data for that ID:

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

const Path = () => {

let { id, slug } = useParams()

useEffect( () => {
alert(`ID: ${id} SLUG: ${ slug }`)
}, [id])

return(
<div><h1>{ slug }: { id }</h1></div>
)
}

export default Path