createContextを生成
valueに共有したい変数を記述。
App.js
import { createContext, useState } from 'react'
import './App.css'
import Login from './components/Login';
import User from './components/User';
export const AuthContext = createContext();
function App() {
const [userName, setUserName] = useState("")
return (
<AuthContext.Provider value={{ userName, setUserName }}>
<div className="App">
<Login />
<br />
<User />
</div>
</AuthContext.Provider>
)
}
export default App
Login.js、User.jsにuseContextを記述
Login.js
import React, { useContext } from 'react'
import { AuthContext } from '../App'
const Login = () => {
const { setUserName } = useContext(AuthContext)
return (
<div>
<h1>Login</h1>
<input
type="text"
placeholder='Input New Name...'
onChange={(e) => setUserName(e.target.value)}
/>
</div>
)
}
export default Login
User.js
import React, { useContext } from 'react'
import { AuthContext } from '../App'
const User = () => {
const { userName } = useContext(AuthContext)
return (
<div>
<h1>User</h1>
<p>{userName}</p>
</div>
)
}
export default User
結果
propsを使わなくても変数を共有できています。
参考動画