Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow mapping to multiple class names #298

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions next-themes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,14 @@ If we want the DOM to instead render `data-theme="my-pink-theme"` when the theme

Done! To be extra clear, this affects only the DOM. Here's how all the values will look:

if we want to map a theme to multiple custom theme values, we can simply pass an array:
```jsx
<ThemeProvider attribute='class' value={{ pink: ['my-pink-theme', 'another-pink-theme'] }}>
```

When the selected theme is `pink`, both `my-pink-theme` and `another-pink-theme` will be added as class names.


```js
const { theme } = useTheme()
// => "pink"
Expand Down
12 changes: 6 additions & 6 deletions next-themes/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const Theme = ({
const [resolvedTheme, setResolvedTheme] = React.useState(() => getTheme(storageKey))
const attrs = !value ? themes : Object.values(value)

const applyTheme = React.useCallback(theme => {
const applyTheme = React.useCallback((theme: string) => {
let resolved = theme
if (!resolved) return

Expand All @@ -48,17 +48,17 @@ const Theme = ({
resolved = getSystemTheme()
}

const name = value ? value[resolved] : resolved
const names = [value ? value[resolved] ?? [] : resolved].flat()
const enable = disableTransitionOnChange ? disableAnimation() : null
const d = document.documentElement

const handleAttribute = (attr: Attribute) => {
if (attr === 'class') {
d.classList.remove(...attrs)
if (name) d.classList.add(name)
d.classList.remove(...attrs.flat())
if (names.length) d.classList.add(...names)
} else if (attr.startsWith('data-')) {
if (name) {
d.setAttribute(attr, name)
if (names.length) {
d.setAttribute(attr, names.join(' '))
} else {
d.removeAttribute(attr)
}
Expand Down
2 changes: 1 addition & 1 deletion next-themes/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from 'react'

interface ValueObject {
[themeName: string]: string
[themeName: string]: string | string[]
}

export interface UseThemeProps {
Expand Down
Loading