Gatsbyプロジェクトに styled-components を導入

インストール及び設定

公式ドキュメントに説明があります。

$ npm install gatsby-plugin-styled-components styled-components babel-plugin-styled-components
$ npm audit fix // 脆弱性が指摘された場合

gatsby-config.js には、次を追加するよう公式ドキュメントに書かれています。

module.exports = {
  plugins: [`gatsby-plugin-styled-components`],
}

実際には次のように1行追加することになったりします。

module.exports = {
  /**
   * Adding plugins to this array adds them to your Gatsby site.
   *
   * Gatsby has a rich ecosystem of plugins.
   * If you need any more you can search here: https://www.gatsbyjs.com/plugins/
   */
  plugins: [
    `gatsby-plugin-styled-components`,  <--- これを追加。
    {
      /**
       * First up is the WordPress source plugin that connects Gatsby
       * to your WordPress site.
       *
       * visit the plugin docs to learn more
       * https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-wordpress/README.md
       *
       */
      resolve: `gatsby-source-wordpress`,
      options: {
        // the only required plugin option for WordPress is the GraphQL url.
        url:
          `https://software.pitang1965.com/graphql`,
      },
    },

styled-componentsの使用

src\components\menu.js は前回は全角スペースでインデントを実装していました(汗)。

:
  return (
    <Animation {...props}>
      {data.allWpPage.edges.map(edge =>
        edge.node.status === 'publish' ? (
          <Link to={edge.node.uri} className="menu-item" key={edge.node.uri}>
            {edge.node.ancestors === null
              ? edge.node.title
              : ' ' + edge.node.title}
          </Link>
        ) : null
      )}
    </Animation>
  );

これをCSSを用いて、第1レベルは太字、第2レベルはインデントの上、少し小さなフォントサイズにしてみました。

:
import styled from 'styled-components';

const FirstLevel = styled.div`
  font-weight: bold;
`;

const SecondLevel = styled.div`
  font-size: 0.9em;
  margin-left: 1em;
`;
:
  return (
    <Animation {...props}>
      {data.allWpPage.edges.map(edge =>
        edge.node.status === 'publish' ? (
          <Link to={edge.node.uri} className="menu-item" key={edge.node.uri}>
            {edge.node.ancestors === null
              ? <FirstLevel>{edge.node.title}</FirstLevel>
              : <SecondLevel>{edge.node.title}</SecondLevel>}
          </Link>
        ) : null
      )}
    </Animation>
  );