0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

初心者による初心者のためのGatsbyJS覚書4(パーツのコンポーネント化)

Last updated at Posted at 2021-08-09

この記事について

この記事はGatsbyJS初心者の新卒2年目が作成しています。
参考資料として書籍を使用していますが、筆者がビギナークラスのため読んでいて「?」となる部分や間違っている箇所もあるかと思います。
参考までに、そして間違えている箇所がありましたらご連絡いただけると嬉しいです。

Chapter3:パーツのコンポーネント化備忘録メモ

今回のチャプター文では特につまずきや迷いはありませんでした。
なので簡単にまとめて行きます。

ページを増やす準備

src/の配下にcomponentsディレクトリを用意してその下にheader.jsfooter.jsを用意する。

中身はこのような感じで準備。

import React from "react"

export default () => (
//要素を追加していく
)

が、gatsby developをするとこのような警告が出るのでコンポーネントの形を変えたほうが良さそう、、、

  6:1  warning  Anonymous arrow functions cause Fast Refresh to not preserve local component state.

       Please add a name to your function, for example:

       Before:
       export default () => {}

       After:
       const Named = () => {}
       export default Named;
  no-anonymous-exports-page-templates
  6:1  warning  Assign arrow function to a variable before exporting as module default

ということでindex.jsやコンポーネントファイル`も下記のような記法に変更。

import React from "react"

const ComponentName = () => (
  <div>

    //要素を追加

  </div>
)

export default ComponentName

index.js<header></header><footer></footer>部分をコピーして
準備したコンポーネントファイルに引っ越しをする。

どちらの要素も<header></header>のようにラップされている状態なのでdivなどで囲む必要はなし。

各コンポーネントファイルに引っ越しが完了したら、components/layout.jsを作成する。
これは作ったコンポーネントパーツをひとまとめに取り込むことのできる「まとめセット」ファイルとなる。
childrenはReactのプロパティでページごとの子要素を取り込める様になっている。

import React from "react"
import Header from "./header"
import Footer from "./footer"
import "./layout.css"

const Layout = ({ children }) => (
<div>
    <Header />

    {children}
    
    <Footer />
</div>
)

export default Layout

今まで使用していたsrc/style/style.cssを名前を変えてsrc/components/layout.cssとなるように移動させる。
また、今までgatsby-browser.jssrc/style/style.cssを取り込んでいたが、
グローバルCSSを利用しているので推奨の「サイトの基本となるコンポーネントから適用する方法」を
使用するためgatsby-browser.jsはファイルごと削除しておく。
gatsby-browser.jsでスタイルシートを取り込む方法は
Gatsbyにおけるスタイルの適用方法として挙げられる「CSS in JS」の方法に影響があるため。

あとは index.jslayout.jsを取り込み、
引っ越しを済ませた<header><footer>要素は削除し、
残りの要素を<Layout></Layout>で挟み込めば完成。

import Layout from "../components/layout" //追加

const IndexPage = () => (
<Layout>

  //残りの要素

</Layout>
)

export default IndexPage

今回はここまで。
次回はこれを使用しながらページを増やしていく予定です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?