JSS array of selectors with same value

Viewed 1002

I created a global stylesheet for my React project that uses JSS. I'm very comfortable with CSS, SASS, and CSS Modules, but this is my first time using JSS.

The headings will all have the same margin. I don't want to type it multiple types or have it appear in the compiled styles more than once for maintainability and performance reasons. I'd also prefer not to have to add a class to all headings.

My JSS that doesn't work because of the array of selectors ([h1, h3, h4, h5, h6]):

const globalStyles = theme => ({
    '@global': {
        body: {
            fontFamily: ['Roboto', 'sans-serif'].join(','),
        },
        [h1, h3, h4, h5, h6]: {
            margin: '0 0 .35em 0'
        },
        h1: {
            fontSize: theme.typography.pxToRem(40),
            fontWeight: 600
        },
        h3: {
            fontSize: theme.typography.pxToRem(34),
            lineHeight: 1.75
        },
        h5: {
            fontSize: theme.typography.pxToRem(28),
            lineHeight: 'normal'
        },
        h6: {
            fontSize: theme.typography.pxToRem(20),
            lineHeight: 'normal'
        }
    }
})

export default globalStyles

I'm trying to achieve the following output:

body {
    font-family: Roboto, sans-serif
}
h1, h3, h4, h5, h6 {
    margin: 0 0 .35em 0
}
h1 {
    font-size: 2.5rem;
    font-weight: 600;
}
h3 {
    font-size: 2.125rem;
    line-height: 1.75;
}
h5 {
    font-size: 1.75rem;
    line-height: normal;
}
h6 {
    font-size: 1.25rem;
    line-height: normal;
}

Is this possible with JSS? I've done some reading on JSS and I haven't found a solution.

2 Answers

Just place them into comma-separated string, kind of like you would in regular old fashioned CSS:

'@global': {
  'h1, h3, h4, h5, h6': {
     margin: "0 0 .35em 0"
  }
}

It's possible to use eg. […].join(', ') to construct the string, of course (like you did with font-family above).

[h1, h3, h4, h5, h6] is a wrong javascript syntax, not specific to JSS. You are allowed to have only one variable in a property. so you can write [h] where h is a variable that you have to define in advance or directly as a string literal ['h1'], which doesn't make much sense since you can use it directly as a property. If you want you can express it also like this if you really need those to be variables. It works because the inner array will be casted to a string, which by default converts to comma separate values in js: [1,2].toString()

  const h1 = 'h1'
  const h2 = 'h2'

  '@global': {
    [[h1, h2]]: {
      color: 'red'    
    }
  }
Related