React Button Component in SPFx: Code Explanation
This code demonstrates how to use the PrimaryButton from Fluent UI in a SharePoint Framework (SPFx) web part with React.
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>
);
}
}
Key Concepts:
- React Component Structure: The
ButtonWebPartclass extendsReact.Component, which is essential to creating reusable, modular web part components. - PrimaryButton: From Fluent UI, the
PrimaryButtonis used to display a clickable button. Thetextproperty defines the button label (“Click Me!”). - Event Handling in React: The
onClickproperty is linked to an event handler. In this example, an arrow function is passed directly, which triggers a JavaScriptalert()when the button is clicked. The use ofonClick={() => alert('Button clicked')}ensures that the event is fired when the user interacts with the button. - No State Required: This component doesn’t manage state as its sole functionality is handling button clicks. For more complex buttons that need to track state or interact with SharePoint data, state would be necessary.
Importance in SPFx:
Buttons are crucial for triggering actions in SPFx web parts, whether submitting data, navigating, or interacting with SharePoint lists. In this example, we see a simple interaction, but the event-handling mechanism is the same, allowing more advanced functionality like API calls or form submissions to be added later.
By using Fluent UI’s PrimaryButton, the SPFx web part ensures consistent styling across SharePoint, adhering to the platform’s UI guidelines while providing interactivity within the component.
This basic implementation is a foundation to build more advanced, user-interactive components in SPFx web parts.

Leave a comment