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.
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();
}
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'};
}
`;
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!