Identify current theme of MS Teams in react bases component

312 Views Asked by At

I am working on the MS Teams app where I have a page in which I want to identify current MS Teams theme (default, dark or high contrast).

I have added this https://www.npmjs.com/package/msteams-react-base-component dependency where it explaining how we can extract teams theme. Below is my code snippet which always giving me themeString as default.

export default function FioriTab(): ReactElement {
    const [{ themeString }] = useTeams({});

    useEffect(() => {
        console.log(themeString)
    }, [themeString]);
}

Any idea what I am doing wrong here.

I tried adding setThemeHandler which also returning theme as undefined.

enter image description here

1

There are 1 best solutions below

14
On

With respect to Wictor, I don't know much about that library you're referencing, but according to the docs on this one (https://github.com/OfficeDev/TeamsFx), it's based on his anyway and probably better maintained, considering. It also has a useTeams hook that aims to do the same thing.

If you have a totally new solution anyway, perhaps best is to start with the Teams Toolkit in any case, as it will scaffold this for you.

On a separate but related note, see that useTeams also allows you to send a theme handler - this is important to handle theme changes while a user is using your apps - Teams will let you know the theme has changed so you can respond accordingly.

With regards your main question, the reason you're always seeing the "default" theme, from what I can see in the code for this framework, is because of the asynchronous setting of the theme state over here. It can be easily solved, per my suggestion above, of implementing the theme change event handler that you need to implement anyway. Basically, you should have something like this:

export default function FioriTab(): ReactElement {
  const [themeString, setThemeString] = useState<string>("default");

  const [{ inTeams }] = useTeams({}, (theme: string | undefined) => {
    setThemeString(theme || "default");
  });

...