-
Notifications
You must be signed in to change notification settings - Fork 32
How to apply multiple classnames to an element
Nakul19 edited this page Sep 21, 2018
·
5 revisions
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 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>
);
}
}
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}`}>
{ this.props.children }
</div>
);
}
}