Skip to content

Instantly share code, notes, and snippets.

@bicky-tmg
Last active July 26, 2022 03:47
Show Gist options
  • Save bicky-tmg/7424fdc5612636d2800d1500b1814c4a to your computer and use it in GitHub Desktop.
Save bicky-tmg/7424fdc5612636d2800d1500b1814c4a to your computer and use it in GitHub Desktop.
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