Giedrius
Giedrius

Reputation: 139

Convert sass styles to inline styles object in react

I'm developing a component library which will be available as react components and css. To avoid redundant code and avoid react components to be dependent on stylesheets I would like to convert the sass styles I have to react inline styles something as following:

import buttonStyles from 'Button.scss'

...

<Button styles={buttonstyles.button__primary}>Submit</Button>

Where buttonstyles.button__primary would be the object of the react styles type for example:

buttonStyles = {
  button__primary: {
    marginLeft: '5px',
    background: 'red'
  },
  button__secondary: {...}
}

Is this possible to configure in webpack or any other way?

Upvotes: 2

Views: 910

Answers (1)

armin yahya
armin yahya

Reputation: 1506

1. config sass modules

if you created your project with create-react-app, only thing you need to do is adding module prefix to your filename.

rename Button.scss to Button.module.scss

but if not, you should set modules option to true inside your sass-loader.

// webpack.config.js

 module: {
    rules: [
      {
        test: /\.(sass|scss)$/,
        use: [
          {
            loader: 'sass-loader',
            options: {
              modules: true
            },
          },
        ],
      },
    ],
  },

2.change your jsx to following

import buttonStyles from 'Button.module.scss'


<Button className={buttonstyles.button__primary}>Submit</Button>

Upvotes: 0

Related Questions