简体   繁体   中英

NextJs Layout Login page?

I'm covering app js with layout. I have the sidebar on the left and my pages on the right. But what I want is that the sidebar should not appear on the login page, how can I edit it?

_app.js 在此处输入图像描述

Layout.js 在此处输入图像描述

you can add a condition with pathname to showing the component or not

something like this:

const router = useRouter():

return (
   ...
   {router.pathname !== '/login' && <Sidebar path={router.route} />}
   ...
)

If you have some pages that are protected and can be seen by logged in user than you would need Public and Protected Routes and you can show in your Public routes only

If this is not the case then solution mentioned by @kaveh karami is good

I'm thinking you should use Option 4 of the Persistent Layout Patterns article by Adam Wathan (the getLayout Pattern) to implement the layout and pass a prop to conditionally render the sidebar.

In this way, your Login / Register page controls the layout rendering

// Layout.js
export default function Layout({ showSidebar, children, ...rest }){
  return (
    ...
    {showSidebar && <Sidebar />}
    ...
  )
}

export function getLayout(page, props) {
    return <Layout {...props}>{page}</DefaultLayout>
}


// Login.js
import { getLayout as getDefaultLayout } from './Layout.js'

function Login(){
  return (
    ...
  )
}

Login.getLayout = page => getDefaultLayout(page, { showSidebar: true})

I would create a HOC(Higher-Order-Component) called WithSidebar:

import Main from '../../components/Main/Main';
import Sidebar from '../../components/Sidebar/Sidebar';
import classes from './WithSidebar.module.scss';

const WithSidebar = (Component) => {

    return props => (
        <div className={classes.WithSidebar}>
            <Sidebar />
            <Main className={classes.Container}>
                <Component {...props} />
            </Main>
        </div>
    );
};

export default WithSidebar;

And then export the pages that should include the sidebar like so:


import WithSidebar from '../hoc/WithSidebar/WithSidebar';

const MyPage = () => {

    return (...)
}

export default WithSidebar(MyPage)

I find this approach really cleaner than conditionally rendering based on the pathname.

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