Skip to content

Instantly share code, notes, and snippets.

@OlivierJM
Created June 29, 2021 20:31
Show Gist options
  • Save OlivierJM/343680e9849fd1fe0d3a27d427c5aa7d to your computer and use it in GitHub Desktop.
Save OlivierJM/343680e9849fd1fe0d3a27d427c5aa7d to your computer and use it in GitHub Desktop.
import { createContext, useContext, useState } from "react";
// Consumer
// useContext
const AppContext = createContext();
const ThemeContext = createContext();
export default function App() {
const [language, setLanguage] = useState("en-US");
const [color, setColor] = useState("blue");
return (
<AppContext.Provider value={{ color, language }}>
{/* child component of app */}
<MainSection lang={language} color={color} />
<Footer lang={language} />
</AppContext.Provider>
);
}
function MainSection({ lang, color }) {
return (
<>
I am the main section guy
<p>lorem </p>
<p>
Language: <b>{lang}</b>{" "}
</p>
{/* child component of MainSection */}
<Button color={color} language={lang} />
<br />
</>
);
}
function Footer({ lang }) {
return (
<>
I am the footer guy
<p>lorem </p>
{/* <p>{lang} </p> */}
</>
);
}
function Button() {
const context = useContext(AppContext);
return (
<button style={{ backgroundColor: context.color }}>
{/* child component of Button */}
<Text language={context.language} />
</button>
);
}
// child component of button
// because the Text is not a direct child of App we can't access its state
// we can't access color
// we can't access the language
// render prop
function Text({ language }) {
return (
<AppContext.Consumer>
{({ color }) => (
<span style={{ backgroundColor: color }}>{language}</span>
)}
</AppContext.Consumer>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment