Skip to content

koltyakov/spfx-styled-components-sample

Repository files navigation

SPFx Themes and Styled Components (CSS in JS) sample

The sample shows the basic setup for consuming SPFx themes with Styled Components.

Styled Components is a modern and extremely popular way of providing CSS in JS.

Binding the styles using ThemeProvider

ThemeProvider allows tracking styles changes and getting current theme variants.

private themeProvider: ThemeProvider;
private themeVariant: IReadonlyTheme | undefined;

// Binding theme provider within SPFx webpart
protected onInit(): Promise<void> {
  this.themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
  this.themeVariant = this.themeProvider.tryGetTheme();
  this.themeProvider.themeChangedEvent.add(this, this.handleThemeChangedEvent);
  return super.onInit();
}

// Theme change handler event
private handleThemeChangedEvent(args: ThemeChangedEventArgs) {
  this.themeVariant = args.theme;
  this.render();
}

Full code

Styled components

The basic way is to bypass theme variant down to styled components wrapper then using properties callbacks with consumption of corresponding theme variables.

import styled from 'styled-components';

import { IReadonlyTheme } from '@microsoft/sp-component-base';

export const Styles = styled.div<{ theme: IReadonlyTheme; }>`
  .themePrimary-background {
    // ...
    background: ${({ theme }) => theme.palette.themePrimary || '#ccc'};
    color: ${({ theme }) => theme.palette.white || '#fff'};
  }
`;

Full code

Debug

npm run start

Open SharePoint page and add query string parameter for debug (?debug=true&noredir=true&debugManifestsFile=https://localhost:4321/temp/manifests.js).

Add Themed web-part and apply code changes to see the effect.

Happy coding!

About

Styled Components and SPFx theming sample (SIG 2020/06/04)

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published