Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get parameter value from url using React Router

I want to get the id value from this React Router:

<BrowserRouter basename="/api">
    <Switch>
        <Route path="/pm" exact component={PaymentMethod}/>
        <Route path="/pw" exact component={PaymentWeb}/>
        <Route path="/rg" exact component={Registrasi}/>
        <Route path="/bonus/:id" exact component={BonusScreen}/>
        <Route path="/hb" exact component={HistoryBonus}/>
    </Switch>
</BrowserRouter>

in my BonusScreen I tried to print the value by using this :

const userId = this.props.match.id;
console.log(this.userId);

from the browser I try to access the URL like this:

bonus/NGO628567652201

But it always returned undefined.
How can I fix this ?

like image 957
kurniawan26 Avatar asked Apr 05 '18 09:04

kurniawan26


People also ask

How do I get query params in react router?

To get the query parameter from a above url, we can use the useLocation() hook in react router v5. In the above code, we first imported the useLocation() hook from the react-router-dom package and invoked it inside the Items functional component then we parsed the query param data using the new URLSearchParams().

How do you query parameters in a URL?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.


1 Answers

In case of anyone having this problem. The correct would be:

const userId = this.props.match.params.id;

05/2020 UPDATE USING REACT ROUTER V4 AND HOOKS

import { useParams } from 'react-router-dom';

//Then inside your component
const { id } = useParams();
like image 183
Alcides Bezerra Avatar answered Sep 28 '22 10:09

Alcides Bezerra