Skip to content

Commit 0623e6a

Browse files
committed
docs: react-router auto color scheme implementation and configuration details
1 parent 367a049 commit 0623e6a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

docs/react-router.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,40 @@ Priority:
5050
3. Session/cookie management (`createTypedCookie`, `rollingCookie`)
5151
4. Real-time (`sse` utilities)
5252
5. Performance/UX (`useDebounceFetcher`, `useDebounceSubmit`, `PrefetchPageAnchors`)
53+
54+
## Auto Color Scheme
55+
56+
To implement auto color scheme and toggle. The app starts using the color scheme of the user's operating system. The user can toggle between light and dark modes using a button, or go back to the system default.
57+
58+
To support this, we use a cookie to store the user's preference, the cookie is typed to have three possible values: `light`, `dark`, and `system`.
59+
60+
If the cookie is not set, or if the value is `system`, we use the `prefers-color-scheme` media query to determine the color scheme. If the value is `light` or `dark`, we use that value instead.
61+
62+
To support this, we override the `dark:` variant on the Tailwind configuration to work with both `.dark` class or `.system` class + media query.
63+
64+
```scss
65+
@custom-variant dark {
66+
/* This supports the .dark class */
67+
&:where(.dark *, .dark) {
68+
@slot;
69+
}
70+
71+
/* This supports the .system class + media query */
72+
&:where(.system *, .system) {
73+
@media (prefers-color-scheme: dark) {
74+
@slot;
75+
}
76+
}
77+
}
78+
```
79+
80+
This approach doesn't use any JavaScript to determine the color scheme, and doesn't have a flash of uncorrect color scheme on page load because we can read the cookie value on the server side and set the initial class on the HTML element.
81+
82+
And since for the `.system` class we use the `prefers-color-scheme` media query in CSS, the browser will automatically render the correct colors when the page loads, instead of needing to inject an inline script in the `<head>` to read the `window.matchMedia` value and set the class on the HTML element.
83+
84+
Files to check:
85+
86+
- `app/app.css`
87+
- `app/color-scheme-cookie.ts`
88+
- `app/root.tsx`
89+
- `app/routes/home.tsx`

0 commit comments

Comments
 (0)