12

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Malay M
  • 1,659
  • 1
  • 14
  • 22

3 Answers3

24

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 
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
2

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;
Malay M
  • 1,659
  • 1
  • 14
  • 22
1

I used it this way:

export const UserInfo = (props) => {
   // assuming 1 is the default value
   const {userId = 1} = useParams()
  // ... other codes 
}
Hesam Marshal
  • 139
  • 1
  • 6