Home > Software design >  Multiple react component className's
Multiple react component className's

Time:05-30

We have a react project where styles are written like this:

import styles from 'styles/sidebar.module.scss'
...
<div className={styles.sidebar}>Hello</div>

I can't for the life of me figure how to include two classes with this syntax, e.g.:

<div className={styles.sidebar} {styles.scroll}>Hello</div>
<div className={styles.sidebar, styles.scroll}>Hello</div>
<div className={styles.sidebar}, {styles.scroll}>Hello</div>
<div className={styles.sidebar}{styles.scroll}>Hello</div>

Nothing from the above works, not sure what else to try. Any help is much appreciated!

CodePudding user response:

just like this, because they are just strings:

<div className={`${styles.sidebar} ${styles.scroll}`}>Hello</div>

CodePudding user response:

You can use template literal

<div className={`${styles.sidebar} ${styles.scroll}`}>Hello</div>

CodePudding user response:

Using a utility lib called classnames could be a good approach, especially if you need to apply some conditions on whether including some of the class names or not. Here is an example;

var classNames = require('classnames');

class Button extends React.Component {
  // ...
  render () {
    var btnClass = classNames({
      'btn': true,
      'btn-pressed': this.state.isPressed,
      'btn-over': !this.state.isPressed && this.state.isHovered
    });
    return <button className={btnClass}>{this.props.label}</button>;
  }
}
  • Related