【中止】Gatsbyメモ
もうGatsbyは使っていません。今はAstroがアツイ。
jsonで指定された画像の表示方法
ポイント
jsonでURLを指定すると"File" Typeになる(自動的に)
"File" typeを画像として表示するには2段階の変換が必要
1. GraphQLで変換(そもそも直でURLを取ろうとするとエラーになる)
2. getImageで変換
3. GatsbyImageのimageパラメータに指定
サンプル
code:json
{
"thumb" : "../images/sample.png"
}
code:js
import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
export default function Home() {
const data = useStaticQuery(graphql`{
allDownloadsJson {
edges {
node {
thumb {
childImageSharp {
gatsbyImageData(width: 200)
}
}
}
}
}
}`)
const downloadItems = data.allDownloadsJson.edges
const image = getImage(downloadItems.thumb)
return (
<GatsbyImage image={image} width="200" alt="title" />
)
}
GraphQLクエリ'edges.node.data'と'nodes.data'の違い
ご覧のとおり、まったく違いはありません。edges.mapはnodesへのショートカットと考えることができます。これにより、graphql によって返されるデータを使用するときに、入力する手間が少し省けます。
エッジのクエリが役立つ場合がいくつかあります。たとえば、allMarkdownRemarkクエリにedgesは、合計投稿数などの役立つ情報が含まれる場合があります。
ページコンポーネントでのみ使えるqueryとは?
ページコンポーネントはdataというpropsでGraphQLクエリの結果を得ることができます。
code:jsx
export default function TopPage({ data }) {
<div>
{data.site....}
</div>
}
export const query = graphql`query {
site {
...
}
}
page queryとStaticQuery、useStaticQueryの違いは、StaticQuery、useStaticQueryがあらゆるコンポーネントで使えるのに対し、page queryはページコンポーネントのみで使えるというほかに、クエリに変数を使うことができるというメリットがあります。
Styleの適用順
1. gatsby-node.js
2. typography.js
3. gatsby-browser.js
4. component.module.css
gatsby-node内でcssをimportすると、その後のページ全体に影響が及んでしまう
typographyでoverrideしたスタイルはその後のgatsby-browserで読み込んだbootstrapに上書きされてしまう
gatsby-browserでbootstrapを読み込んだ後にサイト共通のcssを用意すれば良い
code:js
import "bootstrap/dist/css/bootstrap.min.css"
import "bootstrap/dist/js/bootstrap.min.js"
import "@popperjs/core/dist/umd/popper.min.js"
import "./src/style/common.sass"
cssモジュールの例
code:js
import styles from "some.module.css"
...
export default function SomePage ({ data }) {
return (
<div>
<h1 id={styles.title}>title</h1>
</div>
)
}
スタイルオブジェクトとしてimportしてメンバからclassNameを取得して使用する。つまり面倒くさい
CSSモジュールではidとかタグ名直指定はよくわからないことになるので使わないほうがいい