I am using "react-router": "^5.1.2",
and there is a component called CarJourney for which i have created a path like
path: ‘/seguro-carro/simulacao/:journeyId?/:userId?’,
so as you can see journeyId and userId are optional parameters defined here but i came accros a scenario where i have to get these parameters and hit a different api with these
So, for example if my route contains
/seguro-carro/simulacao/ba6e7ae5-adb6-4722-87df-4f414c575bbb/abcdef
i can use useParams query like
const params = useParams() console.log(params) to get both these parameters which gives journeyId='ba6e7ae5-adb6-4722-87df-4f414c575bbb' and userId="abcdef"
but if my route contains only userId and not journeyId like
/seguro-carro/simulacao/abcdef console.log(params) gives me journeyId="abcdef and userId=undefined
Is there any way i could fix this issue ? In this case journeyId should be undefined and userId should abcdef.
Thanks !
Advertisement
Answer
You can likely provide two paths for matching. List the more specific path first. If a path with two params is used then the more specific path is used and both parameters are assigned, and if a path with only the one is used, the less specific path assigning the parameter to userId
is used. Don’t use optional parameters.
Example:
<Route path={[ '/seguro-carro/simulacao/:journeyId/:userId', '/seguro-carro/simulacao/:userId' ]} ... other props />