Showing posts with label SharePoint Online. Show all posts
Showing posts with label SharePoint Online. Show all posts

Monday, 15 September 2025

SharePoint Framework (SPFx) React WebPart lifecycle

In this blog, we will be learning about the lifecycle event of SharePoint Framework (SPFx) web part with React.

What is a web part?

A web part is a reusable visual object that a page author can add to their content, and customize using a property pane.


In SPFx web parts the lifecycle refers to the sequence of events or methods that are executed during the web part's initialization, rendering, and disposal. The SPFx web part lifecycle integrates both core SPFx methods and the standard React component lifecycle methods.

When building a SPFx web part using React, two lifecycles are involved:
  • SPFx WebPart Lifecycle
  • React Component Lifecycle

I have created a simple react based webpart which displays logged-in user name and webpart edit property. On button click the number gets incremented by one.


SPFx WebPart Lifecycle

The SPFx framework has its own lifecycle methods for the web part class (instance) in the .ts file, which interact with the React Component.

Web part Base Class - defines the main entry point for the web part. Extends the BaseClientSideWebPart. All client-side web parts must extend the BaseClientSideWebPart class to be defined as a valid web part.

export default class SpFxWebpartLifecycleWebPart extends BaseClientSideWebPart <ISpFxWebpartLifecycleWebPartProps>

BaseClientSideWebPart class - This abstract class implements the base functionality for a client-side web part. Every client-side web part needs to inherit from this class.
Extends BaseWebPart<TProperties>

Along with the base functionality, this class provides some APIs that can be used by the web part. These APIs fall in two categories.

The first category of APIs provide data and functionality. Example, the web part context (i.e. this.context). This API should be used to access contextual data relevant to this web part instance.

The second category of APIs provide a base implementation for the web part lifecycle and can be overridden for an updated implementation. The render() API is the only API that is mandatory to be implemented/overridden by a web part. All other life cycle APIs have a base implementation and can be overridden based on the needs of the web part.

The main SPFx lifecycle methods are:
SPFx Method Purpose
constructor() Constructor for the BaseClientSideWebPart class.
Initialize the web part class (services, variables). React is not yet mounted.
onInit() This event method is called when the web part is initialized.
Returns a Promise. Use it for async initialization (fetching data, setting context).
render() This API is called to render the web part. There is no base implementation of this API and the web part is required to override this API.
Creates and renders the React component in DOM with ReactDom.render().
onDispose() This API should be used to refresh the contents of the PropertyPane.
Cleanup (unmount React with ReactDom.unmountComponentAtNode). Called when the web part is removed from the page.

You can find SPFx lifecycle Properties and Methods detail here


React Component Lifecycle

Within the main SPFx web part render method, a React component is mounted. This component is defined in .tsx file which follows its own lifecycle.

React.Component - Component is the base class for the React components defined as JavaScript classes. To define a React component as a class, extend the built-in Component class and define a render method. Only the render method is required, other methods are optional.

export default class SpFxWebpartLifecycle extends React.Component<ISpFxWebpartLifecycleProps, ISpFxWebpartLifecycleState>


The main React component lifecycle methods are:
React Method Purpose
constructor() Initialize state and bind event handlers
render() Returns the JSX/TSX (UI structure) to be rendered
componentDidMount() Called after the component is inserted into the DOM. This is the ideal place for API calls to fetch data from sources like SharePoint lists.
shouldComponentUpdate(nextProps, nextState, nextContext) To optimize the re-rendering process by allowing React to skip the re-render if props or state has changed.
componentDidUpdate(prevProps, prevState, snapshot?) Called after the component’s props or state have been updated. Use this to perform side effects or re-fetch data based on specific prop/state changes.
componentWillUnmount() Called just before the component is removed from the DOM. Essential for clean-up of resources, such as removing event listeners or cancelling network requests.

You can find React Component methods here



In the SPFx react webpart the methods are defined and a console log statement is added to track the webpart lifecycle flow.
Lets add a webpart on the page and check the behavior.

Event: Page load
On Page load the webpart is displayed. The both SPFx lifecycle and React component lifecycle events are triggered.




Event: Button click/State change
Click on the "Increment My Number" button and this will increment the number by 1 on every click. Here state value gets updated. React responds to state/prop changes by re-rendering react component. The SPFx lifecycle events will not get executed and only React component lifecycle events are triggered.





Event: Page edit mode
The both SPFx lifecycle and React component lifecycle events are triggered.
This event first removes/disposes the webpart component. The SPFx onDispose method simply calls ReactDom method ReactDom.unmountComponentAtNode(this.domElement) - it removes a mounted React component from the DOM and clean up its event handlers and state.
In addition, unmounting a component also triggers the React componentWillUnmount() lifecycle method. This method is often used to perform any necessary cleanup, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount.

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

Once the webpart component is unmounted then again the webpart is rendered and mounted. Here the lifecycle is similar to the page load event.




Event: Edit WebPart/Open Property Pane
On editing webpart properties (opening property pane) - only the SPFx lifecycle events are triggered.

The loadPropertyPaneResources() method only gets called once. If you close the property pane and re-open then this method will not get call. It will only be called again if you reload the page and then open property pane.
The getPropertyPaneConfiguration() method will get executed twice. It's happening because of the reactive property pane interaction mode. When a property value changes (e.g. in a PropertyPaneTextField), the framework often re-evaluates the entire property pane configuration to determine if other fields need to be updated, hidden, shown, or disabled based on the new value.




Event: WebPart Property Pane closed
When webpart property pane is closed SPFx onPropertyPaneConfigurationComplete() method is called. This method will be trigger whether properties are changed or not. Only one SPFx lifecycle event is triggered.




Event: WebPart property change
When property pane field value changes. SPFx detects property changes and updates the web part. React responds to state/prop changes by re-rendering react component. The both SPFx lifecycle and React component lifecycle events are triggered.
The getPropertyPaneConfiguration() and onPropertyPaneRendered() method will get executed twice. It's happening because of the reactive property pane interaction mode. The default behavior is Reactive.







I hope this will help all of you! 🧲
Feel free to provide feedback.


πŸš€ "Happy Coding" πŸš€

Tuesday, 10 June 2025

Get SharePoint search results using the Rest API in PowerAutomate

In this blog, we will be learning about how to get SharePoint search results using the Rest API through PowerAutomate flow. The search results will be exported into a CSV file and saved into a SharePoint library. 

Create Flow

1). Sign in to Power Automate

2). Open the flow, click on the Create option, and select "Instant Cloud Flow".

Enter Flow name.
Choose the flow trigger as "Manually trigger a flow".
Click on the Create button.



3). Add an action "Send an HTTP request to SharePoint".


Site Address
https://yoursite.sharepoint.com/sites/VideoHub
Method
GET
Uri
_api/search/query
?querytext='Path:https://yoursite.sharepoint.com/sites/VideoHub*'
&trimduplicates=false&rowlimit=500
&selectproperties='Title,RefinableString00,RefinableInt00,
                   IsDiscontinued,RefinableString03'
&refiners='contentclass,SecondaryFileExtension,ListID'
&refinementfilters='and(
    contentclass:equals("STS_ListItem_DocumentLibrary"),
    SecondaryFileExtension:or("mp4","mkv"),
    ListID:equals("f7fb8ca6-aaaa-bbbb-cccc-7816d24bdf42")
)'
&sortlist='Created:descending'
Headers
{
  "accept": "application/json; odata=nometadata"
}


4). Add an action "Parse JSON" and enter output of previous step in Content.
In the Schema field use the below JSON content.


Parse JSON - Schema

		

Add additional type null - this will take care of the null values coming in search results.


5). Initialize variables one of type Object and Array.


		


6). Add "Apply to each" loop for rows and enter step 4 output (or enter below) as input value.

body('ParseJSONtoGetRows')['PrimaryQueryResult']['RelevantResults']['Table']['Rows']

Add another nested "Apply to each" loop for cells and enter current cells value (or enter below) as input value.

items('Apply_to_each-Rows')['Cells']


7). Add a "Switch" condition and enter current cell key value (or enter below) as On value.

items('Apply_to_each-Cells')?['Key']


8). Add a case statement to fetch field value from the search property.

Enter search managed property Title in equals field.

Add an action "Compose" and add below value in the inputs parameter.

setProperty(variables('varResponseJson'),'Title',items('Apply_to_each-Cells')?['Value'])

Here, setProperty(object, property, value) function is used; it returns an object with a property set to the provided value.

Add an action "Set variable" (defined in step 5) object variable and enter previous step output as input value.

9). Add more case statements; we are fetching five field values from the search properties. Therefore, five case statements are needed.
Repeat the step 8 for all the required search managed property.

Note: Create search managed properties for your custom fields and use them.




10). Append the array variable (defined in step 5) and enter object variable output as value after closing on inner "Apply to each" loop.


11). Add an action "Create CSV table" and enter array variable in From and Automatic in Columns.


12). Add an action "Create file" to create CSV file to export the search results.

Enter the Site Address and Folder Path as required.

File Name as concat('BlogData_', formatDateTime(utcNow(), 'yyyyMMdd_HHmmss'), '.csv')

File Content as output from previous step 12.



I hope this will help all of you! 🧲
Feel free to provide feedback.


πŸš€ "Happy Coding" πŸš€

Wednesday, 20 December 2023

SharePoint site theme: Add a custom theme using PowerShell

In this blog, we will be learning how to create a custom theme for SharePoint Online.

Now SharePoint has a Site theming feature for applying custom styles and colors to the site. There are six light and two dark themes available by default. This feature provides the ability to define custom themes and make them available to site owners. Creating a custom theme in SharePoint is a quick and easy way to give your site a unique look and feel.

Currently, no theme is available under the "From your organization" option.


The steps to add a custom theme to SharePoint Online.

Step 1: Create a new color theme in SharePoint Online.

Themes are defined in a JSON schema that stores color settings and related metadata for each theme. Create a new custom theme for SharePoint Online using Microsoft Fluent UI Theme Designer, an online tool. Customize the theme as per your needs and click on the Export theme button. Copy and save the PowerShell output for later use.

Light Theme sample:


Dark Theme sample:


Step 2: Add a custom theme to SharePoint Online using PowerShell

First, connect to the SPO admin site using the Connect-SPOService cmdlet. The custom theme can be added to the SharePoint online tenant using the Add-SPOTheme cmdlet. This cmdlet creates a new theme or updates an existing theme. The color palette settings can be passed as either a hash table or a dictionary.

Execute the command for the light theme.



Now go to Site Settings, gear icon (⚙️) > Change the look > Theme and you'll find the newly added color theme listed under "From your organization".


Execute the same command for the dark theme.


Again, go to Site Settings gear icon (⚙️) > Change the look > Theme and you'll find the new added color theme listed under "From your organization".


When you choose a theme, color settings are instantly applied to the site so that you can see what the selected theme will look like. Select the desired theme, click Save to save your selection, or choose Cancel to revert to your current theme.

Our "Maroon - Light theme" output looks like




Our "Orange - Dark theme" output looks like




Update SP Theme
To update an existing theme (to modify some of its color settings, for example), add the -Overwrite flag to the Add-SPOTheme cmdlet.


I hope this will help all of you! 🧲
Feel free to provide feedback.


πŸš€ "Happy Coding" πŸš€

Wednesday, 6 December 2023

Create List templates using Site template and Site script

In this blog, we will be learning how to create list templates under the tab From your organization.

When people in the organization create new lists, they need a template that can be used each time a new list is created.

Site Script

A site script is a collection of actions that SharePoint runs when creating a new site or list. Actions describe changes to apply to the new list, such as creating new columns, adding views, or content types. The actions are specified in a JSON script, which is a list of all actions to apply. When a script runs, SharePoint completes each action in the order listed.

Site Template (previously known as Site Design)

Site templates can be used each time a new site is created to apply a consistent set of actions. Site templates created using custom site scripts will display in the From your organization tab.

A site script is a JSON string that contains the actions to be taken on a site. A site template, on the other hand, is like a container for the site script. You can attach one or more site scripts to a site template, and when you apply the site template, you execute the actions defined in all of the site scripts. It's like the site template is the visible surface part that can group several site scripts together, and the site scripts are all the action underneath.

Currently, no list template is available From your organization tab.


  • A site template can run multiple scripts. The script IDs are passed in an array, and they run in the order listed.
  • The former term for site templates may still appear in certain cmdlets and script labels as "site design".
  • The schema is case-sensitive.

Create a Site script in JSON

Create the script in JSON that describes the action to be executed on the list. You can view and reference the latest JSON schema file here: https://developer.microsoft.com/json-schemas/sp/site-design-script-actions.schema.json

In addition to constructing the JSON by hand, you can also use third-party tools with graphical user interfaces that generate the site scripts for you, such as sitedesigner.io by Mikko PunamΓ€ki or Site Template Studio by Yannick Plenevaux.

Exporting an existing list as a site script

In our scenario, we will be exporting an existing list configuration as a site script.
First, connect to the SPO admin site using the Connect-SPOService cmdlet. It can be achieved with the following script. The Get-SPOSiteScriptFromList cmdlet prints out the site script to the console. It can be saved into a variable, or you can copy and save it in a JSON file.


Deploy Site Script and Site Template

To use our site script, we need to deploy it to our tenant. We also need to create a site template where we can attach the deployed site script.

1) Add the site script

Each site script must be registered in SharePoint so that it is available to use. Add a new site script by using the Add-SPOSiteScript cmdlet.


After running the cmdlet, you get a result that lists the site script ID of the added script. Keep track of this ID, as it will be needed later when you create the site template.

2) Create the site template

Next, we will create the site template. Run the Add-SPOListDesign cmdlet to add a new site template. Use the script ID saved above when you added the site script. It can run one or more scripts that have already been added.


The JSON response displays the ID of the new site template. It can be used later on to update or modify the site template.

Get the existing Site Script and Site Template

After we have deployed our site script and site template to our tenant, we can see their properties and information about all other deployed site scripts and templates using the Get-SPOSiteScript and Get-SPOListDesign cmdlet.



Use the new site template

Now that we've added a site script and site template, we can use them to create a new list.



I hope this will help all of you! 🧲
Feel free to provide feedback.


πŸš€ "Happy Coding" πŸš€

Friday, 14 July 2023

PowerApps: Set the default user value in the Canvas app.

I came across one of the tasks in PowerApps to set the default value of the Person Type column.

In this blog, we will be learning how to set the default value in the Canvas app.

Please follow the below steps:

1. Create a new SharePoint list.

2. Create a Person/User type column called "Requestor Name".


3. Create a blank Canvas App with Format Tablet.

4. Add an Edit form control on screen and add the above created list as the data source for this form control. Set form DefaultMode to New.

5. For "Requestor Name DataCard" set the below value for the Default property.

Switch(
    frm_FileTransferService.Mode,
    FormMode.New,
    {
        '@odata.type': "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedUser",
        DisplayName:User().FullName,
        Claims:"i:0#.f|membership|" & Lower(User().Email),
        Email:User().Email,
        Picture:User().Image
    },
    FormMode.View,
    ThisItem.'Requestor Name'
)


6. No need to do any changes in the Update property value. Its shown for reference only.


7. Under "Requestor Name DataCard" for DataCardValue.

    a. Comment on the Items property value, as it's not required. The items property is for populating the data in the people picker.


    b. Set the below value for the DisplayMode property. This DisplayMode property is used to configure whether the control inside the card allows user input (Edit), only displays data (View), or is disabled (Disabled).

If(
    frm_FileTransferService.Mode = FormMode.New,
    Parent.DisplayMode.Disabled,
    Parent.DisplayMode
)


9. Save and Publish the app.

10. Play/Run the app. In the New Form, the logged-in user is shown as default, and editing is disabled.



πŸš€ "Happy Coding" πŸš€