Last active
July 26, 2022 03:47
-
-
Save bicky-tmg/7424fdc5612636d2800d1500b1814c4a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, createContext, useContext } from "react"; | |
//Creating a context | |
const UserContext = createContext(undefined); | |
function App() { | |
const [user, setUser] = useState('John'); | |
return ( | |
<div> | |
<UserContext.Provider value={{ user, setUser }}> | |
<NavBar /> | |
<MainPage /> | |
</UserContext.Provider> | |
</div> | |
) | |
} | |
export default App; | |
// Navbar component | |
function NavBar() { | |
const { setUser } = useContext(UserContext); | |
return ( | |
<nav | |
style={{ | |
display: "flex", | |
alignItems: "center", | |
padding: "0.5rem 1rem", | |
backgroundColor: "rgb(248 250 252)", | |
}} | |
> | |
<h3 style={{ marginRight: "auto" }}>Navbar</h3> | |
<button | |
style={{ | |
borderRadius: "1rem", | |
padding: "0.5rem", | |
backgroundColor: "rgb(203 213 225)", | |
}} | |
onClick={() => setUser('Jane')} | |
> | |
Change to Jane | |
</button> | |
</nav> | |
) | |
} | |
// MainPage component | |
function MainPage() { | |
return ( | |
<div style={{ marginTop: "2rem", textAlign: "center"}}> | |
<h2>Main Page</h2> | |
<WelcomePage /> | |
</div> | |
) | |
} | |
// WelcomePage component | |
function WelcomePage = () { | |
return ( | |
<div> | |
<WelcomeMessage /> | |
{/** Some other welcome page code */} | |
</div> | |
); | |
} | |
// WelcomeMessage component | |
const WelcomeMessage = () => { | |
const { user } = useContext(UserContext); | |
return ( | |
<h1>Hey, {user}!</h1> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment