Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/koltyakov/spfx-styled-components-sample
Styled Components and SPFx theming sample (SIG 2020/06/04)
https://github.com/koltyakov/spfx-styled-components-sample
css-in-js sample sharepoint spfx styled-components themes
Last synced: 30 days ago
JSON representation
Styled Components and SPFx theming sample (SIG 2020/06/04)
- Host: GitHub
- URL: https://github.com/koltyakov/spfx-styled-components-sample
- Owner: koltyakov
- Created: 2020-04-19T12:49:32.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2023-07-11T13:54:06.000Z (over 1 year ago)
- Last Synced: 2024-04-14T23:12:09.739Z (8 months ago)
- Topics: css-in-js, sample, sharepoint, spfx, styled-components, themes
- Language: TypeScript
- Homepage:
- Size: 1.52 MB
- Stars: 3
- Watchers: 3
- Forks: 0
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## SPFx Themes and Styled Components (CSS in JS) sample
The sample shows the basic setup for consuming SPFx themes with [Styled Components](https://styled-components.com/).
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.
```typescript
private themeProvider: ThemeProvider;
private themeVariant: IReadonlyTheme | undefined;// Binding theme provider within SPFx webpart
protected onInit(): Promise {
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](./src/webparts/themed/index.tsx)
## 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.
```typescript
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](src/webparts/themed/components/Styles.ts)
## Debug
```bash
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!