DEV Community

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

Posted on • Edited on

4 1

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!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay