Skip to content

Instantly share code, notes, and snippets.

@ryanwilsonperkin
Created November 8, 2019 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanwilsonperkin/8bd74ef5fc0078e9aa85a9db2e9d3ac2 to your computer and use it in GitHub Desktop.
Save ryanwilsonperkin/8bd74ef5fc0078e9aa85a9db2e9d3ac2 to your computer and use it in GitHub Desktop.
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