Search code examples
cssreactjsreact-css-modules

How to use @apply in a react component with css modules


I've got this in a global style.css:

:root {
    --font: {
        font-family: "Source Sans Pro", sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
    }
}

... and this in a react component's style.css:

.rightnav {
    @apply --font;
    float: right;
    color: white;
}

In the component itself:

import React from "react"
import cssModules from "react-css-modules"
import style from "./style.css"

render() {
  return (
        <ul>
          <li className={style.rightnav}>Blog</li>
        </ul>
  )
}

I get an error: No custom properties set declared for font.


Solution

  • You've got to import the global stylesheet into the local one. Because postcss-apply has no way to know about that global file while parsing the local one. So it's a good idea to have a partial with only custom properties and custom property sets declarations.

    You probably want something like postcss-import

    @import 'path/to/variables.css';
    
    .rightnav {
      @apply --font;
      float: right;
      color: white;
    }