Obscenity
Obscenity

Reputation: 217

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

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

Upvotes: 1

Views: 412

Answers (3)

Mohammad
Mohammad

Reputation: 11

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

Upvotes: 0

langpavel
langpavel

Reputation: 1330

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

Upvotes: 0

Obscenity
Obscenity

Reputation: 217

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 🙃

Upvotes: 1

Related Questions