Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional render classes based on url in Next.js

Tags:

next.js

I'm trying to show different navigations based on if it is the "Homepage" or if it is a page that contains "docs" (e.g. docs/1, docs/2, docs/3) in its URL. I'm just getting blanks on the "docs"-case - it feels like I am missing something here?

Here's my code so far:

const router = useRouter()
const path = router?.asPath

if (path === '/docs/') {
  return (
    <>
      <Head>
        <title>{pageTitle}</title>
        {description && <meta name="description" content={description} />}
      </Head>
      <Layout
        navigation={navigation1}
        title={title}
        tableOfContents={tableOfContents}
      >
        <Component {...pageProps} />
      </Layout>
    </>
  )
}
if (path === '/') {
  return (
    <>
      <Head>
        <title>{pageTitle}</title>
        {description && <meta name="description" content={description} />}
      </Head>
      <Layout
        navigation={navigation}
        title={title}
        tableOfContents={tableOfContents}
      >
        <Component {...pageProps} />
      </Layout>
    </>
  )
}
like image 511
tom_2543 Avatar asked Oct 26 '25 05:10

tom_2543


1 Answers

NextJS has a built-in route system. You can just create a docs.js file in the pages folder. You can either create different navigations directly in /pages/docs.js or a dynamic component for it.

Here is more about routing https://nextjs.org/docs/routing/introduction

Hope this answers your question :)

like image 62
William Avatar answered Oct 29 '25 07:10

William



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!