Rendering SharePoint List Items Using React and SPFx
In this article, we will guide you through the process of creating a simple SharePoint Framework (SPFx) web part to render list items from a SharePoint list using React. This example demonstrates how to pull data from a SharePoint list and display it on a web part using React components, while keeping everything static for simplicity.
Prerequisites
Before getting started, make sure you have the following installed:
- SharePoint Framework (SPFx) development environment
- Node.js
- Yeoman SharePoint generator
1. Setting Up the SPFx Project
First, set up your SPFx project using Yeoman:
yo @microsoft/sharepoint
Follow the prompts to configure your project. For this example, select React as the framework.
2. Web Part Code Structure
Let’s dive into the structure of our project. The two main files that make up this solution are:
ReacRenderList2WebPart.ts(Web Part code)ReacRenderList2.tsx(React component)
Here’s a breakdown of each file:
3. Web Part (ReacRenderList2WebPart.ts)
The web part is responsible for interacting with SharePoint to fetch list items and passing them as props to the React component.
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
type IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as strings from 'ReacRenderList2WebPartStrings';
import ReacRenderList2 from './components/ReacRenderList2';
import { IReacRenderList2Props } from './components/IReacRenderList2Props';
import { spfi, SPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
export interface IReacRenderList2WebPartProps {
description: string;
}
export default class ReacRenderList2WebPart extends BaseClientSideWebPart<IReacRenderList2WebPartProps> {
public sp:any;
public items:any[];
// Fetch items from the SharePoint list
private async getItems(sp:any) {
this.items = await sp.web.lists.getByTitle("MyList").items.select("Title", "Description")();
console.log(this.items);
}
public render(): void {
// Call getItems and then pass items to the React component
this.getItems(this.sp).then(()=>{
const element: React.ReactElement<IReacRenderList2Props> = React.createElement(
ReacRenderList2,
{
items: this.items,
getItems: this.getItems,
sp: this.sp
}
);
ReactDom.render(element, this.domElement);
});
}
public onInit(): Promise<void> {
return super.onInit().then(_ => {
// Configure PnPjs to use the current SPFx context
this.sp = spfi().using(SPFx(this.context));
});
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}
Key Points:
- We use the PnPjs library to retrieve list items. You need to ensure that the list exists in your SharePoint site, and its name matches the one in the code (
"MyList"). - The
getItemsfunction asynchronously fetches the list items and stores them in theitemsarray. - Once items are fetched, they are passed to the React component via props.
4. React Component (ReacRenderList2.tsx)
The React component receives the list items as props and renders them.
import * as React from 'react';
import type { IReacRenderList2Props } from './IReacRenderList2Props';
export default class ReacRenderList2 extends React.Component<IReacRenderList2Props, {}> {
public render(): React.ReactElement<IReacRenderList2Props> {
const { items } = this.props;
return (
<div>
<h2>List Items</h2>
<ul>
{items.map(item => (
<li key={item.Id}>{item.Title}</li>
))}
</ul>
</div>
);
}
}
Key Points:
- The component receives
itemsfrom the web part and iterates over them usingmapto generate a list. - Each item is rendered as an
<li>element showing theTitleproperty.
5. Deploy and Test
Once you’ve written the code, build your solution using:
gulp build
gulp bundle --ship
gulp package-solution --ship
After deploying your solution to SharePoint, you should see a list of items rendered in your web part.
Conclusion
This simple example shows how to create an SPFx web part that fetches and renders SharePoint list items using React. It’s a foundation that can be expanded to handle more complex scenarios, such as dynamic list names, filtering, or error handling.
By understanding how SPFx works with React, you’ll have more flexibility in creating dynamic and responsive web parts for your SharePoint site.
French Version
Rendu des éléments de liste SharePoint à l’aide de React et SPFx
Dans cet article, nous vous expliquerons comment créer une web part SharePoint Framework (SPFx) pour afficher les éléments d’une liste SharePoint en utilisant React.
Prérequis
Avant de commencer, assurez-vous d’avoir :
- Un environnement de développement SPFx
- Node.js
- Générateur Yeoman SharePoint
1. Création du projet SPFx
Configurez votre projet avec Yeoman :
yo @microsoft/sharepoint
Suivez les instructions et sélectionnez React comme framework.
2. Structure du code
Les fichiers principaux :
ReacRenderList2WebPart.ts(Web Part)ReacRenderList2.tsx(Composant React)
3. Web Part (ReacRenderList2WebPart.ts)
La web part récupère les éléments de la liste SharePoint et les passe au composant React.
4. Composant React (ReacRenderList2.tsx)
Le composant affiche les éléments sous forme de liste.
5. Déploiement
Construisez votre solution avec :
gulp build
gulp bundle --ship
gulp package-solution --ship
Italian Version
Visualizzare gli elementi di una lista SharePoint con React e SPFx
In questo articolo, vi mostreremo come creare una web part di SharePoint Framework (SPFx) per visualizzare gli elementi di una lista SharePoint usando React.
Prerequisiti
- Ambiente di sviluppo SPFx
- Node.js
- Generatore Yeoman SharePoint
1. Creazione del progetto SPFx
Avviate il progetto con Yeoman:
yo @microsoft/sharepoint
Scegliete React come framework.
2. Struttura del codice
I file principali:
ReacRenderList2WebPart.ts(Web Part)ReacRenderList2.tsx(Componente React)
3. Web Part (ReacRenderList2WebPart.ts)
La web part recupera gli elementi dalla lista e li passa al componente React.
4. Componente React (ReacRenderList2.tsx)
Il componente mostra gli elementi come una lista.
5. Distribuzione
Compilate la soluzione con:
gulp build
gulp bundle --ship
gulp package-solution --ship
Spanish Version
Renderizado de elementos de lista de SharePoint usando React y SPFx
En este artículo, te mostraremos cómo crear una web part de SharePoint Framework (SPFx) para renderizar los elementos de una lista de SharePoint usando React.
Requisitos previos
- Entorno de desarrollo de SPFx
- Node.js
- Generador Yeoman SharePoint
1. Creación del proyecto SPFx
Configura tu proyecto con Yeoman:
yo @microsoft/sharepoint
Selecciona React como framework.
2. Estructura del código
Archivos principales:
ReacRenderList2WebPart.ts(Web Part)ReacRenderList2.tsx(Componente React)
3. Web Part (ReacRenderList2WebPart.ts)
La web part obtiene los elementos de la lista y los pasa al componente React.
4. Componente React (ReacRenderList2.tsx)
El componente muestra los elementos como una lista.
5. Despliegue
Construye la solución con:
gulp build
gulp bundle --ship
gulp package-solution --ship
German Version
SharePoint-Listenelemente mit React und SPFx rendern
In diesem Artikel zeigen wir, wie man eine SharePoint Framework (SPFx) Web Part erstellt, um Listenelemente einer SharePoint-Liste mit React anzuzeigen.
Voraussetzungen
- SPFx-Entwicklungsumgebung
- Node.js
- Yeoman SharePoint-Generator
1. Einrichtung des SPFx-Projekts
Erstelle dein Projekt mit Yeoman:
yo @microsoft/sharepoint
Wähle React als Framework.
2. Code-Struktur
Hauptdateien:
ReacRenderList2WebPart.ts(Web Part)ReacRenderList2.tsx(React-Komponente)
3. Web Part (ReacRenderList2WebPart.ts)
Die Web Part ruft die Listenelemente ab und übergibt sie an die React-Komponente.
4. React-Komponente (ReacRenderList2.tsx)
Die Komponente zeigt die Elemente als Liste an.
5. Bereitstellung
Baue die Lösung mit:
gulp build
gulp bundle --ship
gulp package-solution --ship

Leave a comment