Skip to main content

Add dynamic control on property panel conditionally in SharePoint SPFx

How we can add text, select and checkbox fields dynamically to provide a rich and meaningful full user experience in the SPFx framework?

Solution provided:

The answer is yes, it is possible to add, show, hide inputs fields conditionally based on the user requirement in the SPFx framework property panel in the SharePoint modern side to realize how modern it is and which can be used only on demand.

To achieve that kind of feature we just need to use some logic on our solution, so, don't be worried I am going to tell you all here about the new project.

Step-1
Open the PowerShell or Visual Studio Code and run the command to create the new solution
yo @microsoft/sharepoint   
then select the solution name and WebPart name, in my case I created DynamicControl as the solution name.

Once it is completed need to run
gulp build
after the successful build up the solution
you only need to follow the below steps to achieve it on your solution

To achieve this you need to write some logic in your main component.ts file, in my case, I am opened the DynamicWebPart.ts file

Step-2 
Need to import some library or add in existing
import {
  IPropertyPaneConfiguration,
  PropertyPaneTextField, IPropertyPaneGroup, PropertyPaneCheckbox,
PropertyPaneDropdown,IPropertyPaneDropdownOption, PropertyPaneChoiceGroup,
PropertyPaneButton
} from '@microsoft/sp-property-pane';

Step-3
add your logic inside 
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    const lists : IPropertyPaneDropdownOption[] = [{ key: 1, text: "BMW"},{key: 2, text:"Fiat"},{key: 3, text:"Hundai"},{key: 4, text:"Ford"}];
    const conditionalGroupFields1: IPropertyPaneGroup["groupFields"] = [
      PropertyPaneCheckbox("Field1", {
        text: "Show Box 1",
      }),
     ]
Step-4
you can add your own controls like in my case I use textbox fields

protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    const lists : IPropertyPaneDropdownOption[] = [{ key: 1, text: "BMW"}
,{key: 2, text:"Fiat"},{key: 3, text:"Hundai"},{key: 4, text:"Ford"}];
    const conditionalGroupFields1: IPropertyPaneGroup["groupFields"] = [
      PropertyPaneCheckbox("Field1", {
        text: "Show Box 1",
      }),
     ]

     if(this.properties.Field1) {
      conditionalGroupFields1.push(      
            PropertyPaneTextField('imageLink1', {
              label: "Set an image URL"
            }),
            PropertyPaneTextField('heading1', {
              label: "Set a heading"
            }),  
            PropertyPaneTextField('description1', {
              label: "Set a description"
            }),
            PropertyPaneTextField('redirectURL1', {
              label: "Set a redirection URL"
            }),





Step-5

Finally, you need to add variables in group fields




below is the final code of DynamicControlWebPart.ts file for only TextBox

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  PropertyPaneTextField, IPropertyPaneGroup,
PropertyPaneCheckbox, PropertyPaneDropdown,IPropertyPaneDropdownOption,
PropertyPaneChoiceGroup, PropertyPaneButton
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import * as strings from 'DyanmicControlWebPartStrings';
import DyanmicControl from './components/DyanmicControl';
import { IDyanmicControlProps } from './components/IDyanmicControlProps';


export interface IDyanmicControlWebPartProps {
  description: string;
  Field1: string;
}

export default class DyanmicControlWebPart extends
BaseClientSideWebPart<IDyanmicControlWebPartProps> {

  public render(): void {
    const element: React.ReactElement<IDyanmicControlProps>
     = React.createElement(
      DyanmicControl,
      {
        description: this.properties.description,
        Field1:this.properties.Field1,
      }
    );

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

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

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

  private Call = (e) => {
      alert("Button 1, Clicked");
  }
  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    const lists : IPropertyPaneDropdownOption[] = [{ key: 1, text: "BMW"},
    {key: 2, text:"Fiat"},{key: 3, text:"Hundai"},{key: 4, text:"Ford"}];
    const conditionalGroupFields1: IPropertyPaneGroup["groupFields"] = [
      PropertyPaneCheckbox("Field1", {
        text: "Show Box 1",
      }),
     ]

     if(this.properties.Field1) {
      conditionalGroupFields1.push(      
            PropertyPaneTextField('imageLink1', {
              label: "Set an image URL"
            }),
            PropertyPaneTextField('heading1', {
              label: "Set a heading"
            }),  
            PropertyPaneTextField('description1', {
              label: "Set a description"
            }),
            PropertyPaneTextField('redirectURL1', {
              label: "Set a redirection URL"
            }),
               
       );
    }

    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [                     
            {
               groupFields: conditionalGroupFields1,
            },           
          ]
        }
      ]
    };
  }
}


Based on your requirement you can use any control here, you can add a drop-down list, checkbox, radio buttons as well, also, you can apply the nested logic of dynamic control generation in a cascaded manner.
To Add Drop-Down List: 
To add a drop-down list, dynamic control need to add some more lines of code, as below


protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    const lists : IPropertyPaneDropdownOption[] = [{ key: 1, text: "BMW"},
{key: 2, text:"Fiat"},{key: 3, text:"Hundai"},{key: 4, text:"Ford"}];

PropertyPaneDropdown('listName', {
              label: "My Drop Down List",
              options: lists,              
            }),
   
To Add Choice-Select Control:
To add, Choice-Select below is the extra steps need to do, don't be worried I will share the complete code of the solution.

protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    const lists : IPropertyPaneDropdownOption[] = [{ key: 1, text: "BMW"},
{key: 2, text:"Fiat"},{key: 3, text:"Hundai"},{key: 4, text:"Ford"}];


PropertyPaneChoiceGroup('listName2', {
              label: "My Choice List",
              options: lists,              
            }),


To Add-Buton Control:
To add-Button Control, need to add a one-clicked event and the line of code for the button control


PropertyPaneButton('btn',{
              text:"Button 1",
              onClick: this.Call
            })


This is the final code of DyanmicControlWebPart.ts

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
 IPropertyPaneConfiguration,
 PropertyPaneTextField, IPropertyPaneGroup, PropertyPaneCheckbox,
PropertyPaneDropdown,IPropertyPaneDropdownOption, PropertyPaneChoiceGroup,
PropertyPaneButton
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import * as strings from 'DyanmicControlWebPartStrings';
import DyanmicControl from './components/DyanmicControl';
import { IDyanmicControlProps } from './components/IDyanmicControlProps';


export interface IDyanmicControlWebPartProps {
  description: string;
  Field1: string;
}

export default class DyanmicControlWebPart extends
BaseClientSideWebPart<IDyanmicControlWebPartProps> {

  public render(): void {
    const element: React.ReactElement<IDyanmicControlProps>
     = React.createElement(
      DyanmicControl,
      {
        description: this.properties.description,
        Field1:this.properties.Field1,
      }
    );

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

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

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

  private Call = (e) => {
      alert("Button 1, Clicked");
  }
  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    const lists : IPropertyPaneDropdownOption[] = [{ key: 1, text: "BMW"},
    {key: 2, text:"Fiat"},{key: 3, text:"Hundai"},{key: 4, text:"Ford"}];
    const conditionalGroupFields1: IPropertyPaneGroup["groupFields"] = [
      PropertyPaneCheckbox("Field1", {
        text: "Show Box 1",
      }),
     ]
     if(this.properties.Field1) {
      conditionalGroupFields1.push(      
            PropertyPaneTextField('imageLink1', {
              label: "Set an image URL"
            }),
            PropertyPaneTextField('heading1', {
              label: "Set a heading"
            }),  
            PropertyPaneTextField('description1', {
              label: "Set a description"
            }),
            PropertyPaneTextField('redirectURL1', {
              label: "Set a redirection URL"
            }),
            PropertyPaneDropdown('listName', {
              label: "My Drop Down List",
              options: lists,              
            }),
            PropertyPaneChoiceGroup('listName2', {
              label: "My Choice List",
              options: lists,              
            }),
            PropertyPaneButton('btn',{
              text:"Button 1",
              onClick: this.Call
            })      
       );
    }

    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [                     
            {
               groupFields: conditionalGroupFields1,
            },            
          ]
        }
      ]
    };
  }
}

Click here to download the source code.
I am hoping it will help, please write your comments here to share your feedback, so that, I will improve my blogs to make them more meaning full.
Thank you :)
Happy Coding...


Comments

  1. Thanks for sharing the best information and suggestions, it is very nice and very useful to us. I appreciate the work that you have shared in this post. Keep sharing these types of articles here.keyword

    ReplyDelete
  2. Thanks for this great guide for beginners to learn how to make the property pane reactive!

    ReplyDelete

Post a Comment

Popular posts from this blog

Interview Questions of SPFx SharePoint

What is SPFx? The SharePoint Framework (SPFx) is a web part model that provides full support for client-side SharePoint development, it is easy to integrate with SharePoint data, and extend Microsoft Teams. With the SharePoint Framework, you can use modern web technologies and tools in your preferred development environment to build productive experiences and apps that are responsive and mobile-ready. Scenario Based asking Scenario 1: Scenario: Your team is developing a SharePoint Framework (SPFx) web part that needs to retrieve data from an external API and display it on a SharePoint site. The API requires authentication using OAuth 2.0. The web part should also allow users to refresh the data manually. Question 1: How would you approach implementing this functionality in an SPFx web

Power Apps modern driven app Interview Question and answer

Question 1: What is a Power Apps modern driven app? Answer: A Power Apps modern driven app is a low-code/no-code application development platform provided by Microsoft. It allows users to create custom applications that can run on various devices and platforms without the need for extensive coding. These apps can be built using a visual interface and can integrate with different data sources. Question 2: What are the key components of a Power Apps modern driven app? Answer: The key components of a Power Apps modern driven app are: Screens : Screens serve as the user interface for the app and can include multiple layouts, controls, and data visualizations. Data sources : These are the various repositories where the app can retrieve and store data, such as SharePoint lists, SQL databases, Excel files, etc. Connectors : Connectors enable integration with external services and systems, allowing data to be fetched or updated. Formulas : Power Apps uses a formula language called Power Apps

Interview Question of Advanced SharePoint SPFx

1. What is WebPack? A module bundling system built on top of Node. js framework is known as a WebPack. It is capable to handle the combination and minification of JavaScript and CSS files, also other files such as images by using plugins. WebPack is the recommended way of bundling the files in JS framework and .Net frameworks. In the SPFx it is used with React Js. 2. What is PowerShell.? PowerShell is a platform introduced by Microsoft to perform cross-platform task automation and configuration management framework, it is made up of a command-line shell, a scripting language. it can be run on Windows, Linux, and macOS. 3. What is bundling and Minification? The terms bundling and minification are the processes of code compressing, which is used to improve the load and request time, It is used in modern JavaScript frameworks and .Net frameworks. It improves the load time by reducing the number of requests to the s