Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router useParams hook returning empty object

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.

like image 671
Ashraf Slamang Avatar asked Apr 01 '20 14:04

Ashraf Slamang


People also ask

How do I use useparams () hook in react-router-Dom?

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.

How to access the parameters of the current route in react?

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.

How to access the param value inside a users component in react?

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.

What is the useparams () hook in the users function?

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.


1 Answers

I think you have problem because you used Router instead of Route.

like image 122
Kirill Skomarovskiy Avatar answered Nov 15 '22 21:11

Kirill Skomarovskiy