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.

【Next.js】useContextを使ってファイル間で値データを共有する

Last updated at Posted at 2021-12-14

useContextを使ってファイル間で値データを共有します。

test.js

import React from 'react';
import Test2 from './test2';

export const UserCount = React.createContext();

function  Test() {

  let count = 333;

  return (
    <div style={{ textAlign: 'center' }}>
      <h1>Test1</h1>
      <UserCount.Provider value={count}>
        <Test2/>
      </UserCount.Provider>
    </div>
  );
}

export default Test;

test2.js

import {useContext} from 'react';
import { UserCount } from './test';

const Test2 = () => {

    const count = useContext(UserCount);

    return (
        <div>
            <p>Test2</p>
            {count}
        </div>
    )
}

export default Test2

###結果
スクリーンショット 2021-12-14 15.04.31.png

test1.jsからtext2.jsへ、値を渡すことができました!

###参考にさせていただいたサイト様

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?