SharePoint Framework - React Partial State Update

In this article, we will explore how we can partially update the state in SPFx web part. We will use React JS in this example. For this article, I am using SharePoint Framework version 1.7.1

Overview

SharePoint framework supports React JS natively. React works well with SharePoint and it only updates virtual DOM of what has been changed instead of re-rendering the entire DOM (Document Object Model). ReactComponent is one of the primary building blocks of React which has a state. Once the state is changed, React auto-renders what has changed. We can have fairly large data in a state.
 
React State
 
A state is mutable data that represents the internal state of the component. When the state is updated, component and its children are re-rendered. It is ideal to initialize a state in a constructor. Any events happening on the SharePoint Framework web part can change the component state. We can use the setState method of ReactComponent to change its state. When the state has huge data, it is challenging to set the data again along with what has been changed. In these circumstances, we should partially update the state.
 
Create SPFx Solution
 
Open the command prompt. Create a directory for SPFx solution.
  1. md spfx-react-partial-state-update  
Navigate to the above-created directory.
  1. cd spfx-react-partial-state-update  
Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
Yeoman generator will present you with the wizard by asking questions about the solution to be created.
 
SharePoint Framework - React Partial State Update
 
Solution Name: Hit Enter to have a default name (spfx-react-partial-state-update in this case) or type in any other name for your solution.
Selected choice: Hit Enter
 
Target for component: Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
 
Place of files: We may choose to use the current folder or create a subfolder for our solution.
Selected choice: Use the current folder
 
Deployment option: We may choose to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding apps in sites.
Selected choice: N (install on each site explicitly)
 
Type of client-side component to create: We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice: WebPart
 
Web part name: Hit Enter to select the default name or type in any other name.
Selected choice: ReactPartialStateUpdate
 
Web part description: Hit Enter to select the default description or type in any other value.
Selected choice: Partially update React State
 
Framework to use: Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice: React
 
Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command.
  1. npm shrinkwrap  
In the command prompt, type this command to open the solution in a code editor of your choice.
  1. code .  

Define State

Create a new file IReactPartialStateUpdateState.ts under the “\src\webparts\ reactPartialStateUpdate\components\” folder.
  1. export interface IReactPartialStateUpdateState {  
  2.     currentDate: Date;  
  3.     randomNumber: number;  
  4.     ramdomText: string;  
  5. }  
Update your component “\src\webparts\ reactPartialStateUpdate\components\ ReactPartialStateUpdate.tsx” to use the state.
  1. import { IReactPartialStateUpdateState } from './IReactPartialStateUpdateState';  
  2.   
  3. export default class ReactPartialStateUpdate extends React.Component<IReactPartialStateUpdateProps, IReactPartialStateUpdateState> {  
  4.   
  5.   public constructor(props: IReactPartialStateUpdateProps, state: IReactPartialStateUpdateState) {  
  6.     super(props);  
  7.   
  8.     this.state = {  
  9.       currentDate: new Date(),  
  10.       randomNumber: 0,  
  11.       ramdomText: ""  
  12.     };  
  13.   }  
  14. }  
Code the WebPart
 
Open the ReactPartialStateUpdate.tsx web part under “\src\webparts\reactPartialStateUpdate\components\” folder.
 
Add buttons to render the method.
  1. public render(): React.ReactElement<IReactPartialStateUpdateProps> {  
  2.   return (  
  3.     <div className={styles.reactPartialStateUpdate}>  
  4.       <div className={styles.container}>  
  5.         <div className={styles.row}>  
  6.           <div className={styles.column}>  
  7.             <span className={styles.title}>Welcome to SharePoint!</span>  
  8.             <p className={styles.subTitle}>Customize SharePoint experiences using Web Parts.</p>  
  9.             <p className={styles.description}>{escape(this.props.description)}</p>  
  10.   
  11.             <div>  
  12.               <a href="#" className={`${styles.button}`} onClick={() => this.clickShowDate()}>  
  13.                 <span className={styles.label}>Show Date</span>  
  14.               </a>  
  15.                  
  16.               Current Date: {this.state.currentDate.toDateString()}  
  17.             </div>  
  18.             <p></p>  
  19.   
  20.             <div>  
  21.               <a href="#" className={`${styles.button}`} onClick={() => this.clickShowRandomNumber()}>  
  22.                 <span className={styles.label}>Generate Random Number</span>  
  23.               </a>  
  24.                  
  25.               Random Number: {this.state.randomNumber}  
  26.             </div>  
  27.             <p></p>  
  28.   
  29.             <div>  
  30.               <a href="#" className={`${styles.button}`} onClick={() => this.clickShowRandomString()}>  
  31.                 <span className={styles.label}>Generate Random String</span>  
  32.               </a>  
  33.                  
  34.               Random Text: {this.state.ramdomText}  
  35.             </div>  
  36.   
  37.           </div>  
  38.         </div>  
  39.       </div>  
  40.     </div>  
  41.   );  
  42. }  
Implement the button click methods to set the state partially using spread operator.
  1. private clickShowDate(): void {  
  2.   this.setState(() => {  
  3.     return {  
  4.       ...this.state,  
  5.       currentDate: new Date()  
  6.     };  
  7.   });  
  8. }  
  9.   
  10. private clickShowRandomNumber(): void {  
  11.   this.setState(() => {  
  12.     return {  
  13.       ...this.state,  
  14.       randomNumber: Math.floor(Math.random() * 10) + 1  
  15.     };  
  16.   });  
  17. }  
  18.   
  19. private clickShowRandomString(): void {  
  20.   this.setState(() => {  
  21.     return {  
  22.       ...this.state,  
  23.       ramdomText: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)  
  24.     };  
  25.   });  
  26. }  
Spread operator
 
Using the spread operator (…), the state of the object that you pass in is copied onto the component's state. The spread operator can be used to take an existing array and add another element to it while preserving the original array.
 
Test the WebPart
  1. On the command prompt, type “gulp serve”.
  2. Open SharePoint site.
  3. Navigate to /_layouts/15/workbench.aspx.
  4. Locate and add the web part to the page.
  5. Verify the state by clicking each of the buttons.

    SharePoint Framework - React Partial State Update
Troubleshooting
 
The spread operator will help update the state partially.
 
SharePoint Framework - React Partial State Update
 
Open the below URL in the next tab of the browser. Accept the warning message.
 
https://localhost:4321/temp/manifests.js
 
Summary
 
The Spread attribute allows copying enumerable properties from one object to another. We can use the same in SharePoint Framework to partially update the state.