Soumalya Bhattacharya
Soumalya Bhattacharya

Reputation: 662

How to catch the dynamic part of the URL in react router

I have this route which calls PriceWithId function

<Route path='/collections/:pId' component={PriceWithID} />

The function is like this

const PriceWithID = ({match}) =>
    {
        let test = Object.entries(match);
        let test2 = test.filter(([prop])=>(prop === 'params'));
        let test3 = test2[0][1];
        let test4 = Object.values(test3)[0]
        return(
          <Price image={IMGS.filter((i)=>(i.id === parseInt(test4,10)))[0]}/>
        );
    }

I know there is a nicer oneline way to achieve test4. The method I used came with trial and error. Can anyone tell me the nicer way so that I can replace test4 in parseInt with it

Upvotes: 0

Views: 199

Answers (2)

Soumalya Bhattacharya
Soumalya Bhattacharya

Reputation: 662

The previous answer can be improved upon this way:

const PriceWithID = ({match}) =>
    {
        return(
          <Price image={IMGS.filter((i)=>(i.id === parseInt(match.params.pId,10)))[0]}/>
        );
    }

But as the previous solution was correct I marked it as answer.

Upvotes: 0

kennysliding
kennysliding

Reputation: 2977

use this.props.match.params.pId

or with functional component

const PriceWithID = (props) =>
    {
        let pId = props.match.params.pId
        return(
          <Price image={IMGS.filter((i)=>(i.id === parseInt(pId))[0]}/>
        );
    }

Upvotes: 2

Related Questions