Skip to content

Latest commit

 

History

History

02-fabricreact

Leveraging Fabric React

In this demo, you will update the existing React-based SPFx web part to leverage a few controls from the Fabric React controls.

This project uses the final project from the previous demo as the starting point. A copy of the final project from the previous demo can be found in the ./Demos/01-webpart folder.

  1. Update the existing ColorList React component to leverage Fabric React controls.

    1. Open the ./src/webparts/reactWebPartDemo/components/ColorList.tsx file.

    2. Add the following import statements to the top of the file. These will enable adding a DefaultButton and List control to the component:

      import { List } from 'office-ui-fabric-react/lib/List';
      import { DefaultButton } from 'office-ui-fabric-react/lib/Button';
    3. Update the render() method within the ColorList class to the following code:

      public render(): React.ReactElement<IColorListProps> {
        return (
          <div>
            <List items={ this.props.colors } 
                  onRenderCell={ this._onRenderListCell } 
            />
          </div>
        );
      }
    4. Handle the rendering of each item in the list by adding the following method to the ColorList class:

      private _onRenderListCell = (color: IColor, index: number | undefined): JSX.Element => {
        return (
          <div>
            { color.title }<br />
            <DefaultButton text="delete"
                          data={ color.id }
                          onClick={ () => this._onButtonClick(color) }
            />
          </div>
        );
      }
    5. Next, add an event handler for when the button is selected:

      private _onButtonClick(color:IColor): void {
        console.log('clicked delete for color', color);
      }
  2. Test the project:

    1. Start the local web server using the provided gulp serve task:

      gulp serve
    2. The SharePoint Framework's gulp serve task will build the project, start a local web server and launch a browser open to the local SharePoint Workbench.

    3. Add the web part to the workbench. Notice our list of three colors is rendered up exactly as we would expect.

      Screenshot of running React web part

    4. Select the delete button for one of the colors & examine the browser's JavaScript console, usually located in the browser's developer tools. You should see a log message displayed each time a button is selected:

      Screenshot of browser's JavaScript Console

    5. Close the browser and stop the local web server by pressing CTRL+C in the command prompt.