'Two classes on single react HTML element

I feel like there is a simple answer here, but I'm not finding it -

In my react header I import my stylesheet under 'styles' and as such refers to css classes as

<div className={styles.selectorname}>

But I can't figure out, with this notation, how to declare multiple styles on one element. Example that doesn't work:

<div className={styles.selectorname1} {styles.selectorname2}>

Any ideas?



Solution 1:[1]

If those are class names, then you can do with template strings (``)

<div className={`${styles.selectorname1} ${styles.selectorname2}`}>

Solution 2:[2]

You can use spread operator to combine different style objects. For an example, let's have a look at this css file which has few declarations.

.myColor {
  color: DodgerBlue;
}

.myFont {
  font-family: Arial;
  text-align: center;
}

We can combine these using the following syntax.

<div style={{...styles.myColor, ...styles.myFont}}>

Similarily, you can use the following code to combine those styles. The styles can be from two different files as well.

<div style={{...styles.selectorname1, ...styles.selectorname2}}>

Note: The ... which we are using is called spread operator. Read more on spread syntax here.

Solution 3:[3]

Are you sure you used quotes ? Like such as :

<div className="{styles.selectorname1} {styles.selectorname2}">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siva K V
Solution 2 Amit
Solution 3 Ridvan BEAU