useColorScheme
Hook to handle ColorScheme.
Demo
INFO
The component uses useColorScheme with these properties:
- defaultValue: "mediaQuery", so it read color-scheme with media query.
- returnValue: true, so it returns current value.
- getter: a function that returns value from sessionStorage item with key "color-scheme".
- setter: a function that save current value to sessionStorage item with key "color-scheme". The component renders a div with a class container that changes border and text colors by color-scheme selected and a button to manually change value.
Loading demo…
Show source code
tsx
import { useCallback } from "react";
import { useColorScheme } from "../../../.."
export const UseColorScheme = () => {
const [value, update] = useColorScheme({
defaultValue: "mediaQuery",
returnValue: true,
getter: useCallback(() => sessionStorage.getItem("color-scheme") as "dark" | "light" | null, []),
setter: useCallback((val: "dark" | "light") => sessionStorage.setItem("color-scheme", val), [])
});
return (
<div className="container-themed" data-color={value}>
<p>Current color-scheme is: {value}</p>
<button onClick={() => update(value === "dark" ? "light" : "dark")}>Change color</button>
</div>
);
}Types
UseColorSchemeProps
Props accepted by useColorScheme.
| Property | Type | Required | Description |
|---|---|---|---|
defaultValue | "dark" \| "light" \| "mediaQuery" | ✓ | initial value if getter function isn't present or isn't return a valid value. |
getter | () => "dark" \| "light" \| null \| undefined | an optional function used to initialize current value. For example, it can be useful for reading the value from an attribute of an html file or from localStorage | |
setter | (schema: "light" \| "dark") => void | an optional function, which should work in conjunction with the getter function, to run when the color scheme changes to save the value for future runs. | |
returnValue | boolean | ✓ | if true returns only a function to manually change the color scheme value. |
UseColorSchemeResult
Result returned by useColorScheme.
[0]— curren color schema value.[1]— function to update value.
OR
[0]— function to update value.
ts
export type UseColorSchemeResult =
| [
/**curren color schema value */
"light" | "dark",
/**
* function to update value
* @param value - The value to update.
*/
(schema: "light" | "dark") => void
]
| ((schema: "light" | "dark") => void);