Accordion in Fluent UI / Office UI Fabric

Fluent UI / Office UI Fabric does not provide any Accordion control. But you can create your Accordion using the Fluent UI controls itself. Below is the code for Accordion control that I have created in React. You can also see it action on CodeSandbox.

import * as React from "react";
import {
  DefaultPalette,
  AnimationClassNames
} from "office-ui-fabric-react/lib/Styling";
import {
  IconButton,
  initializeIcons,
  Stack,
  IStackItemStyles,
  IStackStyles
} from "office-ui-fabric-react";

initializeIcons();

export class Accordion extends React.Component<IAccordionProps, {}> {
  private accordionHeader: IStackItemStyles = {
    root: {
      background: DefaultPalette.neutralLighter,
      padding: 5,
      cursor: "pointer"
    }
  };
  private accordion: IStackStyles = {
    root: {
      borderStyle: "solid",
      borderWidth: 1,
      borderColor: DefaultPalette.neutralTertiary
    }
  };
  private accordionConent: IStackStyles = {
    root: {
      padding: 10
    }
  };

  constructor(props: IAccordionProps, public state: any) {
    super(props);

    this.state = {
      content: false
    };
  }

  private showContent = (e) => {
    this.setState({
      content: !this.state.content
    });
  };

  public componentDidMount() {}

  public render(): React.ReactElement<IAccordionProps> {
    return (
      <>
        <Stack horizontal={false} styles={this.accordion}>
          <Stack.Item styles={this.accordionHeader}>
            <Stack horizontal={true} onClick={this.showContent}>
              <Stack.Item>
                <IconButton
                  iconProps={{
                    iconName: this.state.content
                      ? "ChevronDown"
                      : "ChevronRight"
                  }}
                />
              </Stack.Item>
              <Stack.Item align="center">{this.props.header}</Stack.Item>
            </Stack>
          </Stack.Item>
          {this.state.content && (
            <Stack.Item
              className={AnimationClassNames.slideDownIn20}
              styles={this.accordionConent}
            >
              {this.props.children}
            </Stack.Item>
          )}
        </Stack>
      </>
    );
  }
}

interface IAccordionProps {
  header: string;
}

You can use the control in your code with below sample code.

<Accordion header="Lorem Ipsum">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.
    </Accordion>
Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply