ChatGPT解决这个技术问题 Extra ChatGPT

Nested routes with react router v4 / v5

I am currently struggling with nesting routes using react router v4.

The closest example was the route config in the React-Router v4 Documentation.

I want to split my app in 2 different parts.

A frontend and an admin area.

I was thinking about something like this:

<Match pattern="/" component={Frontpage}>
  <Match pattern="/home" component={HomePage} />
  <Match pattern="/about" component={AboutPage} />
</Match>
<Match pattern="/admin" component={Backend}>
  <Match pattern="/home" component={Dashboard} />
  <Match pattern="/users" component={UserPage} />
</Match>
<Miss component={NotFoundPage} />

The frontend has a different layout and style than the admin area. So within the frontpage the route home, about and so one should be the child routes.

/home should be rendered into the Frontpage component and /admin/home should be rendered within the Backend component.

I tried some other variations but I always ended in not hitting /home or /admin/home.

Final solution:

This is the final solution I am using right now. This example also has a global error component like a traditional 404 page.

import React, { Component } from 'react';
import { Switch, Route, Redirect, Link } from 'react-router-dom';

const Home = () => <div><h1>Home</h1></div>;
const User = () => <div><h1>User</h1></div>;
const Error = () => <div><h1>Error</h1></div>

const Frontend = props => {
  console.log('Frontend');
  return (
    <div>
      <h2>Frontend</h2>
      <p><Link to="/">Root</Link></p>
      <p><Link to="/user">User</Link></p>
      <p><Link to="/admin">Backend</Link></p>
      <p><Link to="/the-route-is-swiggity-swoute">Swiggity swooty</Link></p>
      <Switch>
        <Route exact path='/' component={Home}/>
        <Route path='/user' component={User}/>
        <Redirect to={{
          state: { error: true }
        }} />
      </Switch>
      <footer>Bottom</footer>
    </div>
  );
}

const Backend = props => {
  console.log('Backend');
  return (
    <div>
      <h2>Backend</h2>
      <p><Link to="/admin">Root</Link></p>
      <p><Link to="/admin/user">User</Link></p>
      <p><Link to="/">Frontend</Link></p>
      <p><Link to="/admin/the-route-is-swiggity-swoute">Swiggity swooty</Link></p>
      <Switch>
        <Route exact path='/admin' component={Home}/>
        <Route path='/admin/user' component={User}/>
        <Redirect to={{
          state: { error: true }
        }} />
      </Switch>
      <footer>Bottom</footer>
    </div>
  );
}

class GlobalErrorSwitch extends Component {
  previousLocation = this.props.location

  componentWillUpdate(nextProps) {
    const { location } = this.props;

    if (nextProps.history.action !== 'POP'
      && (!location.state || !location.state.error)) {
        this.previousLocation = this.props.location
    };
  }

  render() {
    const { location } = this.props;
    const isError = !!(
      location.state &&
      location.state.error &&
      this.previousLocation !== location // not initial render
    )

    return (
      <div>
        {          
          isError
          ? <Route component={Error} />
          : <Switch location={isError ? this.previousLocation : location}>
              <Route path="/admin" component={Backend} />
              <Route path="/" component={Frontend} />
            </Switch>}
      </div>
    )
  }
}

class App extends Component {
  render() {
    return <Route component={GlobalErrorSwitch} />
  }
}

export default App;
Thank you for updating your question with the final answer! just a suggestion: maybe you could keep only the 4th listing and the first, since the other ones are using outdated versions of the api and are distracting from the answer
lol, I have no idea what format this date is: 08.05.2017 I suggest you use the universal ISO8601 format for dates if you don't want to confuse people. is 08 the month or day? ISO8601 = year.month.day hour.minute.second (progressively more granular)
Nice updated final solution, but I think you don't need the previousLocation logic.
what's the motivation for completely rewriting react router. It better be a good reason
It's the declarative approach. So you can set up your routings as you would use react components.

K
Karen Liu

In react-router-v4 you don't nest <Routes />. Instead, you put them inside another <Component />.

For instance

<Route path='/topics' component={Topics}>
  <Route path='/topics/:topicId' component={Topic} />
</Route>

should become

<Route path='/topics' component={Topics} />

with

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <Link to={`${match.url}/exampleTopicId`}>
      Example topic
    </Link>
    <Route path={`${match.path}/:topicId`} component={Topic}/>
  </div>
) 

Here is a basic example straight from the react-router documentation.


i'm able to implement from your link in basic example however when i type the url manually it doesnt work on my localhost server. but it does on your example. In the otherhand HashRouter work properly when i type the url manualy with #. Do you have any idea why on my localhost server the BrowserRouter not working when i type the url manually?
can you make Topics component into a class? and where is the 'match' parameter came in? in the render()?
Seems ridiculous you can't just to="exampleTopicId" with the ${match.url} being implicit.
You can have nested routes per docs reacttraining.com/react-router/web/example/route-config. This would allow for centralized route config as per the topic in the docs. Think how insane this would be to manage in a larger project if unavailable.
These are not nested routes, it's a one-level routing still using the render property of a Route which takes a functional component as an input, look more carefully, there is no nesting in the sense of react router < 4. RouteWithSubRoutes is a one-level list of routes that use pattern matching.
d
davnicwil

react-router v6

Update for 2022 - v6 has nested Route components that Just Work™.

This question is about v4/v5, but the best answer now is just use v6 if you can!

See example code in this blog post. If you can't upgrade just yet, however...

react-router v4 & v5

It's true that in order to nest Routes you need to place them in the child component of the Route.

However if you prefer a more inline syntax rather than breaking your Routes up across components, you can provide a functional component to the render prop of the Route you want to nest under.

<BrowserRouter>

  <Route path="/" component={Frontpage} exact />
  <Route path="/home" component={HomePage} />
  <Route path="/about" component={AboutPage} />

  <Route
    path="/admin"
    render={({ match: { url } }) => (
      <>
        <Route path={`${url}/`} component={Backend} exact />
        <Route path={`${url}/home`} component={Dashboard} />
        <Route path={`${url}/users`} component={UserPage} />
      </>
    )}
  />

</BrowserRouter>

If you're interested in why the render prop should be used, and not the component prop, it's because it stops the inline functional component from being remounted on every render. See the documentation for more detail.

Note the example wraps the nested Routes in a Fragment. Prior to React 16, you can use a container <div> instead.


Thank god the only solution that is sorta clear, mantainable and works as expected. I wish react router 3 nested routes were back.
this one perfect looks like angular route-outlet
You should use match.path, not match.url. The former is usually used in the Route path prop; the latter when you push a new route (e.g. Link to prop)
With the react-router v4/v5 example, when someone navigates to the /admin page, will it render the admin page or will they need to navigate to /admin/? Thanks!
Best and neatest solution in my opinion for nested routes
t
twharmon

Just wanted to mention react-router v4 changed radically since this question was posted/answed.

There is no <Match> component any more! <Switch>is to make sure only the first match is rendered. <Redirect> well .. redirects to another route. Use or leave out exact to either in- or exclude a partial match.

See the docs. They are great. https://reacttraining.com/react-router/

Here's an example I hope is useable to answer your question.

<Router>
  <div>
    <Redirect exact from='/' to='/front'/>
    <Route path="/" render={() => {
      return (
        <div>
          <h2>Home menu</h2>
          <Link to="/front">front</Link>
          <Link to="/back">back</Link>
        </div>
      );
    }} />          
    <Route path="/front" render={() => {
      return (
        <div>
        <h2>front menu</h2>
        <Link to="/front/help">help</Link>
        <Link to="/front/about">about</Link>
        </div>
      );
    }} />
    <Route exact path="/front/help" render={() => {
      return <h2>front help</h2>;
    }} />
    <Route exact path="/front/about" render={() => {
      return <h2>front about</h2>;
    }} />
    <Route path="/back" render={() => {
      return (
        <div>
        <h2>back menu</h2>
        <Link to="/back/help">help</Link>
        <Link to="/back/about">about</Link>
        </div>
      );
    }} />
    <Route exact path="/back/help" render={() => {
      return <h2>back help</h2>;
    }} />
    <Route exact path="/back/about" render={() => {
      return <h2>back about</h2>;
    }} />
  </div>
</Router>

Hope it helped, let me know. If this example is not answering your question well enough, tell me and I'll see if I can modify it.


There are no exact on Redirect reacttraining.com/react-router/web/api/Redirect That would be a lot cleaner than <Route exact path="/" render={() => <Redirect to="/path" />} /> that I am doing instead. At least it won't let me with TypeScript.
Do i understand correctly that there is no such thing as nested/sub routes (anymore)? do i need to duplicate the base route in all the routes? Doesn't react-router 4 provide any help for structuring routes in maintainable manner?
@Ville I'm astonished; did you find a better solution? I don't want to have routes all over the place, gosh
this will work but make sure you have the public path set to "/" in webpack config for the bundle.js, otherwise the nested routes wont work on page refresh.
a
asukiaaa

I succeeded in defining nested routes by wrapping with Switch and define nested route before than root route.

<BrowserRouter>
  <Switch>
    <Route path="/staffs/:id/edit" component={StaffEdit} />
    <Route path="/staffs/:id" component={StaffShow} />
    <Route path="/staffs" component={StaffIndex} />
  </Switch>
</BrowserRouter>

Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md


rearranging the order fixed my issue although I dont know if this will have any side effects. but working for now.. thanks :)
Please note that while this solution fits in certain circumstances, it won't work for the case where you are using nested routes to render hierarchical layout components, which is one of the nice things you could do with nested routes in v3.
m
mohRamadan

Using Hooks

The latest update with hooks is to use useRouteMatch.

Main routing component


export default function NestingExample() {
  return (
    <Router>
      <Switch>
       <Route path="/topics">
         <Topics />
       </Route>
     </Switch>
    </Router>
  );
}

Child component

function Topics() {
  // The `path` lets us build <Route> paths 
  // while the `url` lets us build relative links.

  let { path, url } = useRouteMatch();

  return (
    <div>
      <h2>Topics</h2>
      <h5>
        <Link to={`${url}/otherpath`}>/topics/otherpath/</Link>
      </h5>
      <ul>
        <li>
          <Link to={`${url}/topic1`}>/topics/topic1/</Link>
        </li>
        <li>
          <Link to={`${url}/topic2`}>/topics/topic2</Link>
        </li>
      </ul>

      // You can then use nested routing inside the child itself
      <Switch>
        <Route exact path={path}>
          <h3>Please select a topic.</h3>
        </Route>
        <Route path={`${path}/:topicId`}>
          <Topic />
        </Route>
        <Route path={`${path}/otherpath`>
          <OtherPath/>
        </Route>
      </Switch>
    </div>
  );
}


S
Sanjeev Shakya

Some thing like this.

import React from 'react'; import { BrowserRouter as Router, Route, NavLink, Switch, Link } from 'react-router-dom'; import '../assets/styles/App.css'; const Home = () =>

HOME

; const About = () =>

About

; const Help = () =>

Help

; const AdminHome = () =>

root

; const AdminAbout = () =>

Admin about

; const AdminHelp = () =>

Admin Help

; const AdminNavLinks = (props) => (

Admin Menu

Admin Home Admin Help Admin About Home {props.children}
); const NormalNavLinks = (props) => (

Normal Menu

Home Help About Admin {props.children}
); const App = () => (
); export default App;


D
Devlin Duldulao

A complete answer for React Router v6 or version 6 just in case needed.

import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";

/*Routes is used to be Switch*/
const Router = () => {

  return (
    <Routes>
      <Route path="/" element={<LandingPage />} />
      <Route path="games" element={<Games />} />
      <Route path="game-details/:id" element={<GameDetails />} />
      <Route path="dashboard" element={<Dashboard />}>
        <Route path="/" element={<DashboardDefaultContent />} />
        <Route path="inbox" element={<Inbox />} />
        <Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
        <Route path="*" element={<NotFound />} />
      </Route>
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";

const Dashboard = () => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      <Outlet />
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-6-demo


Could you please include DashboardSidebarNavigation in here too?
f
ford04

React Router v6

allows to use both nested routes (like in v3) and separate, splitted routes (v4, v5).

Nested Routes

Keep all routes in one place for small/medium size apps:

<Routes>
  <Route path="/" element={<Home />} >
    <Route path="user" element={<User />} /> 
    <Route path="dash" element={<Dashboard />} /> 
  </Route>
</Routes>

const App = () => { return ( // /js is start path of stack snippet } > } /> } /> ); } const Home = () => { const location = useLocation() return (

URL path: {location.pathname}

user dashboard

) } const User = () =>
User profile
const Dashboard = () =>
Dashboard
ReactDOM.render(, document.getElementById("root"));

Alternative: Define your routes as plain JavaScript objects via useRoutes.

Separate Routes

You can use separates routes to meet requirements of larger apps like code splitting:

// inside App.jsx:
<Routes>
  <Route path="/*" element={<Home />} />
</Routes>

// inside Home.jsx:
<Routes>
  <Route path="user" element={<User />} />
  <Route path="dash" element={<Dashboard />} />
</Routes>

const App = () => { return ( // /js is start path of stack snippet } /> ); } const Home = () => { const location = useLocation() return (

URL path: {location.pathname}

} /> } />

user dashboard

) } const User = () =>
User profile
const Dashboard = () =>
Dashboard
ReactDOM.render(, document.getElementById("root"));


i think Routes with Routeis old way, i like this approach, i used same way in AngularJS too, Thanks
A
Aniruddh Agarwal

You can try something like Routes.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import FrontPage from './FrontPage';
import Dashboard from './Dashboard';
import AboutPage from './AboutPage';
import Backend from './Backend';
import Homepage from './Homepage';
import UserPage from './UserPage';
class Routes extends Component {
    render() {
        return (
            <div>
                <Route exact path="/" component={FrontPage} />
                <Route exact path="/home" component={Homepage} />
                <Route exact path="/about" component={AboutPage} />
                <Route exact path="/admin" component={Backend} />
                <Route exact path="/admin/home" component={Dashboard} />
                <Route exact path="/users" component={UserPage} />    
            </div>
        )
    }
}

export default Routes

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Routes from './Routes';

class App extends Component {
  render() {
    return (
      <div className="App">
      <Router>
        <Routes/>
      </Router>
      </div>
    );
  }
}

export default App;

I think you can achieve the same from here also.


good point! I thought same way when started with React after Java Spring boot app development. the only thing that I'd change is 'div' to 'Switch' in Routes.js. And tbh, you can define all routes in App.js but wrap it outside in index.js file for example (create-react-app)
Yes, you are right! I have implemented this way that's why I am mentioning this method.
D
Devlin Duldulao

A complete answer for React Router v5.


const Router = () => {
  return (
    <Switch>
      <Route path={"/"} component={LandingPage} exact />
      <Route path={"/games"} component={Games} />
      <Route path={"/game-details/:id"} component={GameDetails} />
      <Route
        path={"/dashboard"}
        render={({ match: { path } }) => (
          <Dashboard>
            <Switch>
              <Route
                exact
                path={path + "/"}
                component={DashboardDefaultContent}
              />
              <Route path={`${path}/inbox`} component={Inbox} />
              <Route
                path={`${path}/settings-and-privacy`}
                component={SettingsAndPrivacy}
              />
              <Redirect exact from={path + "/*"} to={path} />
            </Switch>
          </Dashboard>
        )}
      />
      <Route path="/not-found" component={NotFound} />
      <Redirect exact from={"*"} to={"/not-found"} />
    </Switch>
  );
};

export default Router;
const Dashboard = ({ children }) => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      {children}
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-5-demo


s
seyed mohammad asghari

I prefer to use react function. This solution is short and more readable

const MainAppRoutes = () => (
    <Switch>
        <Route exact path='/' component={HomePage} />
        {AdminRoute()}                  
        {SampleRoute("/sample_admin")}  
    </Switch>
);

/*first implementation: without params*/
const AdminRoute = () => ([
    <Route path='/admin/home' component={AdminHome} />,
    <Route path='/admin/about' component={AdminAbout} />
]);

/*second implementation: with params*/
const SampleRoute = (main) => ([
    <Route path={`${main}`} component={MainPage} />,
    <Route path={`${main}/:id`} component={MainPage} />
]); 

s
sampath kumar

**This code worked for me with v6**

index.js

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />}>
          <Route path="login" element={<Login />} />
          <Route path="home" element={<Home />} />
        </Route>
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

App.js:

function App(props) {
  useEffect(() => {
    console.log('reloaded');
// Checking, if Parent component re-rendering or not *it should not be, in the sense of performance*, this code doesn't re-render parent component while loading children
  });
  return (
    <div className="App">
      <Link to="login">Login</Link>
      <Link to="home">Home</Link>
      <Outlet /> // This line is important, otherwise we will be shown with empty component
    </div>
  );
}

login.js:

const Login = () => {
    return (
        <div>
            Login Component
        </div>
    )
};

home.js:

const Home= () => {
    return (
        <div>
            Home Component
        </div>
    )
};

E
EVGENY GLUKHOV
interface IDefaultLayoutProps {
    children: React.ReactNode
}

const DefaultLayout: React.SFC<IDefaultLayoutProps> = ({children}) => {
    return (
        <div className="DefaultLayout">
            {children}
        </div>
    );
}


const LayoutRoute: React.SFC<IDefaultLayoutRouteProps & RouteProps> = ({component: Component, layout: Layout, ...rest}) => {
const handleRender = (matchProps: RouteComponentProps<{}, StaticContext>) => (
        <Layout>
            <Component {...matchProps} />
        </Layout>
    );

    return (
        <Route {...rest} render={handleRender}/>
    );
}

const ScreenRouter = () => (
    <BrowserRouter>
        <div>
            <Link to="/">Home</Link>
            <Link to="/counter">Counter</Link>
            <Switch>
                <LayoutRoute path="/" exact={true} layout={DefaultLayout} component={HomeScreen} />
                <LayoutRoute path="/counter" layout={DashboardLayout} component={CounterScreen} />
            </Switch>
        </div>
    </BrowserRouter>
);