简体   繁体   中英

Conditional component render based on route in next js

is there a way to conditionally render components based on URL in next.js?

Edit:

as if now, I'm doing this:

const router = useRouter();

return (
  <>
    <SomeComponent />
    {router.pathname === "/somePath" && <RenderThis />}
  </>
)

I'm wondering if there's a better/cleaner way to this conditional render? like...

<>
  <SomeComponent />
  <Route path="/additionalUrl" component={RenderThis} />
</>

//or

<>
  <SomeComponent />
  <Route path="/additionalUrl">
     <RenderThis />
  </Route>
</>

The style of your second example is reminiscent of React Router, so I can see where you're coming from.

However, in Next.js, filesystem based routing is implemented, and routing is handled for you based on the filename in the /pages directory.

If you are handling many different query parameters in your URLs, Next.js handles that as well, using dynamic routes

From the above linked docs:

Consider the following page pages/post/[pid].js :

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { pid } = router.query

  return <p>Post: {pid}</p>
}

export default Post

Any route like /post/1 , /post/abc , etc. will be matched by pages/post/[pid].js . The matched path parameter will be sent as a query parameter to the page, and it will be merged with the other query parameters.

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