logo
Published on

Fabric React DatePicker in SPFx

This article demonstrates how to use the Fabric React DatePicker control in a SharePoint Framework (SPFx) web part.
The DatePicker allows users to pick a date, display it in a friendly format, and save or update it in a SharePoint list item using SPHttpClient.


📦 Install dependencies

The required Fabric React components are already included in SPFx. However, you can ensure that you have the latest version by installing:

npm install office-ui-fabric-react --save

🧩 Implement the DatePicker component

In your FabricDatePicker.tsx file, add the following code:

import * as React from 'react';
import { IFabricDatePickerProps, IFabricDatePickerWebpartProps } from './IFabricDatePickerProps';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { DatePicker } from 'office-ui-fabric-react/lib/DatePicker';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import styles from './FabricDatePicker.module.scss';

export default class FabricDatePicker extends React.Component<IFabricDatePickerProps, IFabricDatePickerWebpartProps> {

  private etag: String = undefined;

  constructor(props: IFabricDatePickerProps, state: IFabricDatePickerWebpartProps) {
    super(props);
    this.state = {
      birthday: null,
      message: ''
    };

    if (Environment.type === EnvironmentType.SharePoint) {
      this.props.spcontect.spHttpClient.get(
        this.props.spcontect.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('sampleLIST')/items(1)",
        SPHttpClient.configurations.v1
      ).then((response: SPHttpClientResponse) => {
        response.json().then((listItem: any) => {
          this.setState({ birthday: new Date(listItem.Birthday) });
        });
      });
    }

    this._alertClicked = this._alertClicked.bind(this);
  }

  public render(): React.ReactElement<IFabricDatePickerProps> {
    return (
      <div className={styles.fabricDatePicker}>
        <div className={styles.container}>
          <div className={styles.row}>
            <Label>Birthday</Label>
            <DatePicker
              placeholder="Select a date..."
              onSelectDate={this._onSelectDate}
              value={this.state.birthday}
              formatDate={this._onFormatDate}
            />
            <div className={styles.label}>
              <label>{this.state.message}</label>
            </div>
            <div className={styles.button}>
              <PrimaryButton text="Save" onClick={this._alertClicked} />
            </div>
          </div>
        </div>
      </div>
    );
  }

  private _onSelectDate = (date: Date | null | undefined): void => {
    this.setState({ birthday: date });
  };

  private _onFormatDate = (date: Date): string => {
    return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
  };

  private _alertClicked(): void {
    const body: string = JSON.stringify({
      '__metadata': { 'type': 'SP.Data.SampleLISTListItem' },
      'Birthday': this.state.birthday
    });

    this.props.spcontect.spHttpClient.get(
      this.props.spcontect.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('sampleLIST')/items(1)",
      SPHttpClient.configurations.v1
    ).then((response: SPHttpClientResponse) => {
      this.props.spcontect.spHttpClient.post(
        this.props.spcontect.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('sampleLIST')/items(1)",
        SPHttpClient.configurations.v1,
        {
          headers: {
            'Accept': 'application/json;odata=nometadata',
            'Content-type': 'application/json;odata=verbose',
            'odata-version': '',
            'IF-MATCH': response.headers.get('ETag'),
            'X-HTTP-Method': 'MERGE'
          },
          body: body
        }
      ).then((response: SPHttpClientResponse) => {
        this.setState({ message: 'Successfully saved' });
        console.log(`Status code: ${response.status}`);
      });
    });
  }
}

🧠 Key points explained

  • DatePicker: Renders the Fabric UI date selection control.
  • SPHttpClient: Used to read and update SharePoint list items.
  • _onSelectDate: Stores the user-selected date in the component state.
  • _alertClicked: Updates the SharePoint list with the selected date.

🚀 Deploy and test

  1. Build and package the solution:
gulp build
gulp bundle --ship
gulp package-solution --ship
  1. Upload the .sppkg file to your App Catalog.
  2. Add the web part to a modern page.
  3. Select a date and click Save — you’ll see the “Successfully saved” message once updated.

You’ve now built a simple Fabric React DatePicker web part in SPFx that connects directly to SharePoint list items! 🎉

Calendar IconBook a demo