简体   繁体   中英

Next js parent route component for children components

Let's imagine we have the admin module that has a few pages customize , settings , account . Each of these pages should have some common layout for ex. sidebar .

In the case of a standard React app I would do the next thing to implement this part of the app.

I'd create the Parent route - admin and would create the parent Component that would contain a Sidebar and an entry point for children routes. Each child routed would have its own component and the parent will render the Sidebar and an Active Child component together. A very cool benefit of this approach - the Sidebar will be rendered only once while children will be dynamically changing during the user interaction.

A small example:

    const Customize = () => <div><h1>Customize</h1></div>;
    const Settings = () => <div><h1>Settings</h1></div>;
    const Account = () => <div><h1>Account</h1></div>

    const Sidebar = () => (
       <h2>Frontend</h2>
       <p><Link to="/admin">Admin</Link></p>
       <p><Link to="/admin/customize">Customize</Link></p>
       <p><Link to="/admin/settings">Settings</Link></p>
       <p><Link to="/admin/account">Account</Link></p>
    );
    
    const Admin= props => {
      return (
        <div>
          <Sidebar  />
          <Switch>
            <Route path='/user' component={Customize}/>
            <Route path='/user' component={Settings}/>
            <Route path='/user' component={Account}/>
          </Switch>
          <footer>Bottom</footer>
        </div>
      );
    }

But how can we do it in the case of Next.js? Based on their docs we need to use the File structure pattern. Eg. create an Admin page in the pages folder and put Account, Customize, Settings into this folder. To share some layout we can use the global _app , _document templates but they are global for the whole app.

How can I create the Parent route entry component that should keep Sidebar for all its children?

I don't want to re-render this Sidebar during the route changes because it isn't good regarding UX

Thanks for any info!

You can create the Layout component with the Sidebar .

Your pages folder structure gonna look like this:

pages
  -customize
  -settings
  -account

and every of this pages will be wrapped by the Layout component like:

const Customize = () => (
  <Layout>
    [page content]
  </Layout>
)

and the Layout itself looks like:

const Layout = ({ children }) => (
  <>
    <Sidebar />
    {children}
  </>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM