SCSS modules for your SPFx component

Warning: This recipe is about SCSS modules for your SPFx component and does not contain anything that has not been published elsewhere. Still, for the sake of completeness (and as a “note to self”) I think it makes sense to keep the following in mind, when writing your own SPFx Webpart and you want to add custom styles in the form of SCSS modules to it.

Create SCSS modules for your SPFx component

By default, the build chain for an SPFx Webpart has already built-in support for SASS. To use it you can simply add new SCSS files to your (src\components) folder and make sure the name ends with “.module.scss”. So if you have a component file “MyComponent.tsx” you can add a SASS file with the name “MyComponent.module.scss”. When building your project, the SASS module will be automatically processed and a TypeScript representation of your styles named “MyComponent.module.scss.ts” will be created for you.

Use SCSS modules in your SPFx component

To use the module that was created you can now simply import your SCSS module and assign it to a property as follows:

import styles from './MyComponent.module.scss';
...
public render(): React.ReactElement<any> {
    return(
        <div className={styles.buttonRight}>
    );
}

Final thoughts

I believe it makes sense to create a folder structure inside your components folder and apply some naming convention. Under the hood, however, such conventions are not so important. Building all SASS modules will create intermediate CSS files and in the end this will be merged into one file. More detailed information on this topic can be found (here)[https://github.com/SharePoint/sp-dev-docs/blob/master/docs/spfx/css-recommendations.md].

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: