LoginSignup
0
0

More than 3 years have passed since last update.

nextjsで複数のレイアウトをサーバー側(SSR)で特定し出力したい

Posted at

useStateを使う問題

https://nextjs.org/docs/advanced-features/custom-app
ページ全体に共通なレイアウトはcustom-appを使って設定できる、がuseStateなんかをして動的に変更すると一瞬DefaultLayoutが表示されて、その後にLayout2に切り替わるようなことになってしまう。

雑な例
import type { AppProps } from 'next/app'
...
...

function MyApp(props: AppProps) {
  const { Component, pageProps } = props
  const [layoutType, ...] = useState()
  ...
  ...

  const Layout = layoutType == ... ? Layout2 : DefaultLayout

  return(
    <>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </>
  )
}

export default MyApp

解決方法

AppPropsのrouter.routeを使う。


function MyApp(props: AppProps) {
  const { Component, pageProps, router: { route } } = props

  console.log("route", route) // => pages直下のパスが返ってくる  

このrouteのパスで、パス毎で表示に必要なLayoutを切り替えてやればクライアント側で動的に変わらない。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0