0

I have a SharePoint Online site with green theme color currently set. In my SPFx webpart I want to be able to get the current theme color (primary, secondary and tertiary) in TypeScript code. Below are the approaches I tried.

Approach 1

import { getTheme, loadTheme } from '@uifabric/styling';
const theme = getTheme();
const pivotItemStyle: React.CSSProperties = {
    borderColor: theme.palette.themePrimary,
    borderWidth: "1px",
    borderStyle: "solid"
};

But theme.palette.themePrimary return blue color rather than green.

Approach 2

I tried using DefaultPalette.themePrimary but it still gives me blue color.

This link gives CSS equivalents like

.button {
  /* ... */
  background-color: "[theme: themePrimary, default: #0078d7]";
  border-color: "[theme: themePrimary, default: #0078d7]";
  /* ... */
}

How can I get current site theme color in SPFx webpart using TypeScript?

  • Did you followed all the steps given in here? – Ganesh Sanap Nov 5 '19 at 9:44
1

As per the official documentation, Use theme colors in your SharePoint Framework customizations,

When you scaffold a new SharePoint Framework client-side web part, by default, it uses the fixed blue palette.

And you need to follow the steps described at Use theme colors in your customizations with the necessary adjustments to have the web part use theme colors instead.

Additional references:

  1. How to use Theme Colors in SPFX Web Parts.
  2. SharePoint themes and colors.

Update:

Additionally, we can get the global variable __themeState__ from SharePoint Context which contains all defined color and slots used by the theme. You can leverage that to use it in your typescript file.

Check below references on how to use __themeState__:

  1. How to get the current theme in a spfx webpart using the new ts based styling approach?
  2. How to use Theme Colors in SPFX Web Parts - Check "Bonus Content" section.
  • I went through all the links in your answer. They all seem to give me the CSS option. I need to be able to access theme color in TypeScript code. Is there any way to fetch that? – Naveen Nov 5 '19 at 10:06
  • Sorry, I am not getting why you need this in ts file? you can create a class in CSS file and apply those classes to your html elements in ts file. – Ganesh Sanap Nov 5 '19 at 10:14
  • In the example in link, we need to add style in TypeScript for tabs inside Pivot. For this scenario I am unable to figure out how to add classes. Any idea how can I achieve this? – Naveen Nov 6 '19 at 3:10
  • As I mentioned in Update section in my answer, you can leverage the __themeState__ to get the current theme and colors used in SharePoint site and you can use them in your webpart. – Ganesh Sanap Nov 6 '19 at 4:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.