React Fluent UI Theming

8.1k Views Asked by At

I´m currently developing an App for MS Teams. After getting used to the MS UI library (now it´s called fluent-ui) everything is starting to get assembled together. Since I want to provide my users a "built-in" expirience, I want to use the native themes and styles which microsoft also uses.

As a foundation, I use @fluentui/react-northstar which is offically teams supported check here. And the best is, it has built-in themes for teams on board. Awesome.

So far so good. I also want to show some lists where data of the current logged in user is shown. To do so, I wanted to use the Shimmer-DetailsList. The problem here is that I cannot apply the themes from @fluentui/react-northstar which is driving me totally crazy. Has anybody a good idea what I can do here? This is driving me totally bonkers that the provided UIs are not compatible with each other or maybe I´m not using the right approach.

I can also show some code if wanted but at this state I´m just trying to understand.

Thanks a lot for your help guys!

Best, Tom

Update: Ok might get a little bit complicated but I try my best to show my code. I will shorten unecessary parts. Code is written for React.

Index.js I determine here which theme the user has currently active which can be done through window.location.search. The theme is then also passt to App.js as a prop.

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider, themes } from '@fluentui/react-northstar'

...

const teamsTheme =  updateTheme(getQueryVariable('theme'));
//const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const rootElement = document.getElementById('root');
console.log("theme in index: " + teamsTheme);
ReactDOM.render(
    <Provider theme={teamsTheme}>
        <App theme={teamsTheme}/>
    </Provider>,
    rootElement
);

App.js In App.js i determine some general things. I check if Teams can authenticate the user and also if the user has accepted TOU on first use (query against my API). If everything is fine I render a custom component called content, where I also pass the theme as a prop. I´ll leave general function declarations because they are currently not causing the problem.

import React, { Component } from 'react';
import TouService from "./services/touService";
import { Stack } from 'office-ui-fabric-react'
import { Loader } from '@fluentui/react-northstar'
import "./css/settings.css"
import Content from "./components/Content"
import AcceptTou from "./components/AcceptTou"
const microsoftTeams = require('@microsoft/teams-js');

export default class App extends Component {
    static displayName = App.name;

    constructor(props) {
        super(props)

        this.touService = new TouService();

        this.state = {
            userIsAuthenticated: false,
            authenticationLoading: true,
            authMessage: "Unauthorized!!!",
            currentUser: "",
            tokenString: "",
            touAccepted: false,
            touLoading: true
        };

        **some functions here**

    componentDidMount() {
        this.initializeTeams();
    }

    render() {
        const loading = (this.state.authenticationLoading || this.state.touLoading || (this.state.touAccepted === false)) ?
            <div>
                <br />
                <Loader label='Loading...' />
                <br />
            </div> :
            <Content theme={this.props.theme}/>;

        const tou = (this.state.userIsAuthenticated && !this.state.authenticationLoading && !this.state.touLoading && !this.state.touAccepted) &&
            <AcceptTou currentUser={this.state.currentUser} touAccepted={this.state.touAccepted} theme={this.props.theme} onTouChange={this.touAcceptedChanged}/>;

        //console.logconsole.log(this.state);

        return (
            <Stack
                horizontalAlign="center"
                verticalFill
                styles={{
                    root: {
                        width: this.width,
                        height: this.height,
                        margin: '0 auto',
                        textAlign: 'center',
                        color: '#605e5c'
                    }
                }}>
                {loading}
                {tou}
            </Stack>
        );
    }
}

Content.js In content I determine my general content for the layout of the page.

import React, { Component } from 'react';
import AssetMenu from "../UI/AssetMenu"
import Layout from "../UI/Layout"
import ToolbarMenu from '../UI/ToolbarMenu';
import ShimmerApplicationExample from "./List"

export default class Content extends React.Component {
    constructor(props) {
        super(props)
        console.log("theme in content.js: " + this.props.theme);
    }
    render() {
        const content = "my Content";
        return (
            <Layout header={<AssetMenu />} toolbar={<ToolbarMenu />} content={<ShimmerApplicationExample theme={this.props.theme}/>} />
        );
    }
}

Layout.js handles the general layout for the page. which is currently not ideal because I´m still learning but this can be done later.

import React from 'react';
import { Flex, Segment, Divider } from '@fluentui/react-northstar'

export default class Layout extends React.Component {

    //<Grid columns="repeat(3, 1fr)" rows="50px 150px 50px">
    render() {
        return (
            <Flex column fill>
                {this.props.header}
                {this.props.toolbar}
                <Segment content={this.props.content} />
            </Flex>
        );
    }
}

ToolbarMenu.js provides a Toolbar for the user to interact or create some content. But has no functionality yet.

import React from 'react';
import { Menu, menuAsToolbarBehavior } from '@fluentui/react-northstar';

const items = [
    {
        key: 'add',
        icon: {
            name: 'add',
            outline: true,
        },
        content: "New",
        'aria-label': 'add',
    },
    {
        key: 'edit',
        icon: {
            name: 'edit',
            outline: true,
        },
        content: "Edit",
        'aria-label': 'Edit Tool',
    },
    {
        key: 'delete',
        icon: {
            name: 'trash-can',
            outline: true,
        },
        content: "Delete",
        'aria-label': 'Delete Tool',
    },
];

export default class ToolbarMenu extends React.Component {
    render() {
        return (
            <Menu
                defaultActiveIndex={0}
                items={items}
                primary
                iconOnly
                accessibility={menuAsToolbarBehavior}
                aria-label="Compose Editor"
            />
        )
    }
}

List.tsx should provide the Detailslist for the user content. Here is where the problem currently is. The code is basically the example from MS here:. Except I tried to use my theme from Index.js here in the list which doesnt work.

import * as React from 'react';
import { Async } from 'office-ui-fabric-react/lib/Utilities';
import { createListItems, IExampleItem } from '@uifabric/example-data';
import { IColumn, buildColumns, SelectionMode, Toggle } from 'office-ui-fabric-react/lib/index';
import { ShimmeredDetailsList } from 'office-ui-fabric-react/lib/ShimmeredDetailsList';

const fileIcons: { name: string }[] = [
  { name: 'accdb' },
  { name: 'csv' },
  { name: 'docx' },
  { name: 'dotx' },
  { name: 'mpt' },
  { name: 'odt' },
  { name: 'one' },
  { name: 'onepkg' },
  { name: 'onetoc' },
  { name: 'pptx' },
  { name: 'pub' },
  { name: 'vsdx' },
  { name: 'xls' },
  { name: 'xlsx' },
  { name: 'xsn' }
];

const ITEMS_COUNT = 200;
const INTERVAL_DELAY = 2500;

let _items: IExampleItem[];

export interface IShimmerApplicationExampleState {
  items: IExampleItem[]; // DetailsList `items` prop is required so it expects at least an empty array.
  columns?: IColumn[];
  isDataLoaded?: boolean;
}

interface IShimmerListProps {
  theme?: any;
}

export default class ShimmerApplicationExample extends React.Component<IShimmerListProps, IShimmerApplicationExampleState> {
  private _lastIntervalId: number = 0;
  private _lastIndexWithData: number = 0;
  private _async: Async;

  constructor(props: {}) {
    super(props);

    this.state = {
      items: [],
      columns: _buildColumns(),
      isDataLoaded: false
    };

    this._async = new Async(this);
    console.log("theme in shimmer list consturctor: " + this.props.theme);
  }

  public componentWillUnmount(): void {
    this._async.dispose();
  }

  public render(): JSX.Element {
    const { items, columns, isDataLoaded } = this.state;
    const theme = this.props.theme;
    return (
      <div>
        <Toggle
          theme = {theme}
          label="Toggle to load content"
          style={{ display: 'block', marginBottom: '20px' }}
          checked={isDataLoaded}
          onText="Content"
          offText="Shimmer"
        />
        <div>
          <ShimmeredDetailsList
            theme = {theme}
            setKey="items"
            items={items}
            columns={columns}
            selectionMode={SelectionMode.none}
            enableShimmer={!isDataLoaded}
            ariaLabelForShimmer="Content is being fetched"
            ariaLabelForGrid="Item details"
            listProps={{ renderedWindowsAhead: 0, renderedWindowsBehind: 0 }}
          />
        </div>
      </div>
    );
  }

  private _loadData = (): void => {
    this._lastIntervalId = this._async.setInterval(() => {
      const randomQuantity: number = Math.floor(Math.random() * 10) + 1;
      const itemsCopy = this.state.items!.slice(0);
      itemsCopy.splice(
        this._lastIndexWithData,
        randomQuantity,
        ..._items.slice(this._lastIndexWithData, this._lastIndexWithData + randomQuantity)
      );
      this._lastIndexWithData += randomQuantity;
      this.setState({
        items: itemsCopy
      });
    }, INTERVAL_DELAY);
  };

  private _onLoadData = (ev: React.MouseEvent<HTMLElement>, checked: boolean): void => {
    if (!_items) {
      _items = createListItems(ITEMS_COUNT);
      _items.map((item: IExampleItem) => {
        const randomFileType = this._randomFileIcon();
        item.thumbnail = randomFileType.url;
      });
    }

    let items: IExampleItem[];
    const randomQuantity: number = Math.floor(Math.random() * 10) + 1;
    if (checked) {
      items = _items.slice(0, randomQuantity).concat(new Array(ITEMS_COUNT - randomQuantity));
      this._lastIndexWithData = randomQuantity;
      this._loadData();
    } else {
      items = [];
      this._async.clearInterval(this._lastIntervalId);
    }
    this.setState({
      isDataLoaded: checked,
      items: items
    });
  };

  private _onRenderItemColumn = (item: IExampleItem, index: number, column: IColumn): JSX.Element | string | number => {
    if (column.key === 'thumbnail') {
      return <img src={item.thumbnail} />;
    }

    return item[column.key as keyof IExampleItem];
  };

  private _randomFileIcon(): { docType: string; url: string } {
    const docType: string = fileIcons[Math.floor(Math.random() * fileIcons.length) + 0].name;
    return {
      docType,
      url: `https://static2.sharepointonline.com/files/fabric/assets/brand-icons/document/svg/${docType}_16x1.svg`
    };
  }
}

function _buildColumns(): IColumn[] {
  const _item = createListItems(1);
  const columns: IColumn[] = buildColumns(_item);

  for (const column of columns) {
    if (column.key === 'thumbnail') {
      column.name = 'FileType';
      column.minWidth = 16;
      column.maxWidth = 16;
      column.isIconOnly = true;
      column.iconName = 'Page';
      break;
    }
  }

  return columns;
}


For better undestanding: Microsoft says that this package (fluentui/react-northstar) is best for Teams support because it has everything and also has integrated themes for teams but it does not provide a DetailsList as office-ui-react (which should be in fact almost the same library?) and they are also not compatible to each other?

I have no idea what I did wrong and if possible I would rather not define my own themes than using preexisting ones.

0

There are 0 best solutions below