Implementing Fluent UI Components in SPFx: A Step-by-Step Guide
Introduction
Fluent UI, by Microsoft, offers a rich set of customizable controls for SharePoint Framework (SPFx) solutions. This guide will cover how to create SPFx web parts using various Fluent UI components, showcasing how to render them dynamically in a web part.
Web Part 1: Button Component
1. Install Fluent UI
First, install Fluent UI into your SPFx project:
npm install @fluentui/react
2. Create Web Part for Button
Modify your ButtonWebPart.ts:
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { PrimaryButton } from '@fluentui/react';
export default class ButtonWebPart extends React.Component {
public render(): React.ReactElement {
return (
<div>
<PrimaryButton text="Click Me!" onClick={() => alert('Button clicked')} />
</div>
);
}
}
3. Run the Web Part
Execute the web part with gulp serve, and you will see a button rendered in SharePoint. Clicking it will show an alert.
Web Part 2: TextField Component
1. Create Web Part for TextField
Next, let’s render a TextField control. Update your TextFieldWebPart.tsx:
import * as React from 'react';
import { TextField } from '@fluentui/react';
export default class TextFieldWebPart extends React.Component {
state = { value: '' };
private handleChange = (e: any, newValue: string) => {
this.setState({ value: newValue });
};
public render(): React.ReactElement {
return (
<div>
<TextField label="Enter text" value={this.state.value} onChange={this.handleChange} />
<p>Typed value: {this.state.value}</p>
</div>
);
}
}
This renders a text field with live input display.
Web Part 3: Dropdown Component
1. Create Web Part for Dropdown
Create a new web part to implement the Dropdown component. Use DropdownWebPart.tsx:
import * as React from 'react';
import { Dropdown, IDropdownOption } from '@fluentui/react';
const options: IDropdownOption[] = [
{ key: 'option1', text: 'Option 1' },
{ key: 'option2', text: 'Option 2' },
{ key: 'option3', text: 'Option 3' },
];
export default class DropdownWebPart extends React.Component {
state = { selectedKey: '' };
private handleChange = (event: React.FormEvent<HTMLDivElement>, option: IDropdownOption): void => {
this.setState({ selectedKey: option.key });
};
public render(): React.ReactElement {
return (
<div>
<Dropdown placeholder="Select an option" options={options} onChange={this.handleChange} />
<p>Selected: {this.state.selectedKey}</p>
</div>
);
}
}
Conclusion
By following these examples, you will have built multiple SPFx web parts that render Fluent UI components dynamically. Each part demonstrates how to work with buttons, text fields, and dropdowns, giving you the ability to expand your solution with more controls like DatePickers, Dialogs, and more.

Leave a comment