SharePoint 2016 Logo

When I started to work with SPFX solutions for SharePoint, I couldn’t understand how to load external CSS files. I came up with one solution, but it was a crutch. I did it with embedding <styles> tag into JSX. It looked like this:

    <div>
      <style>{`
.mbsc-timeline-header-week-text {
  width: auto;
  text-align: center; margin: 1px; padding: 1px;
  font-size: 10px;
 }
 .mbsc-timeline-header-column,   .mbsc-timeline-column {
  width: auto; min-width: 34px;
}
`}
      </style>
….
</div>

There’s a good way to load external CSS into SPFX webparts with SPComponentLoader. It allows you to load css from assets directory of your solution, float SharePoint document library or from any external site (CDN, for example).


import { SPComponentLoader } from '@microsoft/sp-loader';
....

and modify onInit method with loading CSS

  protected onInit(): Promise<void> {
    return this._getEnvironmentMessage().then(message => {

      // eslint-disable-next-line @typescript-eslint/no-var-requires
      const cssYet = require('./assets/styles.css')
      SPComponentLoader.loadCss(cssYet)
      //SPComponentLoader.loadCss(this.context.pageContext.web.serverRelativeUrl + '/SiteAssets/yet-another-react-lightbox-styles.css');
      this._environmentMessage = message;
    });
  }