スマレジエンジニアyushiのブログ

スマレジエンジニアのブログ

【自作ブログ #8】Layout Componentを作成

自作ブログを作っています。

yushi-dev.hatenablog.com

技術スタック

  • TypeScript
  • React
  • Next.js
  • Styled Components
  • GitHub Pages

今回はLayout Componentを作成していきます。

目的

今後複数のページを追加していくわけですが、それらに共通する土台が存在します。
それをコンポーネントとして作成しておくことで、ページを作成を簡易にし、またデザインを統一することができます。

Layout ComponentとMainContainerという2つのコンポーネントを作成予定ですが、今回はLayout Componentを紹介していきます。

Layout Component

このコンポーネントは、すべての画面で共通化される想定をしています。

ここではHeader・Footerの表示をします。

(Layout.tsx)

const Layout = ({ children }: Props) => {
  return (
    <>
      <AppHeader />
      {children}
      <AppFooter />
    </>
  )
}

全ページ共通の想定なので、_app.tsxで配置します。

(_app.tsx)

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

これらの記述により、各ページで定義されるコンポーネントがAppHeader・AppFooterに上下に挟まれた形で配置されることになります。

AppHeader・AppFooter

AppHeader・AppFooterについて、今回は仮のものですが、定義していきます。

AppHeaderは下記のように定義しています。

(AppHeader.tsx)

const Header = styled.header`
  display: flex;
  align-items: center;
  height: 60px;
  padding: 0 ${commonCss.VERTICAL_PADDING};
`
const AppHeader = () => {
  return (
    <Header>
      <TopNav href="/" />
    </Header>
  )
}


(TopNav.tsx)

const A = styled.a`
  font-size: 1.8em;
  text-decoration: none;
`

const TopNav = ({ href }: Props) => {
  return <A href={href}>Blog</A>
}

AppFooterは下記のように定義しています。

(AppFooter.tsx)
const Footer = styled.footer`
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
`

const AppFooter = () => {
  return <Footer>©︎ 2022 NAME</Footer>
}

画面

ヘッダー(Blogのリンク)と、フッター(©︎ 2022 NAME)が表示されました。

あとがき

今回でヘッダー・フッターの共通記述ができました。

次回は、ページ本体部分の共通レイアウトを行なっていきます。