man thinking

Building SPFx Web Parts with React Functional Components

If you build a "Hello World" web part using the Yeoman SPFx generator you will get a React component using a TypeScript class that extends the React.Component base class. This is the normal way that you create a React component in a language that supports classes. TypeScript has made it easier to use classes because, even though classes have been introduced to the JavaScript language (or more stricly-speaking the ECMAScript 2015 standard) you can't rely on this feature being available everywhere you want to run JavaScript. The TypeScript compiler takes care of this for you and also means you don't have to deal with the complexity of code isolation patterns like modules. You just get what you would expect from a classical language, even though JavaScript is actually using prototypal inheritance behind the scenes.

But JavaScript is a functional language (in the broadest sense), and if you are interested in functional programming you might prefer to avoid classes when writing React components. Well you can, because as well as writing React components with classes you can write one with just a simple function:

function myComponent(myProps) {
    return <h1>Hello {myProps.name}!</h1>;
}

It's ridiculously simple. Even I can do file->new and write this from memory. No remembering the class syntax and the base class and what method I need to override, no this and that. It's just a function that returns some React elements.

In fact this is a pure stateless function. It only depends on the properties you pass in. It has no side-effects and no state. Actually a lot of useful React components are like that. So you can use this straight away to write simpler code next time you need one of these stateless components.

An example stateless React component

I built a sample SPFx web part that uses a stateless function to reproduce the simple template web part created by the Yeoman generator. You can view the code on Github by following the link, where you will also find instructions for getting the sample working. It is actually a re-work of the React version of the Hello World web part that you get when you use the @microsoft/generator-sharepoint Yeoman generator with a few simplifications and, of course, a pure functional component. The web part is intended to be easier to understand for new developers building their first SPFx web part. If you run it you will see a web part that is identical to the regular web part that results from running the generator.

The standard Hello World web part

Although it looks identical to a Hello World web part created by any other means, it has been refactored as a pure functional component. This simplifies the code structure and will also gain you additional kudos when talking to computer scientists and functional code enthusiasts. The structure is a simple JavaScript function with the name of the component, a single argument containing the React props, and a simple return of the component rendering. Here's the code for the React component in the sample:

import * as React from 'react';
import styles from './HelloWorld.module.scss';
import { IHelloWorldProps } from '../HelloWorldWebPart';
import { escape } from '@microsoft/sp-lodash-subset';
import * as Fabric from 'office-ui-fabric-react';

export default function HelloWorld(props: IHelloWorldProps) {
  return (
    <div className={styles.container}>
      <div className={styles.row}>
        <div className={styles.column}>
          <span className={styles.title}>Welcome to SharePoint!</span>
          <p>Customize SharePoint experiences using Web Parts.</p>
          <p>{escape(props.description)}</p>
          <Fabric.PrimaryButton href="https://aka.ms/spfx">
            Learn more</Fabric.PrimaryButton>
        </div>
      </div>
    </div>
  );
}

In addition the React elements returned have been simplified. In particular the "Learn more" button, which was constructed from HTML primitives in the Yeoman-generated sample, has been replaced by an Office-UI-Fabric PrimaryButton component. This also means that it has been possible to greatly simplify the SASS file HelloWorld.module.scss.

Adding State

You may be wondering how maintaining state, side effects or other complexities can be accomodated with functional components like the one used. All of these can be achieved using a fairly new React feature called React Hooks, and will be demonstrated using another sample which does conversions to roman numerals. Because there is an input control where a user is typing a value, this React control needs to manage state. For this reason it is not a pure functional component and we can't use the simple approach in the previous example. In fact if you do this the "old" way, using classes, you will need quite a bit of extra code to keep track of state.

Screenshot

On line 11 of RomanNumerals.tsx the React.useState function is used to provide state:

  const [value, setValue] = React.useState(parseInt(props.initialValue));

React.useState takes an initial value for the state variable and returns an array of two objects. The first is a variable containing the state value, and the second is a setter function for the value. We could refer to these as state[0] and state[1] or something, but the convention is to use the array destructuring operator to unpack them into local constants. The name of these is not important but a good practice is to use the form [foo, setFoo], etc. Whenever we need to use the current value of the state variable we just refer to it (e.g. {value}), and wherever we need to change the value we call useState(newValue). There is no need to use this because we are not inside a class, nor do we need to worry about the context of the this value, nor create a constructor to initialize state.

In the code we use the number input control to change the value of the state using a local function onChange, which simply sets a new value as the user types in characters:

<input type="number" min="0" max="9999999" value={value} onChange={onChange} />

The onChange function could be defined using a lambda expression, but in this case we have defined a local function:

function onChange(event) {
  setValue(parseInt(event.target.value));
}

We also have a couple of additional buttons that can be used to increment and decrement the value which also demonstrates updating state with inline functions. Everything just works because the React framework will re-render the component whenever we update the state variable using the setValue function. If you need more complex state you could pass a more complex object to useState but a better approach is often to simply call useState once for each variable that makes up the state.

The output rendering uses the value of the state variable and does a conversion using the romanToString function:

<h3>{props.resultCaption} {romanToString(value)}</h3>

Using React Hooks allows us to manage state in a very simple way, without the complexities around component lifecycle events like componentDidMount, constructors, or keeping track of different incarnations of the this variable.

Prerequisites

React Hooks were introduced in version 16.8 of the React framework. The original version of the sample was built with version 1.82 of the SharePoint Framework (which uses an older version of React by default) and was modified to use version 16.8 of the React framework. Since the release of version 1.9.1 of the SharePoint Framework this is no longer necessary because it is using a newer version of React, but be aware of this if you decide to start working on some older code that was built using an older version of SPFx.

A more complex example

The previous example showed a React functional component that included state. In many cases, particularly when building extensions for SharePoint, Teams or Office, we also need to manage data fetched from a remote service. This can also be achieved using the recent React Hooks feature. The final example web part renders a list of the user's Teams and, if enabled, a list of the Teams channels for each Team with a link to the channel.

Screenshot

This is an extension of the approach used in the React-Functional-Component and React-Functional-Stateful-Component samples.

The onInit method of BaseClientSideWebPart is overriden to initialise the PnPJS graph object. The web part is then able to get access to the Microsoft Graph using the PnPJS library. The User.Read.All permission is implicitly provided.

  public onInit(): Promise<void> {
    return super.onInit().then(() => {
      graph.setup({ spfxContext: this.context });
    });
  }

As in the previous example we need to maintain the state of the component so this is provided by the React.useState hook:

  const initialTeamsList: MSGraph.Group[] = null;
  const [teamsList, setTeamsList] = React.useState(initialTeamsList);

React.useState takes an initial value for the state variable, which we initialise to null but by means of a strongly typed const. This means that we will get type checking and intellisense for the state object.

Fetching Data

If we were writing a React component class, we would need to use various lifecycle methods like componentDidMount and componentDidUpdate, etc. With functional components and React Hooks we use a React method called useEffect, which is designed to allow you to include code that enables your functional component to manage side-effects (hence the name). The code to call the Microsoft Graph is very simple:

  React.useEffect(() => {
    graph.me.joinedTeams.get().then(teams => { setTeamsList(teams); });
  }, []);

We use the PnPJS library to get a list of Teams from the Microsoft Graph, and then use the setTeamsList method (which you may remember was the second element in the array returned by the React.useState function) to set the value of the state variable. Calling setTeamsList is very similar to calling setState() when doing things the 'old way'. It will result in the component being re-rendered to reflect the changes to the state variable.

You might have noticed that there is a second argument to React.useEffect, and we have passed into it an empty array. This array contains any variables that we depend on, for example a filter or other display option - if they change it will result in the useEffect callback function being called again. If we omit the second argument altogether then the graph call will happen whenever the component is rendered, and since the promise causes a re-rendering, the result would be a nasty infinite loop. By providing an empty array we ensure that the useEffect callback only gets called when the component first loads.

For convenience we have rendered the dynamic bit of the web part into a variable called content. We can show a UI Fabric spinner if the data isn't loaded, or a helpful message if the data returned is an empty array. Here is the TSX code that renders the list of Teams:

      <ul>
        {teamsList.map(team => (
          <li key={team.id}>
            <Team channelID={team.id} displayName={team.displayName} 
              showChannels={props.showChannels} />
          </li>
        ))}
      </ul>

Notice that we just take the teamsList (our state variable) and use a map function to render each team into a series of <li> elements. Each team is rendered using a <Team> component which we have defined in Team.tsx.

Team.tsx Component

The Team.tsx component is only responsible for rendering an individual team, and the structure of the component follows a similar pattern to that of TeamTracker.tsx. Notice first that we use a different approach to using the props by using the object destructuring operator to unpack the individual values from the outset, which can sometimes make the subsequent code a little clearer:

export default function Team({ channelID, displayName, showChannels }) {

Again we use state to manage a list of channels and initialise it to an empty array. But in this case we have a property showChannels that is the flag set by the user in the property pane. If this is enabled we retrieve the channels from the Microsoft Graph using the PnPJS library, and if not we set it to an empty array. We need to explicitly reset the array in case the user enables and then subsequently disables the showChannels option. Finally, notice that we now need to include a dependency for the second argument of useEffect so that the framework knows to call the method again if the value of showChannels changes.

  const [channelsList, setChannelsList] = React.useState([]);
  React.useEffect(() => {
    if (showChannels)
      graph.teams.getById(channelID).channels.get().then(channels => {
        setChannelsList(channels); 
        });
    else
      setChannelsList([]);
  }, [showChannels]);

The rest of Team.tsx simply returns the rendering of the component with the name of the Team and a list of channels. If the channelsList is empty it will just render an empty <ul>.

If this were a real application, rather than a demonstration, you would need to decide whether it was efficient to make multiple graph calls, or whether to batch the calls in some way, which would probably make the code a little more complicated. If you end up with a large hierarchy of nested components you might also use the useContext hook to manage data that you retrieve at a higher level, to be referenced in lower level components without having to pass everything down through props.

Building and testing

All of the samples described above are in the SharePoint/sp-dev-fx-webparts repository on Github under the samples directory with names starting "react-functional-". To download them you can git clone this repository. In the directory for the sample you need to do an npm install and then a gulp serve to run the web part in the local workbench.

This will work for the first two samples, but the final sample will need to run in an actual tenant, otherwise the PnPJS promise will never return and so you will just see the loading spinner. In the react-functional-component-with-data-fetch directory, run npm install to resolve all the dependencies. Once this has completed you can run gulp serve --nobrowser to test the web part in the workbench of your tenant (https://mytenant.sharepoint.com/_layouts/15/workbench.aspx).