LoginSignup
0
0

More than 3 years have passed since last update.

Gatsby.jsでreact-reduxを使う方法

Posted at

皆さんこんにちは!

今回はGatsby.jsでreduxを使用する方法を書いていこうかなと思います。

素のReactと実装方法が少しだけ異なるので、ぜひGatsby.jsでreduxを使いたいという方はご覧ください!

それでは説明していきます。

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

まずは必要なパッケージをインストールしてください。

npm install --save redux react-redux redux-thunk gatsby-plugin-react-redux

reduxの設定

次に、reduxの設定を行っていきます。

store.js
import { applyMiddleware, combineReducers, createStore as reduxCreateStore } from "redux"
import thunk from "redux-thunk"
import Test from "./test"


export default function createStore() {
  let middleWares = [thunk]

  return reduxCreateStore(
    combineReducers({
      test: Test
    }),
    applyMiddleware(...middleWares)
  )
}

gatsby-configの設定

次は、gatsby-config.jsに以下の設定を加えて下さい。

module.exports = {
  plugins: [
    // 省略
    {
      resolve: `gatsby-plugin-react-redux`,
      options: {
        pathToCreateStoreModule: "@/store.js" // 先ほど作成したreduxの設定ファイルのパスを入力
      }
    }
  ],
}

Providerの設置

最後にstoreの情報を扱えるようにLayout.jsのような毎回レンダリングされる要素の配下にProviderを設置してあげましょう!

Layout.js
import React from "react"
import { Provider } from "react-redux"
import createStore from "@/store.js" // reduxの設定を行ったファイル
import { Header } from "../Header"

export const store = createStore()

const Layout = (props) => {
  return (
    <Provider store={store}>
      <Header />
      <main></main>
    </Provider>
  )
}

export default Layout

propsとしてstoreプロパティにcreateStore()で作成したstoreを渡してあげましょう。

このようにしてstoreの情報を参照することができます!

いかがだったでしょうか?

こうしてみると案外簡単なものですね。

皆さんもぜひ使って下さい!

以上、「Gatsby.jsでreact-reduxを使う方法」でした!

Thank you for reading

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