Skip to content

Instantly share code, notes, and snippets.

@artginzburg
Last active July 27, 2021 08:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artginzburg/ff6575ae9d27e9bdffb93300b8ba8f9a to your computer and use it in GitHub Desktop.
Save artginzburg/ff6575ae9d27e9bdffb93300b8ba8f9a to your computer and use it in GitHub Desktop.
Perfectly valid React className from an Array · without falsy values
export const toClassNames = (arr) => arr.filter(Boolean).join(' ');
export const classNames = (arr) => ({ className: toClassNames(arr) });

React className from an Array

Just type git.io/toClassNames to go here

This is a simplified version of npm classnames for projects with a limited list of depencendies (e.g. university homework).


Example with classNames()

Use Spread syntax (...) to make it succinct and simple.

import { classNames } from '../functions/toClassNames';
// logo.jsx
<a {...classNames(['logo', '', isInHeader && 'header__logo'])} onClick={showUnicorns}>

outputs className="logo header__logo"



If you're not satisfied with using spread syntax in such context, your perfect option would be the following:

Example with toClassNames()

Pass anything to the array that generates into a string, without worries about ' ', undefined, false etc. being output:

import { toClassNames } from '../functions/toClassNames';
// link.jsx

const linkClasses = [
  linkStyle,
  (props.selectedIndex === index) && 'is-selected',
];

<a className={ toClassNames(linkClasses) } href={pkg.repo}>...</a>

now it doesn't matter how linkStyle was even defined in the first place

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment