reactjstypescriptbabel-plugin-react-css-modules

Passing css module as prop using babel-plugin-react-css-modules


I'm using babel-plugin-react-css-modules and need to pass classes via props to React components, as such:

import "./style.css"

// Works
<div styleName="a" />

// Does not work
<CustomComponent styleNameOverride="b" />

Inside CustomComponent, I take the prop and apply it where needed.

When it's not passed to styleName directly, the class name is not hashed. Is there a way I can achieve this with this plug-in, i.e. get the hashed class name and pass it as a prop?


Solution

  • I found a solution to this. By passing in the attributeNames option when configuring the plugin, I could specify the names of props that I want to be transformed, and what I want them to be transformed to.

    {
      "plugins": [
        ["@dr.pogodin/react-css-modules", {
          attributeNames: {
            altStyleName: "altClassName",
          }
        }]
      ]
    }