SharePoint Framework - React Based OrgChart From SharePoint List

Overview
 
SharePoint Framework client web parts are targeted to develop business scenarios. Office 365 UI Fabric component offers seamless integration with Office 365 and offers a wide range of UI components. However, it does not offer Organization chart kind of controls yet. In these scenarios, we can make use of open source npm packages offerings.
 
In this article, we will explore organization chart control. We will use React JS to develop the example.
 
Create SPFx Solution
 
Open the command prompt. Create a directory for SPFx solution.
  1. md spfx-react-orgchart  
Navigate to the above-created directory.
  1. cd spfx-react-orgchart  
Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
Yeoman generator will present you with the wizard by asking questions about the solution to be created.

  
Solution Name: Hit Enter to have the default name (spfx-react-orgchart in this case) or type in any other name for your solution.
Selected choice: Hit Enter
 
Target for the component: Here, we can select the target environment where we are planning to deploy the client webpart, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
 
Place of files: We may choose to use the same folder or create a subfolder for our solution.
Selected choice: Same folder
 
Deployment option: Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
Selected choice: N (install on each site explicitly)
 
Type of client-side component to create: We can choose to create a client-side webpart or an extension. Choose the webpart option.
Selected choice: WebPart
 
Web part name: Hit Enter to select the default name or type in any other name.
Selected choice: OrgChartViewer
 
Web part description: Hit Enter to select the default description or type in any other value.
Selected choice: Organization chart with React
 
Framework to use: Select any JavaScript framework to develop the component. Available choices are (No JavaScript Framework, React, and Knockout)
Selected choice: React
 
Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running below command
  1. npm shrinkwrap  
In the command prompt type the below command to open the solution in code editor of your choice.
  1. code .   
Development Scenario
 
In this article, we will make use of SharePoint to store the hierarchical information for the chart and render it on SPFx web part.
 
A SharePoint list (named OrgChart) is used to store the hierarchical data. The schema of the list is as below.
 
The Parent column is a lookup on same OrgChart list’s Title column.
 
Let’s add some test data to our list.
 
NPM Packages
 
Organization Chart Control
 
At the time of writing this article, organization chart control is not available in Office 365 UI Fabric controls. We will explore the org chart control called react-orgchart (https://www.npmjs.com/package/react-orgchart)
 
Use the below command to install the org chart control
  1. npm install react-orgchart --save  
The --save option enables NPM to include the packages to dependencies section of the package.json file.
 
Array to Tree
 
The array-to-tree npm package helps to convert a plain array of nodes (with pointers to parent nodes) to a nested data structure. (https://www.npmjs.com/package/array-to-tree)
 
Use the below command to install the array-to-tree npm package.
  1. npm install array-to-tree --save  
Code the webpart
 
Open OrgChartViewer.tsx file under “\src\webparts\orgChartViewer\components\” folder to import the org chart control
  1. import OrgChart from 'react-orgchart';  
Open OrgChartViewer.module.scss file under “\src\webparts\orgChartViewer\components\” folder to import the CSS
  1. @import '~react-orgchart/index.css';  
Modify the render method to render the tree view
  1. public render(): React.ReactElement<IOrgChartViewerProps> {  
  2.   return (  
  3.     <div className={ styles.orgChartViewer }>  
  4.       <div className={ styles.container }>  
  5.         <div className={ styles.row }>  
  6.           <div className={ styles.column }>  
  7.   
  8.             <OrgChart tree={this.state.orgChartItems} NodeComponent={this.MyNodeComponent} />  
  9.   
  10.           </div>  
  11.         </div>  
  12.       </div>  
  13.     </div>  
  14.   );  
  15. }  
  16.   
  17. private MyNodeComponent = ({ node }) => {  
  18.   if (node.url) {  
  19.     return (  
  20.       <div className="initechNode">  
  21.         <a href={ node.url.Url } className={styles.link} >{ node.title }</a>          
  22.       </div>  
  23.     );      
  24.   }  
  25.   else {  
  26.     return (  
  27.       <div className="initechNode">{ node.title }</div>  
  28.     );      
  29.   }      
  30. }    
Implement method to read items from SharePoint list - OrgChart.
  1. private readOrgChartItems(): Promise<IOrgChartItem[]> {  
  2.   return new Promise<IOrgChartItem[]>((resolve: (itemId: IOrgChartItem[]) => void, reject: (error: any) => void): void => {  
  3.     this.props.spHttpClient.get(`${this.props.siteUrl}/_api/web/lists/getbytitle('${this.props.listName}')/items?$select=Title,Id,Url,Parent/Id,Parent/Title&$expand=Parent/Id&$orderby=Parent/Id asc`,  
  4.     SPHttpClient.configurations.v1,  
  5.     {  
  6.       headers: {  
  7.         'Accept''application/json;odata=nometadata',  
  8.         'odata-version'''  
  9.       }  
  10.     })  
  11.     .then((response: SPHttpClientResponse): Promise<{ value: IOrgChartItem[] }> => {  
  12.       return response.json();  
  13.     })  
  14.     .then((response: { value: IOrgChartItem[] }): void => {  
  15.       resolve(response.value);  
  16.     }, (error: any): void => {  
  17.       reject(error);  
  18.     });  
  19.   });      
  20. }  
Implement method to process the items and convert to OrgChart.
  1. private processOrgChartItems(): void {  
  2.   this.readOrgChartItems()  
  3.     .then((orgChartItems: IOrgChartItem[]): void => {  
  4.   
  5.       let orgChartNodes: Array<ChartItem> = [];  
  6.       var count: number;  
  7.       for (count = 0; count < orgChartItems.length; count++) {  
  8.         orgChartNodes.push(new ChartItem(orgChartItems[count].Id, orgChartItems[count].Title, orgChartItems[count].Url, orgChartItems[count].Parent ? orgChartItems[count].Parent.Id : undefined));  
  9.       }  
  10.   
  11.       var arrayToTree: any = require('array-to-tree');  
  12.       var orgChartHierarchyNodes: any = arrayToTree(orgChartNodes);  
  13.       var output: any = JSON.stringify(orgChartHierarchyNodes[0]);  
  14.   
  15.       this.setState({  
  16.         orgChartItems: JSON.parse(output)  
  17.       });  
  18.     });  
  19. }  
Test the WebPart
  1. On the command prompt, type “gulp serve”.
  2. Open SharePoint site.
  3. Navigate to /_layouts/15/workbench.aspx.
  4. Add the webpart to page.
  5. Edit the webpart and add list name (i.e. OrgChart) to web part property.



  6. The web part should display the data from the SharePoint list in an organization chart.

Troubleshooting
 
In some cases, SharePoint workbench (https://[tenant].sharepoint.com/_layouts/15/workbench.aspx) shows the below error although “gulp serve” is running.


Open the below URL in the next tab of the browser. Accept the warning message.
https://localhost:4321/temp/manifests.js
 
Summary
 
We can utilize the open source npm packages in SharePoint framework to easily develop complex controls like organization chart control.