Skip to content

Instantly share code, notes, and snippets.

@jhnsnc
Created January 26, 2018 01:05
Show Gist options
  • Save jhnsnc/e8b83e519e8b153d697d208fcad6910a to your computer and use it in GitHub Desktop.
Save jhnsnc/e8b83e519e8b153d697d208fcad6910a to your computer and use it in GitHub Desktop.
Utility class for adding/removing class names by chaining function calls rather than doing manual string manipulation
/**
* Conditionally add/remove classes and render the result to a class list string
*
* @param {...string} initialClasses - initial class names to add
*/
export class ClassNames {
constructor(...initialClasses) {
this.arrClasses_ = initialClasses;
this.breakUpSpaces_();
return this;
}
breakUpSpaces_() {
this.arrClasses_.slice().forEach(className => { // slice a copy so iteration doesn't stop short
if (className.indexOf(' ') >= 0) {
var idx = this.arrClasses_.indexOf(className);
this.arrClasses_.splice.apply(this.arrClasses_, [idx, 1].concat(className.split(' ')));
}
});
}
add(strClass) {
var trimmed = strClass.trim();
if (this.arrClasses_.indexOf(trimmed) < 0 && trimmed.length) {
this.arrClasses_.push(trimmed);
this.breakUpSpaces_();
}
return this;
}
addIf(strClass, condition) {
return condition ? this.add(strClass) : this;
}
remove(strClass) {
const idx = this.arrClasses_.indexOf(strClass.trim());
if (idx >= 0) {
this.arrClasses_.splice(idx, 1);
this.breakUpSpaces_();
}
return this;
}
removeIf(strClass, condition) {
return condition ? this.remove(strClass) : this;
}
toString() {
return this.arrClasses_.join(' ');
}
get [Symbol.toStringTag]() {
return 'ClassNames';
}
}
@jhnsnc
Copy link
Author

jhnsnc commented Jan 26, 2018

usage:

import React, { Component } from 'react';
import { ClassNames } from 'ClassNames.js';
import { cssClasses } from './stylesheet.less';

export default class MyComponent extends Component {
   render() {
      const componentClasses = new ClassNames()
         .add(cssClasses.main)
         .addIf(cssClasses.active, this.props.active)
         .addIf(cssClasses.disabled, !this.props.enabled);

      return (
         <div className={componentClasses}>test</div>
      );
   }
}

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