0

When I use React-Router the old-fashioned way, with a simple component={MyComponent} in my Switch Route, I can get its URL param with props.match.params. This works fine:

Container:

<Switch>
  <Route path="/newAgreement/:type" component={NewAgreement} /> 
</Switch>

NewAgreement:

export default function NewAgreement(props) {
    return (
        <div>
           TYPE: {props.match.params.type} <-- THIS WORKS
        </div>
    );
}

The modern React-Router allows you to pass custom properties in a Route block, <Route>..</Route>, which wasn't possible with the old method. I have custom properties I need to pass, so my Switch Route looks like

<Switch>
    <Route path="/newAgreement/:type">
       <NewAgreement userInfo="someCustomProperty" />    
    </Route>
</Switch>  

The new method works when I don't specify any : URL params, it passes my properties as it should. But now, with the new block method and an : URL param, it started breaking with the error:

TypeError: Cannot read property 'params' of undefined

So how can I both pass custom properties within a <Route>..</Route> block to my component, and obtain :... URL params?

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • Does this answerr your question: https://stackoverflow.com/questions/45898789/react-router-pass-param-to-component/51791300? – T J Apr 27 '21 at 20:31

1 Answers1

1

In the module where you declared the NewAgreement component do this;

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


const NewAgreement = () => {
   const params = useParams();
   console.log(params.id)

   return (
    <>
    ...
    </>
   )
}

You can find more information about it on the documentation

Tolumide
  • 944
  • 9
  • 11