December 2, 2020

How to clear Office UI Fabric multi-select dropdown in SPFx webpart with React Framework?

Scenario:

We implemented a webpart using SharePoint Framework (SPFx) that includes the filter functionality. As per the requirement, we have one dropdown that allows multiple options selection for filter functionality. Now when user clicks on the "Clear Filter" button, it should clear the selection of options from the dropdown.

Below is our dropdown control with multiple items selection:
 <Dropdown  
  multiSelect  
  className="multiSelectDrodpown"  
  options={currentObj.state.dropdownOptions}  
  defaultSelectedKeys={this.state.selectedOptions}  
  onChanged={(val) => currentObj.filterData(val)}           
 ></Dropdown>  

Note:
  • dropdownOptions state contains all the options which will be display in multi select dropdown control.
  • selectedOptions is the state which contains the options which are currently selected.


Problem Statement:

  • When we select the values from the multi-select dropdown control, we pass those values to defaultSelectedKeys parameter of the multi-dropdown control to show the selected values. 
  • But when we clear the value of the state which we are using in defaultSelectedKeys parameter(selectedOptions state in our scenario), it does not clear the selection of multi-select dropdown.


Solution:

  • To resolve this issue, we need to use the "key" parameter of the office fabric UI dropdown control and set the unique number as the value on click event of the "Clear Filter" button.
  • Using a new value for key parameter means, it renders fresh control each time.
  • Here, we use randomIndex state to set a new key value to generate a random number. Below is an example to use key attribute:
 <Dropdown  
  multiSelect  
  className="multiSelectDrodpown"  
  options={currentObj.state.dropdownOptions}  
  defaultSelectedKeys={this.state.selectedOptions}  
  onChanged={(val) => currentObj.filterData(val)}     
  key={this.state.randomIndex}        
 ></Dropdown>  
  • Now, when user clicks the "Clear Filter" button, it will update randomIndex state and set a new random number as its value.
  • Here, we are using Math.floor and Math.random()  function to generate random numbers.
 private async clearFields() {  
      await this.setState({    
          randomIndex: Math.floor(Math.random() * 6) + 1          
       });  
 }  


Conclusion:

This is how we can clear the value of multi-select dropdownlist in SharePoint Framework (SPFx).

If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment