rtsao / csjs

:sparkles: Modular, scoped CSS with ES6
MIT License
576 stars 32 forks source link

How should I write to apply multiple classname? #22

Closed bokuweb closed 8 years ago

bokuweb commented 8 years ago

How should I write to apply multiple classname? I want to apply multi classname to single element.

module.exports = csjs`
    .foo  {
      font-size: '20px';
    }

    .bar {
      color: red;
    }
import React, { Component, PropTypes } from 'react';
import csjs from 'csjs';
import styles from './styles';
import insertCss from 'insert-css';

insertCss(csjs.getCss(styles));

export default class Foo extends Component {
  render() {
    return (
      <div className={styles.foo styles.bar}>
        { this.props.children }
      </div>
    );
  }
}
rtsao commented 8 years ago

You have a few options.

The most idiomatic "CSS Modules" approach would to create a single class that is a composition of everything you would want to apply to a given element. Since there's scoping, you can create lots of classes without worrying about name collisions.

For example:

module.exports = csjs`
    .foo  {
      font-size: '20px';
    }

    .bar {
      color: red;
    }

    .both extends .bar, .foo {}
`
import React, { Component, PropTypes } from 'react';
import csjs from 'csjs';
import styles from './styles';
import insertCss from 'insert-css';

insertCss(csjs.getCss(styles));

export default class Foo extends Component {
  render() {
    return (
      <div className={styles.both}>
        { this.props.children }
      </div>
    );
  }
}

Alternatively, you can use something like the https://github.com/JedWatson/classnames module to combine classes into a single string.

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={classNames({[styles.foo]: true, [styles.bar]: true})}>
        { this.props.children }
      </div>
    );
  }
}

Or just concat the names together:

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.foo, styles.bar].join(' ')}>
        { this.props.children }
      </div>
    );
  }
}
bokuweb commented 8 years ago

@rtsao Thank you for answering!! csjs is a cool!!

ptim commented 7 years ago

@rtsao your answer would make a great wiki / docs page :) thanks

neurosnap commented 7 years ago

https://github.com/rtsao/csjs/wiki/How-to-apply-multiple-classnames-to-an-element