Fluent UI/react-northstar Theming and Component Styling
Tags: webdev, javascript, microsoftteamsapps, react
Published: 2022-06-04 00:57:05

[Fluent UI](https://developer.microsoft.com/en-us/fluentui#/) is a collection of open source user interface components built by Microsoft. It has subsets of libraries for different platforms––React, Windows, iOS––to name a few. To incorporate Fluent UI into a React codebase, it is suggested to use the **[@fluentui/react](https://developer.microsoft.com/en-us/fluentui#/get-started/web)** package. However, if looking to build a Microsoft Teams app using Fluent UI, the **[@fluentui/react-northstar](https://fluentsite.z22.web.core.windows.net/0.62.0/)** package is preferred. At the time of writing, I needed to build an app to upload to Microsoft Teams app marketplace and was exploring v0.62 of @fluentui/react-northstar. Though I was able to find documentation on [theming](https://fluentsite.z22.web.core.windows.net/0.62.0/theming), I wasn’t able to find best practices on consuming the theme and using it in components. Therefore, I created my own solution using React context and I’ll share the gist of my solution in this post.

## Set up Theme

In order to use one theme across different components, we need to wrap the components that need theming with Fluent UI’s `Provider`. Additionally, we can import preset themes to build on top of. The themes available for import include `teamsTheme`, `teamsDarkTheme`, and a few other ones, you can refer to their [color scheme](https://fluentsite.z22.web.core.windows.net/0.62.0/color-schemes) for colors. I am going to use `teamsTheme` in my example. 

First I created a `ThemeProvider` to wrap all my components that need to consume the @fluentui/react-northstar library. In my custom theme, I added general theming values under the key `siteVariables`, and customized component styles under `componentVariables` and `componentStyles`, as suggested by the [docs](https://fluentsite.z22.web.core.windows.net/0.62.0/theming-examples#theme-level-styling).

```tsx
import React from 'react';
import deepMerge from 'deepmerge'; // a helper to deep merge objects: npmjs.com/package/deepmerge
import {
  Provider,
  teamsTheme,
} from '@fluentui/react-northstar';

interface Props {
  children: React.ReactNode;
}

const customTheme = {
  // Adding a few values that teamsTheme does not include, 
  // for example the spacing variable.
  siteVariables: {
    spacing: {
      unit: 8,
    },
    colorScheme: {
      myCustomBrand: {
        background: '#8662b9',
        label: '#757b94'
      },
    },
  },
  // Customizing the secondary color for all Buttons
  // Use this key to customize the behavior when using the
  // predefined variables, e.g. <Button secondary />
  componentVariables: {
    Button: {
      secondaryColor: 'orange',
    },
  },
  // Customizing the icon size for all MenuButtons
  componentStyles: {
    MenuButton: {
      icon: {
        fontSize: '10px',
      },
    },
  },
};

// Merging my custom theme with the preset teamsTheme
const theme = deepMerge(teamsTheme, customTheme);
export const ThemeContext = React.createContext(theme);

function ThemeProvider({ children }: Props) {
  return (
    <Provider theme={theme}>
      <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
    </Provider>
  );
};

export default ThemeProvider;
```

There we go, we now have a theme provider that provides theming to all child components and we've made the theme values accessible via React context.

### Accessing Theme & Styling Components

Some solutions for accessing theme and styling component are scattered on the Fluent UI official documentation, including using render props and component variables. Here're a couple examples:
    
```tsx
import React from 'react';
import { Provider, Flex, Header, Text, Button } from '@fluentui/react-northstar';

// Example for using Provider.Consumer and render props
export function Component() {
  return (
    <Provider.Consumer
      render={theme => {
        return (
          <Flex wrap gap="gap.smaller">
            <Header as="h2" content="Happy Summer"/>
            <Text content="It's watermelon time!"/>
          </Flex>
        );
      }}
    />
  );
}

// Example for using component level styling
export function AnotherComponent() {
    return (
	<div>
	    <Text>Get cool!</Text>
	    <Button
	        content="Unlock the summer"
            variables={{
              color: 'watermelon',
              backgroundColor: 'green',
              paddingLeftRightValue: 30,
            }}
	    />
	</div>
    )
}
```

I find the render prop API not as composable, and mixing it with the hook interface and passing theme into styles are messy. As for using the component level variables, it doesn’t automatically give us access to the theme, unless we wrap that component inside the theme consumer render props, which is again, not as neat.

Therefore, I created theme context in the `ThemeProvider` above. Then in my component, I can use `React.useContext` to access the theme. 

For styling my components, I’m using the `useStyles` pattern to apply styles using CSS-in-JS inside each component and allow passing theme as argument. The advantage of this solution is that accessing theme and passing it for styling is easy, and we can extend the `useStyles` pattern to accept other props and have business logic impact component styling if needed.

```tsx
// Example component
import React, { useContext } from 'react';
import { Provider, Flex, Header, Text } from '@fluentui/react-northstar';
import { ThemeContext } from './ThemeProvider'; // This is the ThemeProvider I created up top

function Component() {
  const themeContext = useContext(ThemeContext);
  const styles = useStyles(themeContext);

  return (
    <Flex wrap gap="gap.smaller" style={styles.root}>
      <Header as="h2" content="Happy Summer" style={styles.header}/>
      <Text content="It's watermelon time!" style={styles.description}/>
    </Flex>
  );
}

const useStyles = (theme) => ({
  root: {
      padding: theme.siteVariables.spacing.unit * 2
  },
  header: {
      backgroundColor: theme.siteVariables.colorScheme.myCustomBrand.background
  },
  description: {
      marginTop: theme.siteVariables.spacing.unit
  },
});

export default Component;
```

That’s it! Let me know what you think :)