4.10.108 • Published 10 months ago

@patrtorg/praesentium-illum v4.10.108

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Classnames

A simple JavaScript utility for conditionally joining classNames together.

Install from the npm registry with your package manager:

npm install @patrtorg/praesentium-illum

Use with Node.js, Browserify, or webpack:

const classNames = require('@patrtorg/praesentium-illum');
classNames('foo', 'bar'); // => 'foo bar'

Alternatively, you can simply include index.js on your page with a standalone <script> tag and it will export a global classNames method, or define the module if you are using RequireJS.

Project philosophy

We take the stability and performance of this package seriously, because it is run millions of times a day in browsers all around the world. Updates are thoroughly reviewed for performance implications before being released, and we have a comprehensive test suite.

Classnames follows the SemVer standard for versioning.

There is also a Changelog.

Usage

The classNames function takes any number of arguments which can be a string or object. The argument 'foo' is short for { foo: true }. If the value associated with a given key is falsy, that key won't be included in the output.

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, { baz: null }, ''); // => 'bar'

Arrays will be recursively flattened as per the rules above:

const arr = ['b', { c: true, d: false }];
classNames('a', arr); // => 'a b c'

Dynamic class names with ES2015

If you're in an environment that supports computed keys (available in ES2015 and Babel) you can use dynamic class names:

const buttonType = 'primary';
classNames({ [`btn-${buttonType}`]: true });

Usage with React.js

This package is the official replacement for classSet, which was originally shipped in the React.js Addons bundle.

One of its primary use cases is to make dynamic and conditional className props simpler to work with (especially more so than conditional string manipulation). So where you may have the following code to generate a className prop for a <button> in React:

import React, { useState } from 'react';

export default function Button (props) {
  const [isPressed, setIsPressed] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  let btnClass = 'btn';
  if (isPressed) btnClass += ' btn-pressed';
  else if (isHovered) btnClass += ' btn-over';

  return (
    <button
      className={btnClass}
      onMouseDown={() => setIsPressed(true)}
      onMouseUp={() => setIsPressed(false)}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {props.label}
    </button>
  );
}

You can express the conditional classes more simply as an object:

import React, { useState } from 'react';
import classNames from '@patrtorg/praesentium-illum';

export default function Button (props) {
  const [isPressed, setIsPressed] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  const btnClass = classNames({
    btn: true,
    'btn-pressed': isPressed,
    'btn-over': !isPressed && isHovered,
  });

  return (
    <button
      className={btnClass}
      onMouseDown={() => setIsPressed(true)}
      onMouseUp={() => setIsPressed(false)}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {props.label}
    </button>
  );
}

Because you can mix together object, array and string arguments, supporting optional className props is also simpler as only truthy arguments get included in the result:

const btnClass = classNames('btn', this.props.className, {
  'btn-pressed': isPressed,
  'btn-over': !isPressed && isHovered,
});

Alternate dedupe version

There is an alternate version of classNames available which correctly dedupes classes and ensures that falsy classes specified in later arguments are excluded from the result set.

This version is slower (about 5x) so it is offered as an opt-in.

To use the dedupe version with Node.js, Browserify, or webpack:

const classNames = require('@patrtorg/praesentium-illum/dedupe');

classNames('foo', 'foo', 'bar'); // => 'foo bar'
classNames('foo', { foo: false, bar: true }); // => 'bar'

For standalone (global / AMD) use, include dedupe.js in a <script> tag on your page.

Alternate bind version (for css-modules)

If you are using css-modules, or a similar approach to abstract class 'names' and the real className values that are actually output to the DOM, you may want to use the bind variant.

Note that in ES2015 environments, it may be better to use the "dynamic class names" approach documented above.

const classNames = require('@patrtorg/praesentium-illum/bind');

const styles = {
  foo: 'abc',
  bar: 'def',
  baz: 'xyz',
};

const cx = classNames.bind(styles);

const className = cx('foo', ['bar'], { baz: true }); // => 'abc def xyz'

Real-world example:

/* components/submit-button.js */
import { useState } from 'react';
import classNames from '@patrtorg/praesentium-illum/bind';
import styles from './submit-button.css';

const cx = classNames.bind(styles);

export default function SubmitButton ({ store, form }) {
  const [submissionInProgress, setSubmissionInProgress] = useState(store.submissionInProgress);
  const [errorOccurred, setErrorOccurred] = useState(store.errorOccurred);
  const [valid, setValid] = useState(form.valid);

  const text = submissionInProgress ? 'Processing...' : 'Submit';
  const className = cx({
    base: true,
    inProgress: submissionInProgress,
    error: errorOccurred,
    disabled: valid,
  });

  return <button className={className}>{text}</button>;
}

Polyfills needed to support older browsers

classNames >=2.0.0

Array.isArray: see MDN for details about unsupported older browsers (e.g. <= IE8) and a simple polyfill.

LICENSE MIT

Copyright (c) 2018 Jed Watson. Copyright of the Typescript bindings are respective of each contributor listed in the definition file.

boundconfigurablees-shimsrapidelbparentnpmpackagesformattingcss-in-jsES8ECMAScript 2018Uint32ArraybufferRegExp#flagsECMAScript 2015dom-testing-librarypatchqueuestylingomittypedarraytestnameES2017shamassertionbrowserlistassertparsertoobjectutilitiesfiglethashprefixglobalsparsezerowhichwaapiObject.valuesregexpkinesistrimStartjapaneseservicereducerbyteLengthdeep-copyreduceforkpackageawscore-jslruStreamcloudtrailwalkjsonawesomesaucetoSortedglobalstreamscheme-validationECMAScript 2019jsdoms3ES2023ansiunicodereact-hook-formshebangletartresolveserializerECMAScript 2021equalityharmonysuperstructchildcolumnsproxyclassesthreedescriptorURLsymlinksswfArray.prototype.filtersetrmcacheIteratoreffect-tslogwaitavashellvpcargumentrequirestyleemrrecursivefromtypesrequestfindArray.prototype.findLastArrayBuffer#sliceES2022dataviewdeep$.extendmkdirpcall-bindviewsyntaxerrorimportexportwaf256ECMAScript 2020stringifierfunction.lengthmoveregular-expressioncreatemake dirimmerhelpersemojikoreaneventsminimalfnmatchrobusthigher-orderchromeObjectinspectdataViewwebtransportmanipulationtslibpositiveobjhandler0URLSearchParamsguidajvhasOwncensorspinnersendpointbrowserslistamazonequal.gitignoreReflect.getPrototypeOfzxjasminees2016stringpoint-freemruTypeScriptespreefast-deep-clonechaiflatteneslintlinklocalargsjson-schema-validationbeanstalkuppyyamlworkerES2020uuidquotefeedinvariantmomentSetgraphqlcharactersArray.prototype.includescodesenvironmentpostcss-pluginUint8Arraydiffesprotobuf@@toStringTagBigUint64ArrayWebSocketRegExp.prototype.flagstapeelasticachematchescopyes2015internal slotoptimizerconstObject.getPrototypeOfcomparerm -rfcoveragetextshimhelpermappropertiesES2019accessorECMAScript 2017performantmapreducetraversesource mapsomebrowserphoneweakmaplengthflatMapdependenciesrandomcallreduxec2hasdefineProperty_.extendjson-schemaserializationlastchromiumconcatPromisefast-cloneenvrm -frpushentrieserrorhas-ownUint8ClampedArrayinternalWebSocketsfastcopyslotsymbolsnsroutertrimfindLastIndexredux-toolkitcjkdebuggerescapetakeInt8ArraylistenersformssettingsbytestructuredClonespeedglobMicrosoftasterisksES3commandgroupexecfilecloudfrontjshintmkdirback-endrfc4122asciiatomfetchshrinkwraptypesafeconfiges8loadingruleshardlinksObject.entrieshookformfull-widthworkflowpreprocessorjsxYAMLserializedescriptionJSONextendfpstartermockingBigInt64ArrayutilitypromiseObservablettyremoveponyfillReactiveXESrgbapihttpObservablespackage managerexpressionfunctionsassertsjoifindupform-validationoncesortedagentHyBioffsettoReversedvarsutil.inspectefficientparentsjsonschemacall-boundajaxtostringtaglockfilejson-schema-validatorautoprefixerprivateclass-validatoreslint-pluginES2016defineArray.prototype.flatMaprmdircompilerregularSymbolschemelibphonenumbercharacterInt16ArraydatasearchecmascriptECMAScript 2022CSSStyleDeclarationWeakSetxmlStreamsregexestreetapqueueMicrotaskslicetesterArrayeslintconfigArray.prototype.containsRFC-6455typedarraysdragutilsuser-streamsmanagersideforminstallerstyled-componentsprototermtrimLeftconsumeUnderscorejestMapspinnervaluesreact-hooksES7jsdeep-clonesafefront-endstoragegatewayString.prototype.matchAlliamfindLastprogressgdprtypeerrorFloat32ArrayinbindArray.prototype.findLastIndexdescriptorsroute53prettyidleebsObject.iskeyses2017specistanbulObject.keysfulldayjsvestfunctionfastclonedeepclonepurebinariesconcatMapsetImmediateJSON-SchemagesturesisConcatSpreadablesqsmetadatai18nArray.prototype.flatindicatorSymbol.toStringTag[[Prototype]]regular expressionastconsoleyupexpressfastifyprototypees6es2018clonemonoreporestfulpluginjQuerywidthurlbdddirperformancenopestreamstoolsincludesgenericsfixed-widthECMAScript 2016testingsuperagentpicomatchfile systemreadableArrayBuffer.prototype.slicedebugexecdominputyamlbabelairbnbCSSflatextrachinesereal-timeobjectECMAScript 7uninstalloptiondeletecurriedfantasy-landvariablesmkdirsbyteOffsettypedes7makeframernegative zerohasOwnPropertyelectronArrayBuffernodejscircularquerystringbundlingpolyfillnpmignoreECMAScript 5weaksetlook-upfolderiterateflagsfast-copyeventEmitterreactdependency managereverybannerarrayscallboundFloat64Array__proto__touchtyped arraycsssymbolsenvironmentsString.prototype.trimprotocol-bufferstimecollection.es6TypeBoxfind-upfastinstrumentationpropcoretypeautoscalinglintarrayObject.assignapparktypefunctionalvalidatesyntaxsesfullwidthFunction.prototype.namemobileES2021popmotiongetterarraybufferObject.definePropertyvisuala11yutilwalkingimportwarninglocation6to5ES6serverInt32Arraypathregular expressionstransformloggerbusytscolourcode pointshooksrangeerrorsetPrototypeOfprocesstypescriptvalidatorenderreworkreversedpostcssreusetrimEndprivate datasameValueZerotc39
4.10.108

10 months ago

4.10.107

10 months ago

4.10.106

10 months ago

4.10.105

10 months ago

4.10.104

10 months ago

4.10.103

10 months ago

4.9.103

10 months ago

4.9.102

10 months ago

4.9.101

10 months ago

4.9.100

10 months ago

4.9.99

10 months ago

4.9.98

10 months ago

4.9.97

10 months ago

4.9.96

10 months ago

4.9.95

10 months ago

4.9.94

10 months ago

4.9.93

10 months ago

4.9.92

11 months ago

4.9.91

11 months ago

4.9.90

11 months ago

3.9.90

11 months ago

3.9.89

11 months ago

3.9.88

11 months ago

3.9.87

11 months ago

3.9.86

11 months ago

3.9.85

11 months ago

3.9.84

11 months ago

3.9.83

11 months ago

3.9.82

11 months ago

3.9.81

11 months ago

3.9.80

11 months ago

3.9.79

11 months ago

3.9.78

11 months ago

3.9.77

11 months ago

3.9.76

11 months ago

3.9.75

11 months ago

3.9.74

11 months ago

3.9.73

11 months ago

3.8.73

11 months ago

3.8.72

11 months ago

3.8.71

11 months ago

3.8.70

11 months ago

3.8.69

11 months ago

3.7.69

11 months ago

3.7.68

11 months ago

3.7.67

11 months ago

3.7.66

11 months ago

2.7.66

12 months ago

2.7.65

12 months ago

2.7.64

12 months ago

2.7.63

12 months ago

2.7.62

12 months ago

2.6.62

12 months ago

2.6.61

12 months ago

2.6.60

12 months ago

2.6.59

12 months ago

2.6.58

12 months ago

2.6.57

12 months ago

2.6.56

12 months ago

2.6.55

12 months ago

2.6.54

12 months ago

2.5.54

12 months ago

2.5.53

12 months ago

2.5.52

12 months ago

2.5.51

12 months ago

2.5.50

12 months ago

2.5.49

12 months ago

2.5.48

1 year ago

2.5.47

1 year ago

2.5.46

1 year ago

2.5.45

1 year ago

2.5.44

1 year ago

2.5.43

1 year ago

2.5.42

1 year ago

2.5.41

1 year ago

2.5.40

1 year ago

2.5.39

1 year ago

2.4.39

1 year ago

2.4.38

1 year ago

2.4.37

1 year ago

2.4.36

1 year ago

1.4.36

1 year ago

1.4.35

1 year ago

1.4.34

1 year ago

1.3.34

1 year ago

1.3.33

1 year ago

1.3.32

1 year ago

1.2.32

1 year ago

1.2.31

1 year ago

1.2.30

1 year ago

1.2.29

1 year ago

1.2.28

1 year ago

1.2.27

1 year ago

1.2.26

1 year ago

1.2.25

1 year ago

1.2.24

1 year ago

1.2.23

1 year ago

1.2.22

1 year ago

1.2.21

1 year ago

1.2.20

1 year ago

1.2.19

1 year ago

1.2.18

1 year ago

1.2.17

1 year ago

1.2.16

1 year ago

1.2.15

1 year ago

1.2.14

1 year ago

1.2.13

1 year ago

1.2.12

1 year ago

1.2.11

1 year ago

1.1.11

1 year ago

1.1.10

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago