I'm having an issue with React Router not getting params using the useParams
hook. When going to the route /view/12345
(browser path includes basename /pending-nominations/view/12345
) the console.log()
logs an empty object here {}
where it should be displaying the id
eg. {id: 12345}
const SingleRecognition = (props) => {
let params = useParams();
console.log("SingleRecognition -> params", params)
return (
<div>
id:
</div>
);
}
function App() {
return (
<Provider store={store}>
<ThemeProvider theme={theme}>
<Router basename="/pending-nominations">
<PageNav/>
<Switch>
<Route path="/history">
<History/>
</Route>
<Router path="/view/:id">
<SingleRecognition/>
</Router>
<Route path="/">
<PendingRecognitions/>
</Route>
</Switch>
</Router>
</ThemeProvider>
</Provider>
);
}
Looking at the example https://reacttraining.com/react-router/web/api/Hooks/useparams this should work.
In the above code, we first imported the useParams () hook from the react-router-dom package. Inside the Users function, we invoked a useParams () hook that returns an object with key/value pairs where the key is id and value is whatever we passed after /users/ route in the browser.
ReactJS useParams Hook. In our React app sometimes we want to access the parameters of the current route in this case useParams hook comes into action. The react-router-dom package has useParams hooks that let you access the parameters of the current route.
Now, we can access the :id param value inside a Users component by using the useParams () hook. In the above code, we first imported the useParams () hook from the react-router-dom package.
Inside the Users function, we invoked a useParams () hook that returns an object with key/value pairs where the key is id and value is whatever we passed after /users/ route in the browser.
I think you have problem because you used Router
instead of Route
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With