DEV Community

Cover image for Concat Class Names
Andreas Riedmüller
Andreas Riedmüller

Posted on • Edited on

Concat Class Names

When I began to work with React I used to install and import classnames in any project. But I found that a smaller and simple helper function is sufficient for all of my projects:

// Javascript
export function concatClassNames(...args) {
  return args.filter(item => !!item).join(' ');
}

// TypeScript
export function concatClassNames(...args: Array<string|boolean|null|undefined>)
: string {
  return args.filter(item => !!item).join(' ');
}
Enter fullscreen mode Exit fullscreen mode

Usage is a little different than classnames though. What I like is that it looks similar to conditionally including components in React.

import { concatClassNames as cn } from 'helpers';
import { important, myClass } from './styles.module.css';

export function SomeComponent({ className, isImportant }) {
  return <div
    className={cn(className, myClass, isImportant && important)}
  >
    Hello World{isImportant && ' !!!'}
  </div>;
}
Enter fullscreen mode Exit fullscreen mode

Feel free to use it in you projects and let me know what you think!

Top comments (0)