Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

reactjs - Show a navigation component on all routes except the root

I need to show a main navigation on all routes except the root route. If I was going to show on all routes I would do it like this:

class App extends Component {
    render() {
        return (
            <Container className="App" maxWidth="lg">
                <Grid className="app-container">
                    <MainNav /> 
                    <Switch>
                        <Route exact path="/" component={Home} />
                        <Route
                            exact
                            path="/some-other-route"
                            component={SomeOtherComponent}
                        />
                        ...
                    </Switch>
                </Grid>
            </Container>
        );
    }
}

I could make a wrapper component for all the other routes and put it there, but any solution I can think of to accomplish this just seems wrong and there's probably a better way. Is there a better way?

question from:https://stackoverflow.com/questions/65838520/show-a-navigation-component-on-all-routes-except-the-root

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe you can use this code.

The below code is inspired by nextjs page routing. You just add your routes on ~/pages/ and it imports them dynamically.

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

function DynamicRoutes() {
  return (
    <BrowserRouter>
      <Switch>
        <Route
          path="/"
          render={({ history, location, match })=>{
            const Page = React.lazy(()=>{
              return import('./pages'+location.pathname).catch((e) => {
                if (/not find module/.test(e.message)) {
                  return import("./pages/NotFound");
                }
                if (/Loading chunk d+ failed/.test(e.message)) {
                  window.location.reload();
                  return;
                }
                throw e;
              })
            });
            return (
              <React.Suspense fallback ={<div>Loading...</div>}>
                <Page />
              </React.Suspense>
            )

          }}
        />
      </Switch>
    </BrowserRouter>
  )
}
export default DynamicRoutes;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...