Pichi Wuana
Pichi Wuana

Reputation: 752

React route does not detect nesting routing and ids

I have some React routes that when I nest one route inside another, I need to repeat the route path.

To explain, for example:

<Route
        path="admin">
        <Switch>
            <Route
                path="admin/specific/:id"
                component={SpecificAdmin} />
            <Route
                exact
                path="admin"
                component={AdminPage}>
            </Route>
            <Route
                exact
                path="admin/edit/new"
                component={EditSpecificAdmin} />
        </Switch>
    </Route>

I want a page where I can see the list of items, one for adding a new one and another for looking, editing a specific item. So I thought about the paths edit/new and specific/1. So the routes do not detect when I write specific/1 (the specific id) and not either the admin nesting, so I need to write the admin in each one...

Upvotes: 0

Views: 75

Answers (2)

Thomas Bihan-Poudec
Thomas Bihan-Poudec

Reputation: 165

As Tareq aziz said, you can easily have intel in props.

You can create another router to pass easily new value:

// your original component
import AdminRouter from './Admin/Router';

export default () => {
  return (
    <Route path="admin">
     <AdminRouter />     
    </Route>
  );
}

// in ./Admin/Router.js
export default (props) => {
  return (
    <Switch>
        <Route 
            exact
            path={`${props.match.path}/specific/:id`}
            component={SpecificAdmin}
        />
        <Route 
            exact
            path={`${props.match.path}`}
            component={AdminPage}
        />
        <Route 
            exact
            path={`${props.match.path}/edit/new`}
            component={EditSpecificAdmin}
        />
    </Switch>
  );
}

I'm not sure though if the order of the routes are correct.

Upvotes: 1

tareq aziz
tareq aziz

Reputation: 777

I think you can get your current page's url from props using location.pathname or match.url. You can see my image. Then you may add your nested route after that. Hope it will help you

enter image description here

You may code your path like this way

path=`${this.props.location.pathname}/edit/new`

path=`${this.props.location.pathname}/specific/:id`

Upvotes: 1

Related Questions