LoginSignup
8
5

More than 3 years have passed since last update.

gatsby.jsでAPIを使わずにインスタグラムの写真を表示する方法

Last updated at Posted at 2020-04-13

概念

gatsbyのブログなどで自分のインスタの写真を表示したくて、Instagram Graph APIはややこしすぎて、結局諦めてしまうことが多いと思います。
この記事でgatsby-source-instagramというプラグインを使って、表示したいプロフィールをユーザーネームで指定して写真を表示する簡単な方法を紹介します。
インスタグラムの写真を導入する段階で立ち上げているgatsby.jsが必要になりますので、それを準備してください。

(EDIT 29.09.2020): gatsby-source-instagramのプラグインで「ハッシュタグで絞り」と「ユーザーネーム絞り」という機能はなくなりました。詳しくはプラグインのページを見てください。

プロジェクトフォルダー内容

プロジェクトフォルダーは以下のうようになります。

 - src
    -- components
        --- instagram.js
        --- layout.js
        …
    -- hooks
        --- use-instagram.js
        …
    -- pages
        --- index.js
        --- about.js
        …
- gatsby-config.js
- gatsby-node.js
- package.json
…

必要なプラグインと依存をインストール

まず以下のプラグインをインストールしていきます。

プラグインの一覧

  1. gatsby-source-filesystem ※ gatsbyにデータをコーピするため
  2. gatsby-transformer-sharp ※ 画像のリサイズ
  3. gatsby-plugin-sharp ※ max-width, max-heightを使えるため
  4. gatsby-image ※ 画像ローディング
  5. gatsby-source-instagram ※ インスタグラム連携

ターミナルでnpmを使ってプラグインを一気にインストールします。

terminal
npm install gatsby-source-filesystem gatsby-transformer-sharp gatsby-plugin-sharp gatsby-image gatsby-source-instagram --save

gatsby-config.jsを書く

インストールしたプラグインをgatsby-config.jsで設定します。
gatsby-source-instagramのusernameのところにユーザーIDを入力します。

gatsby-config.js

module.exports = {
  plugins: [
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: 'images',
      }
    },
    {
      resolve: 'gatsby-source-instagram',
      options: {
        username: '//インスタのユーザーID'
      }
    }
  ],
}

ユーザーIDを調べるために、載せたいインスタグラムのプロフィールページで右クリックして、「ページのソースを表示」をクリックします。ソースで「profilePage_」を探して、その右にある番号をusernameに入力します。例えば、このページのユーザーIDを探したら、「profilePage_25573873494」が出るので、IDは25573873494になります。

use-instagram.jsを書く

次はインスタグラムのhooks(hooks/use-instagram.js)を作成して、写真をqueryで取得します。
limit:12のところに写真の数を設定できます。(上限は最近の12写真まで)
fluid(maxWidth: 120 maxHeight: 120)のところに写真のサイズを設定できます。pxになります。

use-instagram.js
import { graphql, useStaticQuery } from 'gatsby';

const useInstagram = () => {
    const data = useStaticQuery(graphql`
    query {
        allInstaNode(limit: 12) {
            nodes {
              id
              caption
              username
              localFile {
                childImageSharp {
                  fluid(maxWidth: 120, maxHeight: 120) {
                    ...GatsbyImageSharpFluid
                  }
                }
              }
            }
          }
    }
    `)
return data.allInstaNode.nodes.filter(function(node) {
    if (node.localFile === null) {
      return false;
    }
    return true;
}).map(node => ({
    ...node.localFile.childImageSharp,
    id: node.id,
    caption: node.caption,
    username: node.username,
}))
};
export default useInstagram;

インスタグラムコンポーネントを作成する

次はインスタグラムコンポーネントをcomponentsフォルダーの中に作成します。ここはgatsby-imageが必要になります。
上に書いた use-instagram.jsも使用しますので、インポートを忘れずに。

instagram.js

import React from 'react';
import Image from 'gatsby-image';
import useInstagram from '../hooks/use-instagram';

const Insta = () => {
    const instaPhotos = useInstagram();
    const { username } = instaPhotos[0];
    return (
        <>
            <h2>Instagram posts from @{username}</h2>
            <div>
                {instaPhotos.map(photo => (
                    <a 
                        key={photo.id}
                        href={`https://instagram.com/p/${photo.id}`}
                    >
                      <Image
                          fluid={photo.fluid}
                          alt={photo.caption}
                      />
                    </a>
                ))}
            </div>
            <a href={`https://instagram.com/${username}`}>See more on Instagram</a>
        </>
    )
}
export default Insta;

お好みのページにインスタのコンポーネントを載せる

最後に写真を表示したいページのファイル(例えば、トップページ)に先書いたインスタグラムコンポーネントをインポートして 適当のところにコンポーネントを入れます。

index.js
import React from 'react';
import Insta from '../components/instagram';
export default () => {
    return (
        <>
            <Layout>
                <Insta />
            </Layout>
        </>
    )
}

おわりに

後はcss等を少し工夫したらこのようになりました。
img-screenshot.png

8
5
5

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
8
5