Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Last active September 6, 2019 03:03
Show Gist options
  • Save nicksheffield/a920bb7849747a3b057009b63024d4c4 to your computer and use it in GitHub Desktop.
Save nicksheffield/a920bb7849747a3b057009b63024d4c4 to your computer and use it in GitHub Desktop.
A function to flatten a combination of strings arrays and objects down into a single string. Used for handling conditional class names in react
export const styles = (arg) => {
if (typeof arg === 'string') return arg
if (arg instanceof Array) {
return arg
.reduce((acc, arg) => {
return [...acc, styles(arg)]
}, [])
.map((x) => x.trim())
.filter((x) => x)
.join(' ')
}
if (typeof arg === 'object') {
return Object.entries(arg)
.reduce((acc, [key, val]) => {
if (!val) return acc
return [...acc, key]
}, [])
.filter((x) => x)
.map((x) => x.trim())
.join(' ')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment