1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Next.jsでページ間でデータを共有する方法

🍣 コード

components/DataContext.js
import React, { createContext } from 'react'

export const DataContext = createContext()
_app.js
import '../styles/globals.css'
import { DataContext } from '../components/DataContext'

function MyApp({ Component, pageProps }) {
  const sushi = { name: 'ikura', price: 1000 }

  return (
    <DataContext.Provider value={sushi}>
      <Component {...pageProps} />
    </DataContext.Provider>
  )
}

export default MyApp
about.jsx
import { useContext } from 'react'
import { DataContext } from '../components/DataContext'

const About = () => {
  const sushi = useContext(DataContext)
  console.log(sushi)

  return (
    <>
      About Page.
    </>
  )
}

export default About

🍣 解説

ページ間でデータを共有するには、React Contextを使用します。

まずcreateContextを使用し、コンテキストを作成します。

components/DataContext.js
export const DataContext = createContext()

次に、データを共有するページをコンテキストのプロバイダを使用しタグで包みます。

_app.js
// ...
  return (
    <DataContext.Provider value={sushi}>
      <Component {...pageProps} />
    </DataContext.Provider>
  )
// ...

最後に、各ページでuseContextを使用しコンテキストを呼び出します。

about.jsx
import { useContext } from 'react'
import { DataContext } from '../components/DataContext'

const sushi = useContext(DataContext)
console.log(sushi)

🍣 参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
1
Help us understand the problem. What are the problem?