Skip to content

Instantly share code, notes, and snippets.

@ChaseH88
Created March 10, 2023 19:38
Show Gist options
  • Save ChaseH88/dc71f68ecdb80b8e9a55b99fc71b5692 to your computer and use it in GitHub Desktop.
Save ChaseH88/dc71f68ecdb80b8e9a55b99fc71b5692 to your computer and use it in GitHub Desktop.
import { useMemo } from 'react'
type ClassValue = string | { [key: string]: boolean } | undefined | null | false
const useClassNames = (...classes: ClassValue[]): string => {
const className = useMemo(
() =>
classes
.filter(Boolean)
.map((classValue) => {
if (typeof classValue === 'string') {
return classValue
} else if (
typeof classValue === 'object' &&
classValue !== null &&
!Array.isArray(classValue) &&
Object.getPrototypeOf(classValue) === Object.prototype
) {
return Object.entries(classValue)
.filter(([, value]) => Boolean(value))
.map(([key]) => key)
.join(' ')
} else {
return ''
}
})
.filter(Boolean)
.join(' '),
[classes]
)
return className
}
export { useClassNames }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment