Using JavaScript Gantt Chart in SharePoint Web Part for Effective Project Management: Part 2
Tags: development, gantt, javascript, sharepoint
Published: 2023-02-07 12:50:58

---
title: Using JavaScript Gantt Chart in SharePoint Web Part for Effective Project Management: Part 2
published: true
date: 2023-02-07 11:55:46 UTC
tags: development, gantt, javascript, sharepoint
canonical_url: https://www.syncfusion.com/blogs/post/using-javascript-gantt-chart-in-sharepoint-web-part-for-effective-project-management-part-2.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/raqkhr3hdv774ononhfq.png
---
This is a follow-up to our previous blog, [Using JavaScript Gantt Chart in SharePoint Web Part for Effective Project Management: Part 1](https://www.syncfusion.com/blogs/post/using-javascript-gantt-chart-in-sharepoint-web-parts-for-effective-project-management-part-1.aspx "Blog: Using JavaScript Gantt Chart in SharePoint Web Parts for Effective Project Management: Part 1"), where we explained integrating the Syncfusion [JavaScript Gantt Chart](https://www.syncfusion.com/javascript-ui-controls/js-gantt-chart "Syncfusion JavaScript Gantt Chart") in a [SharePoint](https://www.office.com/sharepoint "SharePoint") web part.

Now, in this blog, we’ll see how to bind SharePoint list data to the JavaScript Gantt Chart and save the data changes made in the Gantt Chart back to the SharePoint list.

There are only two steps to do this:

1. **Data binding** : Read and bind the SharePoint list data to the JavaScript Gantt Chart.
2. **Edit operation** : Update the edited data from the Gantt Chart to the SharePoint list.

Let’s get started!

## Data binding

A [list](https://support.microsoft.com/en-us/office/introduction-to-lists-0a1c3ace-def0-44af-b225-cfa8d92c52d7 "Introduction to Microsoft Office lists") is a collection of data displayed in rows and columns. SharePoint stores and displays information in the form of a list. These are like databases that we use to store information and build reports.

### Step 1: Prepare SharePoint list data

You can bind an existing list from your SharePoint page or [create a new list](https://support.microsoft.com/en-us/office/create-a-list-0d397414-d95f-41eb-addd-5e6eff41b083 "Create a SharePoint list documentation") and bind it to the JavaScript Gantt Chart. To do so, follow these steps:

1. Create the list data with a unique field through which the Syncfusion JavaScript Gantt Chart can identify child and parent records. For instance, let’s use the data in the following code example where the **TaskID** field is a unique field and **ParentID** in some records denotes that they are child records to the **TaskID** value that equals the **ParentID** field value.
```js
var projectData = [
    { 'TaskID': 1, 'TaskName': 'Planning', 'StartDate': new Date('02/23/2017'), 'Duration': 5 },
 
    { 'TaskID': 2, 'TaskName': 'Plan timeline', 'StartDate': new Date('02/23/2017'), 'Duration': 5, 'parentID': 1 },
 
    { 'TaskID': 3, 'TaskName': 'Plan budget', 'StartDate': new Date('02/23/2017'), 'Duration': 0, 'parentID': 1, },
 
    { 'TaskID':4, 'TaskName': 'Design', 'StartDate': new Date('02/10/2017'), 'Duration': 3 },
 
    { 'TaskID':5, 'TaskName': 'Software Specification','StartDate': new Date('02/10/2017'), 'Duration': 3, 'parentID': 4 }
]
```

The field names **TaskID** and **ParentID** can be whatever we choose, but we have to map those field names in the [taskFields](https://ej2.syncfusion.com/documentation/api/gantt/#taskfields "taskFields property of JavaScript Gantt Chart") property of the JavaScript Gantt Chart. [We will see this later in the blog](#design-properties-panel).

2.Add the Gantt Chart with empty data from the SharePoint web part. For empty data binding, we can pass an empty array to the [dataSource](https://ej2.syncfusion.com/documentation/api/gantt/#datasource "dataSource property of JavaScript Gantt Chart") property of Gantt Chart in the **render** method of the web part file ( **GanttChartWebPart.ts** ).  
Refer to the following code example.
```js
public render(): void {
<section class="${styles.ganttChart} ${!!this.context.sdks.microsoftTeams ? styles.teams : ''}">
    <div id="Gantt-${this.instanceId}"></div>
</section>`;
 
this.ganttInstance = new Gantt({
   editSettings: {allowEditing: this.properties.allowEditing, allowTaskbarEditing: this.properties.allowEditing},
   taskFields: {
      id: this.properties.taskID,
      name: this.properties.taskName,
      startDate: this.properties.startDate,
      duration: this.properties.duration,
      progress: this.properties.progress,
      parentID: this.properties.parentID
   },
   dataSource: this.properties.dataSource,
..
}
this.ganttInstance.appendTo('#Gantt-'+this.instanceId);
 
protected async onInit(): Promise<void> {
 this.properties.dataSource = [];
}
```

### <a name="design-properties-panel">Step 2: Design properties panel to read SharePoint list data</a>

Now, let’s design the properties panel to choose the SharePoint list data source and other input values needed for the Gantt Chart’s [taskFields](https://ej2.syncfusion.com/documentation/api/gantt/#taskfields "taskFields property of JavaScript Gantt Chart") property to map the parent and child data from the list data source.

1. In the **getPropertyPaneConfiguration** method, create a dropdown with values of list names available in SharePoint.
```js
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
  return {
   …
    groups: [
    {
       groupName: strings.BasicGroupName,
       groupFields: [
         PropertyPaneDropdown('selectedList', {
          label: 'Connect to List Source',               
          options: this._siteLists.map((list: string) => {
             return <IPropertyPaneDropdownOption>{
                key: list, text: list
             }
          }),
         }
       ]
    }]
  }
}
```
2.Fetch the dropdown values using the SharePoint API service. I have used the [SPHttpClient](https://learn.microsoft.com/en-us/sharepoint/dev/spfx/connect-to-sharepoint#connect-to-sharepoint-api-using-the-sphttpclient "Connect to SharePoint API using the SPHttpClient") API to fetch the list names in SharePoint.
```js
protected async onInit(): Promise<void> {
  this._siteLists = await this._getSiteLists();
  …
}

public async _getSiteLists(): Promise<string[]> {
  const endpoint: string = `${this.context.pageContext.web.absoluteUrl}/_api/web/lists?$select=Title&$filter=Hidden eq false&$orderby=Title&$top=10`;
 
  const rawResponse: SPHttpClientResponse = await this.context.spHttpClient.get(
    endpoint,
    SPHttpClient.configurations.v1);
 
  return (await rawResponse.json()).value.map(
     (list: {Title: string}) => {
       return list.Title;
     }
  );
}
```
3.Then, add other input fields in the properties panel to map the [taskFields](https://ej2.syncfusion.com/documentation/api/gantt/#taskfields "taskFields property of JavaScript Gantt Chart") property of the Gantt Chart instance in the **render** method. Refer to the following code example.
```js
groupFields: [
   PropertyPaneTextField('taskID', {
      value: this.properties.taskID,
      label: "Task ID"
   }),
   PropertyPaneTextField('taskName', {
      value: this.properties.taskName,
      label: "Task Name"
   }),
   PropertyPaneTextField('startDate', {
      value: this.properties.startDate,
      label: "Start Date"
   }),
   …
]

public render(): void {
<section class="${styles.ganttChart} ${!!this.context.sdks.microsoftTeams ? styles.teams : ''}">
   <div id="Gantt-${this.instanceId}"></div>
</section>`;
…
this.ganttInstance = new Gantt({
   editSettings: {allowEditing: this.properties.allowEditing, allowTaskbarEditing: this.properties.allowEditing},
   taskFields: {
     id: this.properties.taskID,
     name: this.properties.taskName,
     startDate: this.properties.startDate,
     duration: this.properties.duration,
     progress: this.properties.progress,
     parentID: this.properties.parentID
  },
  …
})
```

After doing so, the look and appearance of the properties panel will be like the following image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/02/Designing-the-Properties-Panel-to-Read-SharePoint-List-Data-1.png" alt="Designing the Properties Panel to Read SharePoint List Data" style="width:100%">

  <figcaption>Designing the Properties Panel to Read SharePoint List Data</figcaption>

</figure>
### Step 3: Bind SharePoint list data to the JavaScript Gantt Chart

Finally, let’s bind data from the chosen list in the dropdown of the properties panel to the Gantt Chart. Here, we will retrieve the selected list data and bind it to the Gantt Chart with the help of the click event of the **Apply** button in the properties panel. Using the [SPHttpClient](https://learn.microsoft.com/en-us/sharepoint/dev/spfx/connect-to-sharepoint#connect-to-sharepoint-api-using-the-sphttpclient "Connect to SharePoint API using the SPHttpClient") API, get data from the SharePoint list.

Refer to the following code example.

```js
PropertyPaneButton("", {
    text: "Apply",
    onClick: () => {
        this._getSiteListItems();
    }
})
…

public async _getSiteListItems(): Promise<void> {
  const endpoint: string = `${this.context.pageContext.web.absoluteUrl}/_api/web/lists/${this.properties.selectedList}List/items`;
 
  const rawResponse: SPHttpClientResponse = await this.context.spHttpClient.get(
    endpoint,
    SPHttpClient.configurations.v1);
  var response = await rawResponse.json();
  this.properties.dataSource = response.value.map(
    (list: {Id: number, TaskID: number, TaskName: string, StartDate: DateTime, Duration: number, Progress: number, ParentID: number}) => {
      return {Id: list.Id, TaskID: list.TaskID, TaskName: list.TaskName, StartDate: list.StartDate, Duration: list.Duration, Progress: list.Progress, ParentID: list.ParentID}
    }
  );
}
```

Refer to the following output image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/02/Binding-SharePoint-Data-to-the-JavaScript-Gantt-Chart-1.png" alt="Binding SharePoint Data to the JavaScript Gantt Chart" style="width:100%">

  <figcaption>Binding SharePoint Data to the JavaScript Gantt Chart</figcaption>

</figure>
## Editing operation

To allow users to edit the data in the JavaScript Gantt Chart, refer to [editing tasks in JavaScript Gantt Chart documentation](https://ej2.syncfusion.com/documentation/gantt/managing-tasks/editing-tasks/ "Editing Tasks in JavaScript Gantt Chart control").

When a user edits data in the Gantt Chart, update the data changes back to the SharePoint list. Do this by using the [actionComplete](https://ej2.syncfusion.com/documentation/api/gantt/#actioncomplete "actionComplete property of JavaScript Gantt Chart") event of the Gantt Chart and sending post requests to the SharePoint list using the [SPHttpClient](https://learn.microsoft.com/en-us/javascript/api/sp-http/sphttpclient?view=sp-typescript-latest#@microsoft-sp-http-sphttpclient-post-member(1) "post(url, configuration, options) method of SPHttpClient API") API.

Refer to the following code example.

```js
this.ganttInstance = new Gantt({
   dataSource: this.properties.dataSource,
   actionComplete: (args: ActionCompleteArgs) => {
     if (args.requestType == 'save'){
       for (var i = 0; i < args.modifiedTaskData.length; i++) {
         var url = this.context.pageContext.web.absoluteUrl + '/_api/web/lists/' + this.properties.selectedList + 'List/items(' + args.modifiedTaskData[i]['Id'] + ')';
         this.context.spHttpClient.post(url, SPHttpClient.configurations.v1, {
           headers: {
             'Accept': 'application/json;odata=nometadata',
             'Content-type': 'application/json;odata=nometadata',
             'odata-version': '',
             'IF-MATCH': '*',
             'X-HTTP-Method': 'MERGE'
           },
           body: JSON.stringify(args.modifiedTaskData[i])
         })
       } 
     }
   }
})
```

Now the edited data in the JavaScript Gantt Chart will be updated on the SharePoint page.

## GitHub reference

For more details, check out the complete code example for [integrating the Syncfusion JavaScript Gantt Chart in a SharePoint web part on GitHub](https://github.com/SyncfusionExamples/ej2-gantt-and-sharepoint "Integrating Syncfusion JavaScript Gantt Chart in a SharePoint web part GitHub demo").

## Conclusion

Thanks for reading! In this blog, we have seen how to bind SharePoint list data to the Syncfusion [JavaScript Gantt Chart](https://www.syncfusion.com/javascript-ui-controls/js-gantt-chart "JavaScript Gantt Chart") and save the data changes made in the Gantt Chart back to the SharePoint list. Try the steps in the part 1 and 2 blogs to effectively manage your projects.

In addition to the Gannt Chart, there are more than 80 [JavaScript UI controls](https://www.syncfusion.com/javascript-ui-controls "Syncfusion JavaScript UI Controls"), such as Grid, Scheduler, Charts, and others that can also be integrated with SharePoint web parts. Try them out and leave your feedback in the comments section below.

If you want to try Syncfusion components, you can download our [free trial](https://www.syncfusion.com/downloads/essential-js2/confirm "Free evaluation of the Syncfusion Essential Studio"). Also, check out our [demos](https://ej2.syncfusion.com/demos/#/bootstrap5/gantt/default.html "JavaScript Gantt Chart demo") and [documentation](https://ej2.syncfusion.com/documentation/gantt/getting-started/ "Getting Started with JavaScript Gantt Chart control") for detailed explanations and the facts you need to proceed further.

You can also reach us through our [support forums](https://www.syncfusion.com/forums "Syncfusion Support Forums"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/ "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Null vs. Undefined in JavaScript](https://www.syncfusion.com/blogs/post/null-vs-undefined-in-javascript.aspx "Blog: Null vs. Undefined in JavaScript")
- [JavaScript Debounce vs. Throttle](https://www.syncfusion.com/blogs/post/javascript-debounce-vs-throttle.aspx "Blog: JavaScript Debounce vs. Throttle")
- [Effectively Visualize a Large Number of Markers Using JavaScript Maps](https://www.syncfusion.com/blogs/post/visualize-a-large-number-of-markers-using-javascript-maps.aspx "Blog: Effectively Visualize a Large Number of Markers Using JavaScript Maps")
- [11 Console Methods in JavaScript for Effective Debugging](https://www.syncfusion.com/blogs/post/11-console-methods-in-javascript-for-effective-debugging.aspx "Blog: 11 Console Methods in JavaScript for Effective Debugging")