Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of using React Context to make data available to deeply nested components
import React from "react";
import { ThemeProvider } from "./Theme";
import ToggleTheme from "./ToggleTheme";
import ThemedText from "./ThemedText";
const App: React.FC = () => (
<ThemeProvider>
<ToggleTheme />
<ThemedText>Hello World</ThemedText>
</ThemeProvider>
)
export default App;
import React from "react";
type Theme = "light" | "dark";
interface IThemeContext {
theme: Theme;
setTheme: (theme: Theme) => void;
}
// Here we create the ThemeContext which our components will reference
// We provide the default values that will be used if there's no <ThemeProvider> in the tree
export const ThemeContext = React.createContext<IThemeContext>({
// By default, we'll use the light theme
theme: "light",
// If the <ThemeProvider> isn't in the tree, then calling setTheme will be a no-op
setTheme: () => {}
});
export const ThemeProvider: React.FC = ({ children }) => {
const [theme, setTheme] = React.useState<Theme>("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
import React from "react";
import { ThemeContext } from "./Theme";
const ThemedText: React.FC = ({ children }) => {
const { theme } = React.useContext(ThemeContext);
const textColor = theme === "light" ? "black" : "white";
return <p style={{color: textColor}}>{children}</p>
};
export default ThemedText;
import React from "react";
import { ThemeContext } from "./Theme";
const ToggleTheme: React.FC = () => {
const { theme, setTheme } = React.useContext(ThemeContext);
const toggle = () => {
if (theme === "light") setTheme("dark");
else if (theme === "dark") setTheme("light");
};
return <button onClick={toggle}>Change themes</button>;
};
export default ToggleTheme;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.