Skip to content

Instantly share code, notes, and snippets.

Last active July 27, 2021 08:50
What would you like to do?
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 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 = [
  (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