score:292

Accepted answer

i use classnames when there is a fair amount of logic required for deciding the classes to (not) use. an overly simple example:

...
    var liclasses = classnames({
      'main-class': true,
      'activeclass': self.state.focused === index
    });

    return (<li classname={liclasses}>{data.name}</li>);
...

that said, if you don't want to include a dependency then there are better answers below.

score:-1

just use a comma!

const usestyles = makestyles((theme) => ({
 rightalign: {
  display: 'flex',
  justifycontent: 'flex-end',
 },
 customspacing: {
  margintop: theme.spacing(2.5),
 },
)};

<div classname={(classes.rightalign, classes.customspacing)}>some code</div>

score:0

i use rc-classnames package.

// es6
import c from 'rc-classnames';

// commonjs
var c = require('rc-classnames');

<button classname={c('button', {
  'button--disabled': isdisabled,
  'button--no-radius': !hasradius
})} />

you can add classes in any format (array, object, argument). all truthy values from arrays or arguments plus keys in objects that equal to true get merged together.

for example:

reactclassnames('a', 'b', 'c') // => "a b c"
reactclassnames({ 'a': true, 'b': false, c: 'true' }) // => "a c"
reactclassnames(undefined, null, 'a', 0, 'b') // => "a b"

score:0

i bind classnames to the css module imported to into the component.

import classnames from 'classnames'; 
import * as styles from './[styles path];
const cx = classnames.bind(styles); 

classnames gives the ability to declare classname for a react element in a declarative way.

ex:

<div classnames={cx(styles.titletext)}> lorem </div>

<div classnames={cx('float-left')}> lorem </div> // global css declared without css modules
<div classnames={cx( (test === 0) ?
             styles.titletext : 
             styles.subtitletext)}>  lorem </div> // conditionally assign classes

<div classnames={cx(styles.titletext, 'float-left')}> lorem </div> //combine multiple classes

score:0

if you wanna use a double conditional css module is always somehow confusing so i would advise you to follow this pattern

import styles from "./styles.module.css"

const conditonal=({large, redcolor}) => {
 return(
  <div classname={[large && styles.large] + [redcolor && styles.color]>
   ...
  </div>
 )
}

export default conditonal

and if its just one conditonal statement with two class name, use this

import styles from "./styles.module.css"

const conditonal=({redcolor}) => {
 return(
  <div classname={styles.large + [redcolor && styles.color]>
   ...
  </div>
 )
}

export default conditonal

score:0

use jbcn module. (bem support)

https://www.npmjs.com/package/jbcn

example:

const classnames = jbcn({ 
    btn: { 
        alpha: true, 
        beta: true, 
        gamma: false 
    } 
});

// ==> "btn btn--alpha btn--beta"
const classnames = jbcn({
    expand: true,
    hide: false,

    btn: { 
        alpha: true, 
        beta: true, 
        gamma: false 
    } 
});

// ==> "expand btn btn--alpha btn--beta"

score:0

bad idea to join css classes using a string concatenation. there are multiple cases where it is very confusing and overwhelming. better to add some simple helper which join all of these into the one string. here is example:

import isstring from 'lodash/isstring';
import isobject from 'lodash/isobject';
/**
 * helper function for conditionally creating css class strings.
 *
 * example usage:
 *   classnames('foo', ['bar', ''], { baz: false, bob: true });
 *   => 'foo bar bob'
 *
 * @module helpers/classnames
 * @param {...(string|string[]|object)} args
 * @returns {string}
 */
export default function classnames(...args) {
  const classes = [];
  for (const arg of args) {
    if (arg !== null && typeof arg !== 'undefined') {
        if (isstring(arg)) {
          classes.push(arg);
        } else if (array.isarray(arg)) {
          classes.push(classnames(...arg));
        } else if (isobject(arg)) {
          classes.push(classnames(...object.keys(arg).filter(k => arg[k])));
        }
    }
  }
  return classes.join(' ');
}

(from https://tomsoir.medium.com/react-css-classnames-concatenation-pattern-fd0fa1f31143)

score:1

that's what i do:

component:

const button = ({ classname }) => (
  <div classname={ classname }> </div>
);

calling component:

<button classname = 'hashbutton free anotherclass' />

score:1

i am using react 16.6.3 and @material ui 3.5.1, and is able to use arrays in classname like classname={[classes.tablecell, classes.capitalize]}

so in your example, the following would be similar.

<li key={index} classname={[activeclass, data.class, "main-class"]}></li>

score:1

i usually use it like this : (in your case)

    <li  key={index} classname={
        "component " +
        `${activeclass? activeclass: " not-an-active-class "}` +
        `${data.class? " " + data.class : " no-data-class "}`
   } />

when it comes to jsx and (usually) we have some json... than you loop it ... component.map, plus some conditional to check if json property exists to render class name depending on property value from json. in example below component_color and component_dark_shade are properties from component.map()

   <div classname={
        "component " +
        `${component_color? component_color: " no-color "}` +
        `${component_dark_shade? " " + component_dark_shade : " light "}`
   }/>

output : <div class="component no-color light" .... or: <div class="component blue dark" .... depending on values from map...

score:2

using facebook's todotextinput.js example

render() {
    return (
      <input classname={
        classnames({
          edit: this.props.editing,
          'new-todo': this.props.newtodo
        })}
        type="text"
        placeholder={this.props.placeholder}
        autofocus="true"
        value={this.state.text}
        onblur={this.handleblur}
        onchange={this.handlechange}
        onkeydown={this.handlesubmit} />
    )
  } 

replacing classnames with plain vanilla js code will look like this:

render() {
    return (
      <input
        classname={`
          ${this.props.editing ? 'edit' : ''} ${this.props.newtodo ? 'new-todo' : ''}
        `}
        type="text"
        placeholder={this.props.placeholder}
        autofocus="true"
        value={this.state.text}
        onblur={this.handleblur}
        onchange={this.handlechange}
        onkeydown={this.handlesubmit} />
    )
  }

score:2

if you don't feel like importing another module, this function works like the classnames module.

function classnames(rules) {
    var classes = ''

    object.keys(rules).foreach(item => {    
        if (rules[item])
            classes += (classes.length ? ' ' : '') + item
    })

    return classes
} 

you can use it like this:

render() {
    var classes = classnames({
        'storeinfodiv': true,  
        'hover': this.state.ishovered == this.props.store.store_id
    })   

    return (
        <somecomponent style={classes} />
    )
}

score:2

use https://www.npmjs.com/package/classnames

import classnames from 'classnames';

  1. can use multiple classes using comas seperated:

    <li classname={classnames(classes.tablecelllabel, classes.tablecell)}>total</li>
    
  2. can use multiple classes using comas separated with condition:

    <li classname={classnames(classes.buttonarea, !nodes.length && classes.buttonareahidden)}>hello world</li> 
    

using array as props to classnames will also work, but gives warning e.g.

classname={[classes.tablecelllabel, classes.tablecell]}

score:2

clsx makes this simple!

"the clsx function can take any number of arguments, each of which can be an object, array, boolean, or string."

-- clsx docs on npmjs.com

import it:

import clsx from 'clsx'

use it:

<li key={index} classname={clsx(activeclass, data.class, "main-class")}></li>

score:2

i used this syntax

    <div
      classname={[
        "d-inline-flex justify-content-center align-items-center ",
        withwrapper && `ft-icon-wrapper ft-icon-wrapper-${size}`,
        wrapperclass,
      ].join(" ")}
    >
      <img
        classname={`ft-icon ft-icon-${size} ${iconclass}`}
        alt={id}
        src={icon}
      />
    </div>

score:3

when i have many varying classes, i have found the following to be useful.

the filter removes any of the null values and the join puts all the remaining values into a space separated string.

const buttonclasses = [
    "button", 
    disabled ? "disabled" : null,
    active ? "active" : null
].filter((class) => class).join(" ")

<button classname={buttonclasses} onclick={onclick} disabled={disabled ? disabled : false}>

score:4

late to the party, but why use third party for such a simple problem?

you could either do it as @huw davies mentioned - the best way

1. <i classname={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
2. <i classname={[styles['foo-bar-baz'], 'fa fa-user', 'fa-2x'].join(' ')}

both are good. but writing can become complex for a large app. to make it optimal, i do the same above things but put it in a helper class

using my below helper function, allows me to keep the logic separate for future editing, and also gives me multiple ways to add the classes

classnames(styles['foo-bar-baz], 'fa fa-user', 'fa-2x')

or

classnames([styles['foo-bar-baz], 'fa fa-user', 'fa-2x'])

this is my helper function below. i've put it in a helper.js where i keep all my common methods. being such a simple function, i avoided using 3rd party to keep control

export function classnames (classes) {
    if(classes && classes.constructor === array) {
        return classes.join(' ')
    } else if(arguments[0] !== undefined) {
        return [...arguments].join(' ')
    }
    return ''
}

score:4

you can use arrays and then join them using space.

<li key={index} classname={[activeclass, data.class, "main-class"].join(' ')}></li>

this will result in :

<li key={index} class="activeclass data.class main-class"></li>

score:4


create a function like this

function cssclass(...c) {
  return c.join(" ")
}

call it when needed.

<div classname={cssclass("head",style.element,"black")}><div>

score:4

using css modules (or sass modules) you can isolate your styling to a specific component too.

"component-scoped css allows you to write traditional, portable css with minimal side effects: gone are the worries of selector name collisions or affecting other components’ styles."

import * as styles from "./whatever.module.css"  // css version
import * as styles from "./whatever.module.scss" // sass version

<div classname={`${styles.class1} ${styles.class2}`}>
   insert your code here
</div>

ref1 ref2

score:5

i know this is a late answer, but i hope this will help someone.

consider that you have defined following classes in a css file 'primary', 'font-i', 'font-xl'

  • the first step would be to import the css file.
  • then

<h3 class = {` ${'primary'} ${'font-i'} font-xl`}> hello world </h3>

would do the trick!

for more info: https://www.youtube.com/watch?v=j5p9fhibvno&list=plc3y8-rfhvwgg3vayjghgnmodb54rxok3&index=20

score:5

this seem to work for me

<link classname={[classes.button, classes.buttonfirst]}>

score:7

just adding, we can filter out empty strings.

classname={[
    'read-more-box',
    this.props.classname,
    this.state.isexpanded ? 'open' : 'close',
].filter(x => !!x).join(' ')}

score:7

you can create an element with multiple class names like this, i tryed these both way, its working fine...

if you importing any css then you can follow this way : way 1:

import react, { component, proptypes } from 'react';
import csjs from 'csjs';
import styles from './styles';
import insertcss from 'insert-css';
import classnames from 'classnames';
insertcss(csjs.getcss(styles));
export default class foo extends component {
  render() {
    return (
      <div classname={[styles.class1, styles.class2].join(' ')}>
        { 'text' }
      </div>
    );
  }
}

way 2:

import react, { component, proptypes } from 'react';
import csjs from 'csjs';
import styles from './styles';
import insertcss from 'insert-css';
import classnames from 'classnames';
insertcss(csjs.getcss(styles));
export default class foo extends component {
  render() {
    return (
      <div classname={styles.class1 + ' ' + styles.class2}>
        { 'text' }
      </div>
    );
  }
}

**

if you applying css as internal :

const mystyle = {
  color: "#fff"
};

// react element using jsx
const myreactelement = (
  <h1 style={mystyle} classname="myclassname myclassname1">
    hello world!
  </h1>
);

reactdom.render(myreactelement, document.getelementbyid("app"));
.myclassname {
  background-color: #333;
  padding: 10px;
}
.myclassname1{
  border: 2px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-dom.production.min.js"></script>
<div id="app">
  
</div>

score:7

for more classes adding

... classname={`${classes.hello} ${classes.hello1}`...

score:8

it can be done with https://www.npmjs.com/package/clsx :

https://www.npmjs.com/package/clsx

first install it:

npm install --save clsx

then import it in your component file:

import clsx from  'clsx';

then use the imported function in your component:

<div classname={ clsx(classes.class1, classes.class2)}>

score:9

you could do the following:

<li key={index} classname={`${activeclass} ${data.class} main-class`}></li>

a short and simple solution, hope this helps.

score:10

maybe classnames can help you.

var classnames = require('classnames');
classnames('foo', {'xx-test': true, bar: false}, {'ox-test': false}); // => 'foo xx-test'

score:17


generally people do like

<div classname={  `head ${style.class1} ${style.class2}`  }><div>

or

<div classname={  'head ' + style.class1 + ' ' + style.class2 }><div>

or

<div classname={  ['head', style.class1 , style.class2].join(' ')  }><div>

but you can choose to create a function to do this job

function joinall(...classes) {
  return classes.join(" ")
}

then call it like:-

<div classname={joinall('head', style.class1 , style.class2)}><div>

score:20

vanilla js

no need for external libraries - just use es6 template strings:

<i classname={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>

score:21

i don't think we need to use an external package for just adding multiple classes.

i personally use

<li classname={`li active`}>stacy</li>

or

<li classname={`li ${this.state.isactive ? 'active' : ''}`}>stacy<li>

or

<li classname={'li ' + (this.state.isactive ? 'active' : '') }>stacy<li>

the second and third one in case you need to add or remove classes conditionally.

score:26

this is how you can do that with es6:

classname = {`
      text-right
      ${itemid === activeitemid ? 'active' : ''}
      ${anotherproperty === true ? 'class1' : 'class2'}
`}

you can list multiple classes and conditions and also you can include static classes. it is not necessary to add an additional library.

good luck ;)

score:46

you can create an element with multiple class names like this:

<li classname="class1 class2 class3">foo</li>

naturally, you can use a string containing the class names and manipulate this string to update the class names of the element.

var myclassnammes = 'class1 class2 class3';
...
<li classname={myclassnames}>foo</li>

score:93

this can be achieved with es6 template literals:

<input classname={`base-input-class ${class1} ${class2}`}>

(edited for clarity)

score:167

concat

no need to be fancy i am using css modules and it's easy

import style from '/css/style.css';

<div classname={style.style1+ ' ' + style.style2} />

this will result in:

<div class="src-client-css-pages-style1-selectionitem src-client-css-pages-style2">

in other words, both styles

conditionals

it would be easy to use the same idea with if's

const class1 = doihavesomething ? style.style1 : 'backupclass';

<div classname={class1 + ' ' + style.style2} />

es6

for the last year or so i have been using the template literals, so i feel its worth mentioning, i find it very expressive and easy to read:

`${class1} anotherclass ${class1}`

score:246

just use javascript.

<li classname={[activeclass, data.klass, "main-class"].join(' ')} />

if you want to add classes based keys and values in an object you can use the following:

function classnames(classes) {
  return object.entries(classes)
    .filter(([key, value]) => value)
    .map(([key, value]) => key)
    .join(' ');
}

const classes = {
  'maybeclass': true,
  'otherclass': true,
  'probablynotclass': false,
};

const myclassnames = classnames(classes);
// output: "maybeclass otherclass"

<li classname={myclassnames} />

or even simpler:

const isenabled = true;
const ischecked = false;

<li classname={[isenabled && 'enabled', ischecked && 'checked']
  .filter(e => !!e)
  .join(' ')
} />
// output:
// <li classname={'enabled'} />

score:567

i use es6 template literals. for example:

const error = this.state.valid ? '' : 'error'
const classes = `form-control round-lg ${error}`

and then just render it:

<input classname={classes} />

one-liner version:

<input classname={`form-control round-lg ${this.state.valid ? '' : 'error'}`} />

Related Query

More Query from same tag