I am using react functional component with react router v5 . I am using useParam function to fetch a param. How can I set default value of the param when it is not available or undefined.
My router code
<Switch>
// ....
// ....
<Route path="/users/:userId?" component={UserInfo} />
// ....
</Switch>
My component code
export const UserInfo = (props) => {
const {userId} = useParams()
// ... other codes
}
I am getting undefined
when calling http://localhost:3000/users/.
Any idea will be helpful.
If you don't have another route in your Switch
that matches "/users", you can just provide a fallback value for the destructured params object for the "/users/:userId" path.
export const UserInfo = (props) => {
const { userId = /* fallback value */ } = useParams();
// ... other codes
}
Instead of using useParams()
function in your router you can use props.match
and check the condition.
Instead
const {userId} = useParams()
Use
// assuming 0 is the default value
const userId = props.match?.userId || 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With