In this article, we will learn how to use the Fluent UI document card control in the SharePoint Framework webpart. Usually, we use this control to display files from a SharePoint document library in a document card layout in SPFx web parts.
This control helps display documents in an organised way, so users can easily see details such as file name, type, author, and modified date at once. It gives a neat card style view instead of a simple list, making it easier for people to download.
Create an SPFx Web Part with Fluent UI DocumentCard
In the image below, you can see that there is a SharePoint document library named “ProjectDocuments”. Now, we’ll display these files in a document card layout in the SharePoint Framework web part using Fluent UI React document card control.

Here is the SPFx web part image, which displays the library files, including the file extension icon as an image, file name, who modified it with persona, and the modified date in a document card layout.

To get SharePoint document library files into the SPFx webpart, we are using the PnPJS library. Let’s take a look at the steps to achieve this!
- Open the Node.js command prompt to create a new solution. Create a directory by providing the command below.
md SharePointListandLibraryCreation
- Now enter that directory using the command below.
cd SharePointListandLibraryCreation
- Run the below Yeoman generator command to quickly create a SharePoint client-side solution project with the right toolchain and project structure.
yo @microsoft/sharepoint
- Clicking enter after providing the above command will ask the questions below. Please provide the answers I have provided below.
- What is your solution name? FluentUIDocumentCardDemo
- Which type of client-side component to create? WebPart
- Add new Web part to solution fluent-ui-document-card-demo.
- What is your Web part name? DocumentCardControl
- Which template would you like to use? React
- Once it creates the project successfully! We need to run the following command to install the PnPJS library.
npm install @pnp/sp --save
- Provide code . Pressing Enter opens Visual Studio Code. In the image below, you will see the “DocumentCardControlWebPart.ts” file in the src folder. Add the below PnP JS import statements in it.
import {SPFx,SPFI,spfi} from '@pnp/sp';
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/files";
import "@pnp/sp/folders";

- Then, update the render(), onInit() as given below.
export default class DocumentCardControlWebPart extends BaseClientSideWebPart<IDocumentCardControlWebPartProps> {
private _sp:SPFI;
public render(): void {
const element: React.ReactElement<IDocumentCardControlProps> = React.createElement(
DocumentCardControl,
{
description: this.properties.description,
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userDisplayName: this.context.pageContext.user.displayName,
sp:this._sp,
context:this.context,
}
);
ReactDom.render(element, this.domElement);
}
protected onInit(): Promise<void> {
return this._getEnvironmentMessage().then(message => {
this._environmentMessage = message;
this._sp =spfi().using(SPFx(this.context))
});
}
Here:
- private _sp:SPFI = We assigned the SPFI as a data type to this variable.
- Then, in the onInit() method, we created a PnP Instance [this._sp] by passing the current context.
- In the render() method, along with default props, we additionally added the following ones:
- sp:this._sp = Assigned PnP Instance to the prop sp.
- context:this.context = Assigned the current context to the prop context.
- Now, we need to update the “Props.ts” file code with the code below.
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { SPFI } from "@pnp/sp";
export interface IDocumentCardControlProps {
description: string;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
userDisplayName: string;
sp:SPFI;
context: WebPartContext
}
Here, we are adding the two props, sp and context. These props were recently assigned in the render() method of the .ts file.
- After this, open the “DocumentCardControl.tsx” file and add the below in place of the existing one.
import * as React from 'react';
import styles from './DocumentCardControl.module.scss';
import type { IDocumentCardControlProps } from './IDocumentCardControlProps';
import {
DocumentCard,
DocumentCardPreview,
DocumentCardTitle,
DocumentCardActivity,
DocumentCardDetails,
IDocumentCardPreviewProps,
IDocumentCardActivityPerson,
DocumentCardType,
} from '@fluentui/react/lib/DocumentCard';
import { Stack } from '@fluentui/react/lib/Stack';
export interface IDocumentCardControlState {
documents: any[];
loading: boolean;
error: string | null;
}
export default class DocumentCardControl extends React.Component<
IDocumentCardControlProps,
IDocumentCardControlState
> {
constructor(props: IDocumentCardControlProps) {
super(props);
this.state = {
documents: [],
loading: true,
error: null,
};
}
public componentDidMount(): void {
this._getDocuments();
}
private async _getDocuments(): Promise<void> {
try {
const items = await this.props.sp.web.lists
.getByTitle('ProjectDocuments')
.items.select(
'Id',
'FileLeafRef',
'FileRef',
'Editor/Title',
'Editor/EMail',
'Modified',
'DocIcon'
)
.expand('Editor')
.top(10)
.orderBy('Modified', false)();
this.setState({
documents: items,
loading: false,
error: null,
});
} catch (err: any) {
this.setState({
documents: [],
loading: false,
error: err.message,
});
}
}
public render(): React.ReactElement<IDocumentCardControlProps> {
const { documents, loading, error } = this.state;
if (loading) {
return <div>Loading documents...</div>;
}
if (error) {
return <div style={{ color: 'red' }}>Error: {error}</div>;
}
return (
<section className={styles.documentCardControl}>
<h2 style={{ textAlign: 'center', marginBottom: '20px' }}>
Project Documents Card View
</h2>
<Stack tokens={{ childrenGap: 10 }}>
{documents.map((doc: any) => {
const previewProps: IDocumentCardPreviewProps = {
previewImages: [
{
name: doc.FileLeafRef,
linkProps: { href: doc.FileRef },
previewImageSrc: `/_layouts/15/images/ic${doc.DocIcon}.png`,
width: 80,
},
],
};
// Activity (user who modified)
const activityPeople: IDocumentCardActivityPerson[] = [
{
name: doc.Editor.Title,
initials: doc.Editor.Title.charAt(0),
profileImageSrc: `${this.props.context.pageContext.web.absoluteUrl}/_layouts/15/userphoto.aspx?size=S&accountname=${doc.Editor.EMail}`,
},
];
return (
<DocumentCard
key={doc.Id}
type={DocumentCardType.compact}
onClickHref={doc.FileRef}
styles={{
root: {
maxWidth: 500,
border: '1px solid #e1dfdd',
boxShadow: 'none',
},
}}
>
<DocumentCardPreview {...previewProps} />
<DocumentCardDetails>
<DocumentCardTitle title={doc.FileLeafRef} shouldTruncate />
<DocumentCardActivity
activity={`Modified ${new Date(
doc.Modified
).toLocaleDateString()}`}
people={activityPeople}
/>
</DocumentCardDetails>
</DocumentCard>
);
})}
</Stack>
</section>
);
}
}
Here:
- We imported all the components that are needed for all document cards.
- Then, we created a state “IDocumentCardControlState” to store the library files in the documents and manage loading and error handling.
- Using the constructor() within the class, we initialised those states with empty values.
- componentDidMount() = This is a React life cycle method, which will trigger when the webpart is loaded, so here we are calling this._getDocuments(); function to get files from the library.
- _getDocuments() = In this method, we are using the PnP JS API calls to get the files from the SharePoint document library named “ProjectDocuments.”
- await this.props.sp.web.lists.getByTitle(‘ProjectDocuments’).items Here:
- this.props.sp contains the PnPJS instance.
- web = includes the current site details.
- list = contains all the SharePoint lists and library information.
- getByTitle() = This method will get the provided list or library.
- items = Will retrieve all the files present in it.
- select() = Using this, we are retrieving only the following fields.
- Id
- FileLeafRef
- FileRef
- Editor/Title
- Modified
- DocIcon
- expand() = Used to expand the person/lookup fields to get the data from those fields.
- top() = This will retrieve the top 10 items only.
- orderBy() = To get the latest items, we are providing modified field values in descending order.
- The items variable will contain the output of this API. Using setState (), we update those items in the documents.
- Now in render(), if the loading state is true (if files are being loaded), it displays the “Loading documents…” message.
- In case an error occurs, it will display that error with red colour in the webpart.
- documents.map((..)) = By applying the map() method to the documents, we collect the previewProps, which contains an array of objects. each object contains the
- document file name,
- file link
- file extension image
- width
- activityPeople = This is also an array of objects, which includes the file modifier information, such as:
- name
- initials
- profile image
- <DocumentCard…>… </DocumentCard> = Within this, we provide the SharePoint document library files in the document card layout.
- key = Provided document Id, for unique identification.
- type = Provided compact value so that the files will be in compact mode.
- onClick = Passed the file link, so that when we click, it will allow us to download the file.
- <DocumentCardPreview {…previewProps} /> = Provided the preview props that we collected at the top, so that the file name, file images, and link are passed to the document card.
- <DocumentCardDetails> = Within this, we are showing the following controls:
- <DocumentCardTitle title={doc.FileLeafRef} shouldTruncate /> = Will display the file name.
- <DocumentCardActivity> = Will display the information like when the file was modified, and who modified it.
That’s it, save the changes and to test the web part locally before deployment, follow the steps below.
- Provide your SharePoint site URL to the “initialPage” parameter in the serve.json file located in the config folder.
"InitialPage": "https://<tenantName>.sharepoint.com/sites/spfxtraining/_layouts/workbench.aspx"
Keep the /_layouts/workbench.aspx as it is in the URL. Only change the tenant domain. Then save the changes.
- Now, run the command below in the Terminal pane or in the command prompt where you opened this solution.
gulp serve
Then, it will automatically open the workbench url, add the webpart, which will come as shown below.
This way, we can easily display the SharePoint document library files in a document card layout in the SPFx web part.
I hope you found this article helpful!, In this article, I explain how to use the Fluent UI React Document Card control in an SPFx web part to display files from a SharePoint library. Additionally, how to use the PnP JS library to fetch SharePoint document library files.
Also, you may like:
- Send Email in SPFx using Microsoft Graph API and PnP JS
- Create a SharePoint List using SharePoint Framework [Including Adding Columns]
- Create Folders and Subfolders in SharePoint document library using SPFx
- SPFx Upload File to SharePoint Document Library With Metadata [Complete Example]

Hey! I’m Bijay Kumar, founder of SPGuides.com and a Microsoft Business Applications MVP (Power Automate, Power Apps). I launched this site in 2020 because I truly enjoy working with SharePoint, Power Platform, and SharePoint Framework (SPFx), and wanted to share that passion through step-by-step tutorials, guides, and training videos. My mission is to help you learn these technologies so you can utilize SharePoint, enhance productivity, and potentially build business solutions along the way.