React-router: [v6] Hook for the current outlet route

Created on 4 Jul 2020  路  3Comments  路  Source: ReactTraining/react-router

I wanted to make route transitions, so I figured I had to get the Route path, them I made a hook to do so, here is how I made:

import React from 'react';
import { useOutlet, useNavigate } from 'react-router-dom';

export const useRoute = (nullFallback: string): { route: string | undefined; outlet: React.ReactElement | null } => {
    const outlet = useOutlet();
    const navigate = useNavigate();

    React.useEffect(() => {
        if (outlet === null) {
            navigate(nullFallback);
        }
    }, [outlet, nullFallback]);

    const route = React.useMemo(() => {
        const key = outlet?.props?.children?.props?.path;

        if (key) {
            return key;
        }
    }, [outlet]);

    return { route, outlet };
};

So my final question is if there is a better way to do it? And if there is, how? Thanks!

Most helpful comment

Previously for such cases I utilized something like <Route path="parent/:current" /> but with new fancy nested architecture it just does not work.

This case is actually very common, imagine we have tabs
| Zebras | Lions | Monkeys |
|-|-|-|
| /animals/1 | /animals/2 | /animals/3|

| Tab content inside a Route using nested :id |
|-|

And you want to restrict paths to only available tabs. While generating tabs and routes themselves based on some dictionary is easy, there is a problem with receiving a current value to mark a selected tab for example like this when current path is /animals/2 or for the subpath just 2

| Zebras | _Lions_ | Monkeys |
|-|-|-|
| /animals/1 | /animals/2 | /animals/3|

All 3 comments

Previously for such cases I utilized something like <Route path="parent/:current" /> but with new fancy nested architecture it just does not work.

This case is actually very common, imagine we have tabs
| Zebras | Lions | Monkeys |
|-|-|-|
| /animals/1 | /animals/2 | /animals/3|

| Tab content inside a Route using nested :id |
|-|

And you want to restrict paths to only available tabs. While generating tabs and routes themselves based on some dictionary is easy, there is a problem with receiving a current value to mark a selected tab for example like this when current path is /animals/2 or for the subpath just 2

| Zebras | _Lions_ | Monkeys |
|-|-|-|
| /animals/1 | /animals/2 | /animals/3|

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
You can add the fresh label to prevent me from taking any action.

Bump

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sarbbottam picture sarbbottam  路  3Comments

stnwk picture stnwk  路  3Comments

misterwilliam picture misterwilliam  路  3Comments

imWildCat picture imWildCat  路  3Comments

Waquo picture Waquo  路  3Comments