使用Next.js在某些页面上防止侧边栏出现

huangapple go评论72阅读模式
英文:

Prevent Sidebar from appearing in some page using Next.js

问题

login.jsx 文件中有一个小问题,我不希望在 login.jsx 页面上出现侧边栏,但我希望在所有其他页面上都出现。是否可以在其中添加某种条件?

_app.js 文件中引发问题的部分如下:

import '../styles/globals.css';
import Sidebar from '../components/Sidebar';

function MyApp({ Component, pageProps }) {
  return (
    <Sidebar>
      <Component {...pageProps} />
    </Sidebar>
  );
}

export default MyApp;

这是 Sidebar.jsx 组件的内容:

import React from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { RxSketchLogo, RxDashboard, RxPerson } from 'react-icons/rx';
import { FiSettings } from 'react-icons/fi';
import { HiOutlineShoppingBag } from 'react-icons/hi';
import { BiPackage } from 'react-icons/bi';

const Sidebar = ({ children }) => {
  return (
    <div className='flex'>
      <div className='fixed w-20 h-screen p-4 bg-white border-r-[1px] flex flex-col justify-between'>
        <div className='flex flex-col items-center'>
          <Link href='/'>
            <div className='bg-blue-800 text-white p-3 rounded-lg inline-block'>
              <RxSketchLogo size={20} />
            </div>
          </Link>
          <span className='border-b-[1px] border-gray-200 w-full p-2'>
            <Link href='/'>
              <div className='bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block'>
                <RxDashboard size={20} />
              </div>
            </Link>
            <Link href='/customers'>
              <div className='bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block'>
                <RxPerson size={20} />
              </div>
            </Link>
            <Link href='/orders'>
              <div className='bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block'>
                <HiOutlineShoppingBag size={20} />
              </div>
            </Link>
            <Link href='/products'>
              <div className='bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block'>
                <BiPackage size={20} />
              </div>
            </Link>
            <Link href='/'>
              <div className='bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block'>
                <FiSettings size={20} />
              </div>
            </Link>
          </span>
        </div>
      </div>
      <main className='ml-20 w-full'>{children}</main>
    </div>
  );
};

export default Sidebar;

要解决问题,你可以在 _app.js 中根据条件来决定是否呈现侧边栏。例如,你可以使用路由信息来检测当前页面是否为 "login",如果是,则不呈现侧边栏,否则呈现侧边栏。以下是示例代码:

import '../styles/globals.css';
import Sidebar from '../components/Sidebar';
import { useRouter } from 'next/router';

function MyApp({ Component, pageProps }) {
  const router = useRouter();

  // 根据当前页面的路由判断是否显示侧边栏
  const isLoginPage = router.pathname === '/login';

  return (
    {isLoginPage ? (
      <Component {...pageProps} />
    ) : (
      <Sidebar>
        <Component {...pageProps} />
      </Sidebar>
    )}
  );
}

export default MyApp;

这将根据当前页面的路由来决定是否在登录页面显示侧边栏。

英文:

I'm working on an application, and I have a minor issue with it. I have a sidebar appearing for my login.jsx page when I don't want it to appear for that specific page, though I want it to appear on all other pages. Is there some sort of conditional I can put in it?

login.jsx:

import React from &quot;react&quot;;
import TextField from &quot;@material-ui/core/TextField&quot;;
import Container from &quot;@material-ui/core/Container&quot;;
import Button from &quot;@material-ui/core/Button&quot;;
import { useForm } from &quot;react-hook-form&quot;;
import { Magic } from &quot;magic-sdk&quot;;
import Router from &quot;next/Router&quot;;
export default function LoginPage() {
const {
register, 
handleSubmit, 
formState: { errors },
} = useForm();
const onSubmit = async ({email}) =&gt; 
{
console.log(email);
const magic = new Magic(process.env.NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY);
const didToken = await magic.auth.loginWithMagicLink({email})
console.log(didToken)
const res = await fetch(&quot;/api/login&quot;, {
method: &quot;POST&quot;,
headers: {
&quot;Content-Type&quot;: &quot;application/json&quot;,
Authorization: &quot;Bearer &quot; + didToken,
}, 
body: JSON.stringify({ email }),
});
if(res.status === 200) {
// Redirect
Router.push(&quot;/&quot;);
} else {
// Display an error
}
};
return (
&lt;Container maxWidth=&quot;xs&quot;&gt;
&lt;form onSubmit={handleSubmit(onSubmit)}&gt;
&lt;h1&gt;Hello and Welcome to the Enterprise Dashboard.&lt;/h1&gt;
&lt;TextField 
variant=&quot;outlined&quot; 
label=&quot;email&quot; 
fullWidth autoComplete=&quot;email&quot; 
autoFocus
{...register(&quot;email&quot;, {required: &quot;Required field&quot;, pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: &quot;Invalid email address&quot;,
}})}
error={!!errors?.email}
helperText = {errors?.email ? errors.email.message : null}
/&gt;
&lt;Button type =&quot;submit&quot; variant= &quot;contained&quot; color=&quot;primary&quot; fullWidth&gt;
Login/Sign Up
&lt;/Button&gt;
&lt;/form&gt;
&lt;/Container&gt;
)
}

And this is the part that's giving the issues. My _app.js:

import &#39;../styles/globals.css&#39;
import Sidebar from &#39;../components/Sidebar&#39;;
function MyApp({ Component, pageProps }) {
return (
&lt;Sidebar&gt;
&lt;Component {...pageProps} /&gt;
&lt;/Sidebar&gt;
);
}
export default MyApp

Here's my Sidebar.jsx component

import React from &#39;react&#39;;
import Link from &#39;next/link&#39;;
import Image from &#39;next/image&#39;;
import {RxSketchLogo, RxDashboard, RxPerson} from &#39;react-icons/rx&#39;
import {FiSettings} from &#39;react-icons/fi&#39;;
import {HiOutlineShoppingBag} from &#39;react-icons/hi&#39;;
import {BiPackage} from &#39;react-icons/bi&#39;;
const Sidebar = ({children}) =&gt; {
return (
&lt;div className=&#39;flex&#39;&gt;
&lt;div className=&#39;fixed w-20 h-screen p-4 bg-white border-r-[1px] flex flex-col justify-between&#39;&gt;
&lt;div className=&#39;flex flex-col items-center&#39;&gt;
&lt;Link href=&#39;/&#39;&gt;
&lt;div className=&#39;bg-blue-800 text-white p-3 rounded-lg inline-block&#39;&gt;
&lt;RxSketchLogo size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;span className=&#39;border-b-[1px] border-gray-200 w-full p-2&#39;&gt;
&lt;Link href=&#39;/&#39;&gt;
&lt;div className=&#39;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&#39;&gt;
&lt;RxDashboard size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;Link href=&#39;/customers&#39;&gt;
&lt;div className=&#39;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&#39;&gt;
&lt;RxPerson size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;Link href=&#39;/orders&#39;&gt;
&lt;div className=&#39;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&#39;&gt;
&lt;HiOutlineShoppingBag size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;Link href=&#39;/products&#39;&gt;
&lt;div className=&#39;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&#39;&gt;
&lt;BiPackage size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;Link href=&#39;/&#39;&gt;
&lt;div className=&#39;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&#39;&gt;
&lt;FiSettings size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;main className=&#39;ml-20 w-full&#39;&gt;{children}&lt;/main&gt;
&lt;/div&gt;
)
}
export default Sidebar

I tried putting the Sidebar in different places in different files, but then unfortunately the formatting ended up being off.

答案1

得分: 1

 `Sidebar` 组件中你可以使用 [`useRouter`][1] 和一个 `if` 语句类似于这样

```react
import { useRouter } from "next/router";

export default function Sidebar({ children }) {
  const { pathname } = useRouter();

  // 如果路径是 "/login",则渲染页面时不包含侧边栏
  if (pathname === "/login") {
    return children;
  }

  // 否则渲染页面时包含侧边栏
  return <div>Sidebar {children}</div>;
}

在你的特定情况下,可以这样做:

import { useRouter } from "next/router";

const Sidebar = ({ children }) => {
  const { pathname } = useRouter();
  return (
    <div className="flex">
      {pathname !== "/login" && (
        <div className="fixed w-20 h-screen p-4 bg-white border-r-[1px] flex flex-col justify-between">
          <div className="flex flex-col items-center">
            <Link href="/">
              <div className="bg-blue-800 text-white p-3 rounded-lg inline-block">
                <RxSketchLogo size={20} />
              </div>
            </Link>
            <span className="border-b-[1px] border-gray-200 w-full p-2">
              <Link href="/">
                <div className="bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block">
                  <RxDashboard size={20} />
                </div>
              </Link>
              <Link href="/customers">
                <div className="bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block">
                  <RxPerson size={20} />
                </div>
              </Link>
              <Link href="/orders">
                <div className="bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block">
                  <HiOutlineShoppingBag size={20} />
                </div>
              </Link>
              <Link href="/products">
                <div className="bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block">
                  <BiPackage size={20} />
                </div>
              </Link>
              <Link href="/">
                <div className="bg-gray-100 hover-bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block">
                  <FiSettings size={20} />
                </div>
              </Link>
            </span>
          </div>
        </div>
      )}
      <main className="ml-20 w-full">{children}</main>
    </div>
  );
};
export default Sidebar;

<details>
<summary>英文:</summary>
Inside the `Sidebar` component, you could use [`useRouter`][1] with an `if` statement, something like this:
```react
import { useRouter } from &quot;next/router&quot;;
export default function Sidebar({ children }) {
const { pathname } = useRouter();
// render the page without the sidebar
if (pathname === &quot;/login&quot;) {
return children;
}
// render the page with the sidebar
return &lt;div&gt;Sidebar {children}&lt;/div&gt;;
}

In your specific case, it could be done like this:

import { useRouter } from &quot;next/router&quot;;
const Sidebar = ({ children }) =&gt; {
const { pathname } = useRouter();
return (
&lt;div className=&quot;flex&quot;&gt;
{pathname !== &quot;/login&quot; &amp;&amp; (
&lt;div className=&quot;fixed w-20 h-screen p-4 bg-white border-r-[1px] flex flex-col justify-between&quot;&gt;
&lt;div className=&quot;flex flex-col items-center&quot;&gt;
&lt;Link href=&quot;/&quot;&gt;
&lt;div className=&quot;bg-blue-800 text-white p-3 rounded-lg inline-block&quot;&gt;
&lt;RxSketchLogo size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;span className=&quot;border-b-[1px] border-gray-200 w-full p-2&quot;&gt;
&lt;Link href=&quot;/&quot;&gt;
&lt;div className=&quot;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&quot;&gt;
&lt;RxDashboard size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;Link href=&quot;/customers&quot;&gt;
&lt;div className=&quot;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&quot;&gt;
&lt;RxPerson size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;Link href=&quot;/orders&quot;&gt;
&lt;div className=&quot;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&quot;&gt;
&lt;HiOutlineShoppingBag size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;Link href=&quot;/products&quot;&gt;
&lt;div className=&quot;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&quot;&gt;
&lt;BiPackage size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;Link href=&quot;/&quot;&gt;
&lt;div className=&quot;bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block&quot;&gt;
&lt;FiSettings size={20} /&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;/div&gt;
)}
&lt;main className=&quot;ml-20 w-full&quot;&gt;{children}&lt;/main&gt;
&lt;/div&gt;
);
};
export default Sidebar;

huangapple
  • 本文由 发表于 2023年3月7日 07:42:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定