Building SPFx Web Parts with React: A Guide to Using useState and Fluent UI

In the world of SharePoint development, the SharePoint Framework (SPFx) has emerged as a powerful tool for building modern web parts. With the growing popularity of React as a front-end library, integrating React into SPFx projects has become a standard practice for developers. React provides a declarative and efficient way to create interactive user interfaces, making it an ideal choice for SharePoint developers.

Understanding React and useState

React is a JavaScript library for building user interfaces, particularly single-page applications where you need a dynamic, responsive experience. One of the core concepts in React is the use of state, which allows components to manage and render dynamic data. The useState hook, introduced in React 16.8, is a fundamental way to add state management to functional components.

The useState hook allows you to declare state variables in your functional components and provides a way to update them. This makes it easier to create interactive elements, such as forms and buttons, that respond to user actions.

Creating an SPFx Web Part with React and Fluent UI

In this article, we will walk through creating an SPFx web part that uses React and Fluent UI to display a message and toggle its visibility. We will demonstrate how to manage state using the useState hook and how to utilize Fluent UI components for styling and layout.

Step 1: Setting Up Your SPFx Project

Before we begin, ensure you have the SharePoint Framework environment set up. If you haven’t created a project yet, run the following command:

yo @microsoft/sharepoint

When prompted, select React as your framework.

Step 2: Implementing the Web Part

Main Web Part File (MyToggleWebPart.ts)

First, we’ll set up the main SPFx web part file, where we will render our React component and pass in properties.

import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as React from 'react';
import * as ReactDom from 'react-dom';
import MyToggle, { IMyToggleProps } from './components/MyToggle';

export interface IMyToggleWebPartProps {
  message: string;
}

export default class MyToggleWebPart extends BaseClientSideWebPart<IMyToggleWebPartProps> {
  public render(): void {
    const element: React.ReactElement<IMyToggleProps> = React.createElement(
      MyToggle,
      {
        message: this.properties.message
      }
    );

    ReactDom.render(element, this.domElement);
  }

  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: { description: "Configure the Message" },
          groups: [
            {
              groupName: "Message Settings",
              groupFields: [
                PropertyPaneTextField('message', {
                  label: "Message to Display"
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Step 3: Creating the Functional Component

Next, we’ll create the functional component that utilizes Fluent UI components and manages state with useState.

Component File (MyToggle.tsx)

import * as React from 'react';
import { useState } from 'react';
import { Stack, IStackTokens, PrimaryButton } from '@fluentui/react';

export interface IMyToggleProps {
  message: string;
}

const stackTokens: IStackTokens = { childrenGap: 10 };

const MyToggle: React.FC<IMyToggleProps> = ({ message }) => {
  const [isVisible, setIsVisible] = useState(true);

  const toggleMessage = () => {
    setIsVisible(!isVisible);
  };

  return (
    <Stack tokens={stackTokens} horizontalAlign="center" verticalAlign="center" styles={{ root: { height: '100vh' } }}>
      {isVisible && <p>{message}</p>}
      <PrimaryButton onClick={toggleMessage} text="Toggle Message" />
    </Stack>
  );
};

export default MyToggle;

Explanation of the Code

  • Web Part File: In MyToggleWebPart.ts, we create the main web part structure. The render method creates an instance of the MyToggle component, passing the message property from the property pane.
  • Functional Component: In MyToggle.tsx, we define a functional component that uses the useState hook to manage the visibility of a message. The toggleMessage function updates the state, causing the component to re-render based on user interaction.

Utilizing Fluent UI Components

Fluent UI provides a set of React components that are designed to integrate seamlessly with Microsoft products. In our example, we use the Stack component for layout and the PrimaryButton for user interaction, creating a modern look and feel that aligns with SharePoint’s design language.

Conclusion

Integrating React and Fluent UI into your SPFx web parts not only enhances the user experience but also simplifies the development process. The useState hook is a powerful tool for managing component state, enabling you to build interactive web parts that respond to user actions. As SharePoint continues to evolve, leveraging these technologies will help you create more dynamic and engaging applications.

For further details on using Fluent UI and setting up your SPFx environment, refer to the official documentation on Fluent UI. Happy coding!

Edvaldo Guimrães Filho Avatar

Published by

Categories: