Last active
August 12, 2021 08:34
-
-
Save click2install/fa0b90f0b271d11afc2c0d709b889a42 to your computer and use it in GitHub Desktop.
[ThemeProvider] - A FluentUI React theme context provider.
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 { AzureCustomizationsLight, AzureCustomizationsDark } from "@uifabric/azure-themes"; | |
import { ThemeProvider as FluentThemeProvider } from "@fluentui/react-theme-provider"; | |
import React, { createContext, PropsWithChildren, useContext, useState } from "react"; | |
import { useLocalStorage } from "../hooks/useLocalStorage"; | |
interface IThemeContext | |
{ | |
themeName: string; | |
toggleTheme(): void; | |
} | |
enum themes | |
{ | |
light = "light", | |
dark = "dark" | |
}; | |
const NullThemeContext: IThemeContext = | |
{ | |
themeName: themes.light, | |
toggleTheme: () => { throw new Error(nameof(NullThemeContext)); } | |
}; | |
const ThemeContext = createContext<IThemeContext>(NullThemeContext); | |
export function ThemeProvider<T>({ children }: PropsWithChildren<T>) | |
{ | |
const [themeName, setThemeName] = useLocalStorage("theme", themes.light); | |
const [theme, setTheme] = useState(getTheme(themeName)); | |
function getTheme(name: string) | |
{ | |
const customization = name === themes.light ? AzureCustomizationsLight : AzureCustomizationsDark; | |
return customization.settings.theme; | |
} | |
function toggleTheme() | |
{ | |
const name = themeName === themes.light ? themes.dark : themes.light; | |
setThemeName(name); | |
setTheme(getTheme(name)); | |
} | |
return ( | |
<ThemeContext.Provider value={{ themeName, toggleTheme }}> | |
<FluentThemeProvider theme={theme}> | |
{children} | |
</FluentThemeProvider> | |
</ThemeContext.Provider> | |
); | |
} | |
export function useTheme() | |
{ | |
return useContext(ThemeContext); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment