Published on

メニューの表示をレスポンシブにしてみた

Authors

メニューにタグを追加してみたら、スマホで表示したときに hover がうまく動作しなかったのでレスポンシブで切り替わるようにしてみました。
色々調べてみたところ、gatsby-plugin-breakpoints というプラグインを使うと、簡単に画面サイズに合わせてブレークポイントを取得できそうです。
公式はこちら

まずはプラグインのインストール

npm i gatsby-plugin-breakpoints

プラグインを gatsby-config.js ファイルに入れます。

title=gatsby-config.js
module.exports = {
    plugins: ['gatsby-plugin-breakpoints'],
};

これで準備ができました。
スマホで閲覧したらメニューがハンバーガーに切り替わるようにします。
このサイトのメニューは layout.js で表示しているので、プラグインが使えるように import します。

title=layout.js
import { useBreakpoint } from 'gatsby-plugin-breakpoints'

そして、画面サイズでメニューが切り替わるようにします。

title=layout.js
import * as React from "react"
import { Link } from "gatsby"
import Menu from "../components/menu"
import MobileMenu from "../components/menuMobile"
import { useBreakpoint } from 'gatsby-plugin-breakpoints'
import * as layoutStyles from "./layout.module.scss"

const Layout = ({ location, title, children }) => {
  const breakPoints = useBreakpoint();
  const rootPath = `${__PATH_PREFIX__}/`
  const isRootPath = location.pathname === rootPath
  let header
  let footer
  let menu

    {/*ここでブレークポイントによって表示を切り替えています*/}
    if(breakPoints.sp) {
        menu = ( <MobileMenu right /> )
      }else{
        menu = ( <Menu /> )
    }

    if (isRootPath) {
      header = (
        <h1 className="main-heading">
          <Link to="/">{title}</Link>
          {menu}
        </h1>
      )
    } else {
      header = (
        <h1 className="main-heading">
        <Link className="header-link-home" to="/">
          {title}
        </Link>
        {menu}
        </h1>
      )
    footer = (
      <div className={layoutStyles.footerBackMain}>
          <Link to="/">back to home</Link>
        </div>
    )
    }

  return (
    <div className="global-wrapper" data-is-root-path={isRootPath}>
      <header className="global-header">{header}</header>

      <main>{children}</main>
      <footer>
        {footer}
        {<div className={layoutStyles.copyright}>
          © noine {new Date().getFullYear()}<Link to={"/privacypolicy"}>-privacy policy</Link>
        </div>}
      </footer>
    </div>
  )
}

export default Layout

全て貼り付けてしまいましたが、使ったところはここだけ

if (breakPoints.sp) {
  menu = <MobileMenu right />
} else {
  menu = <Menu />
}

便利!!

if で MobileMenu と Menu のモジュールを切り替えています。
MobileMenu の後ろの right はハンバーガーメニューのプラグインに props を渡しているのですが、機能していない。。。
props 受け取りの書き方が間違っていそうです。
…そのうち直します。