Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. type ValidClass = string | number | undefined | null | ObjectClass;
  2.  
  3. type ObjectClass = {
  4. [key: string]: boolean | undefined;
  5. };
  6.  
  7. type ClassName = ValidClass | ValidClass[];
  8.  
  9. /**
  10. * Easier class names management for JSX elements.
  11. *
  12. * Usage:
  13. *
  14. * ```js
  15. <div className={classNames('some-class', 'another', ['arr', 'of', 'classes'], {
  16. 'conditional-class': this.state.someValue
  17. })}>
  18. ```
  19.  
  20. * Note that the order of the keys in a passed object will not be explicitly
  21. * preserved: that's up to the Javascript engine (most engines preserve key order).
  22. */
  23. export default function classNames(...args: ClassName[]): string {
  24. return args
  25. .filter((_) => !!_) // Filter out falsiness
  26. .map((arg) => {
  27. const type = typeof arg;
  28.  
  29. // We can add numbers and strings as class names instantly,
  30. // but for arrays and objects, we need to traverse.
  31. if (type === 'string' || type === 'number') {
  32. return arg;
  33. } else if (Array.isArray(arg) && arg.length) {
  34. // Recuuuurse
  35. return classNames(...arg);
  36. } else if (type === 'object' && arg) {
  37. const objMap = <ObjectClass>arg;
  38. return Object.keys(objMap)
  39. .filter((cl) => objMap[cl])
  40. .join(' ');
  41. }
  42.  
  43. return '';
  44. })
  45. .join(' ');
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement