1

I'm using react-starter-kit and building a list component that looks like this:

import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './CommandList.css';

const CommandList = () => {
  return (
    <ul className={s.commandList}>
      {data.commands.map((command, index) => (
        <li 
          key={index}
          className={s.commandListItem}>
          {command.command}
        </li>
      ))} 
    </ul>
  );
};

export default withStyles(s)(CommandList);

I'm trying to add an "active" class to my li item but not sure how to to that? I tried using the classnames library but not sure how to get the second class from my styles. When I just pass in the string "active", the styles don't get imported.

import cx from 'classnames';

<li className={cx(s.commandListItem, {'active': command.active })}>

My question is how would I do something like:

<li className={cx(s.commandListItem, {s.active: command.active })}>
Obscenity
  • 197
  • 12

3 Answers3

1

Figured it out. I was using classnames wrong. I needed to import classnames/bind.

import s from './CommandList.css';
import classnames from 'classnames/bind';

let cx = classnames.bind(s);

I can then just pass in the 'active' string like I wanted to:

<li className={cx(s.commandListItem, {'active': command.active })}>

The cx var name makes more sense now

Obscenity
  • 197
  • 12
0

<li className={cx(s.commandListItem, {[s.active]: command.active })}>
see [] object key notation

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
langpavel
  • 1,270
  • 12
  • 16
  • This works as well and is simpler than the answer I posted. I wonder now why someone would use the `bind` method over this? – Obscenity May 01 '18 at 20:47
0

className in React is String and you have to convert all the object into String

First create an array of classes which you want assign to class

Then convert array of class name to String

className={[s.commandListItem, 'active'].join('')}
Mohammad
  • 11
  • 1