isomorphic-style-loader - How to add an "active" class

413 Views Asked by At

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 })}>
3

There are 3 best solutions below

1
langpavel On BEST ANSWER

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

0
Obscenity On

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

0
Mohammad On

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('')}