React is the recommended framework for SPFx web parts, and for good reason. The component model fits perfectly with SharePoint’s web part architecture. Here’s how to build a real-world web part using React and TypeScript.
Project Setup
yo @microsoft/sharepoint
# Select "WebPart"
# Select "React" as the framework
Web Part Structure
An SPFx React web part has two main files:
- WebPart.ts – The SPFx wrapper that handles configuration
- Component.tsx – Your React component
// MyWebPart.ts
export default class MyWebPart extends BaseClientSideWebPart {
public render(): void {
const element: React.ReactElement = React.createElement(
MyComponent,
{
title: this.properties.title,
context: this.context
}
);
ReactDom.render(element, this.domElement);
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [{
groups: [{
groupFields: [
PropertyPaneTextField('title', { label: 'Title' })
]
}]
}]
};
}
}
The React Component
// MyComponent.tsx
import * as React from 'react';
import { useState, useEffect } from 'react';
import { sp } from '@pnp/sp';
export interface IMyComponentProps {
title: string;
context: WebPartContext;
}
const MyComponent: React.FC = ({ title, context }) => {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
sp.setup({ spfxContext: context });
loadData();
}, []);
const loadData = async () => {
const results = await sp.web.lists
.getByTitle('Tasks')
.items
.select('Title', 'Status')
.get();
setItems(results);
setLoading(false);
};
if (loading) return Loading...;
return (
{title}
{items.map(item => (
- {item.Title} - {item.Status}
))}
);
};
export default MyComponent;
Using Office UI Fabric
Office UI Fabric React components make your web part look native:
import { DetailsList, IColumn } from 'office-ui-fabric-react';
const columns: IColumn[] = [
{ key: 'title', name: 'Title', fieldName: 'Title', minWidth: 100 },
{ key: 'status', name: 'Status', fieldName: 'Status', minWidth: 100 }
];
return (
);
Tips
- Use PnP JS for SharePoint operations—it handles REST complexity
- Test in the hosted workbench, not just local
- Keep components small and focused
- Handle loading and error states properly
References
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.