Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React route params with default value

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.

like image 405
Malay M Avatar asked Dec 14 '22 07:12

Malay M


2 Answers

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 
}
like image 157
Drew Reese Avatar answered Dec 24 '22 10:12

Drew Reese


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;
like image 22
Malay M Avatar answered Dec 24 '22 08:12

Malay M