Search code examples
reactjsreact-routerreact-router-dom

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.


Solution

  • 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 
    }