1.0.3 • Published 4 years ago

classnames-helper v1.0.3

Weekly downloads
4
License
ISC
Repository
github
Last release
4 years ago

Description

Build Status Coverage Status

This small package is a simple alternative to other solutions available on npm.

The goal is to reduce the amount of code it takes to describe the structure of an element's classnames.

The classnames-helper offers a simple way to join classnames with optional conditions while removing unnecessary spaces.

How to install

npm install classnames-helper

Usage

import cn from 'classnames-helper';

The function cn accepts an unlimited number of arguments.

Arguments

Each argument must be one of the following:

ShapeEffect
stringThis classname will always be appended to the resulting classnames.
boolean, stringIf the condition is true, the classname will be appended to the resulting classnames.
boolean, string, stringIf the condition is true, the first classname will be used. If the condition is false, the second classname will be used instead.
[number, ...string[]]The appended classname will be selected by the provided number (index).

Example

import React, { useState } from "react";
import cn from "classnames-helper";

const STATE = {
  DEFAULT: 0,
  PRIMARY: 1,
  DANGER: 2,
};

function ReactComponent() {
  const [isActive, setActive] = useState(true);
  const [isHidden, setHidden] = useState(false);
  const [state, setState] = useState(STATE.PRIMARY);

  // ...

  // Define order of classes and conditions
  const className = cn(
    "c-component-name",
    [isActive, "-active"],
    [isHidden, "-hide", "-show"],
    [state, "-default", "-primary", "-danger"],
    "some-other-class"
  );

  return (
    <button type="button" className={className} onClick={...}>Click Me</button>
  );
}

export default ReactComponent;

The ouput :

<button type="button" className="c-component-name -active -show -primary some-other-class">
  Click Me
</button>
1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago