2
1

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.

Gatsby.jsでGraphqlを使ってSEO対策する方法

Posted at

今回もGatsby.jsについての記事を書いていこうと思います。

今回の内容は、Graphqlからデータを取得しそれをメタタグとして、タイトルやらディスクリプションを設定してSEO対策しようって話です。

早速ですが説明していきます。

パッケージのインストール

まずは必要なパッケージをインストールしてみましょう。

npm i gatsby-plugin-react-helmet react-helmet

gatsby-configの設定

そしたら以下のようにgatsby-config.jsを設定。

module.exports = {
  plugins: [
    `gatsby-plugin-react-helmet`,
  ],
  siteMetadata: {
    title: "test",
    description: "テストサイトです"
  },
}

コンポーネントの作成

src\components\SEO.jsxを作成して以下のようにコンポーネントを作成。

import { graphql, useStaticQuery } from 'gatsby'
import React from 'react'
import { Helmet } from 'react-helmet'

const SEO = () => {
  const { site } = useStaticQuery(query)

  return (
    <>
      <Helmet>
        <html lang="ja" />
        <title>{site.siteMetadata.title}</title>
        <meta name="description" content={site.siteMetadata.description} />
      </Helmet>
    </>
  )
}

export const query = graphql`
  query {
    site {
      siteMetadata {
        title
        description
      }
    }
  }
`

export default SEO

あとはこれをLayoutの中身に呼び出してあげましょう!

Layout.js
import React from 'react'
import { SEO } from '@/SEO.js'

const Layout = (props) => {
  return (
    <>
      <SEO />
      // 省略
    </>
  )
}

export default Layout

これで各ページごとにタイトル、ディスクリプションの設定を行うことでSEO対策ができます!

意外と簡単。

Thank you for reading

参考記事

もう迷わないGatsby SEO メタタグの設定方法

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?