Home > Mobile >  Two classes on single react HTML element
Two classes on single react HTML element

Time:05-07

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?

CodePudding user response:

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.

CodePudding user response:

Are you sure you used quotes ? Like such as :

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

CodePudding user response:

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

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