Office UI Fabric Choice Group Integration in SharePoint Framework (SPFx)

Introduction

In this blog, we will learn how to integrate an Office UI Fabric ChoiceGroup control in the SharePoint Framework (SPFx).

The ChoiceGroup component, also known as radio buttons, lets users select one option from two or more choices. Each option is represented by one ChoiceGroup button; a user can select only one ChoiceGroup in a button group.
The below steps explain how to integrate choice group control in your SPFx solution, and how to store values to state variable on change.
 
Steps Involved
 
Install "office-ui-fabric-react" from the node package manager as shown below. 
  1. PS C:\XXXX\SPFxSolutions\SpFxRichTextEditor>npm install --save office-ui-fabric-react  
Import "office-ui-fabric-react" to your .tsx file as shown below. 
  1. import { ChoiceGroup } from 'office-ui-fabric-react';  
In this blog, I have used class file (ProjectTaskConstants.ts) to hold all the values to be populated in choice group as shown below
 
ProjectTaskContants.ts 
  1. import { ChoiceGroup } from 'office-ui-fabric-react';  
  2. export default class ProjectTaskConstants{  
  3.     static get StatusOptions(){  
  4.         const statusOptions: IChoiceGroupOption[] = [  
  5.             { key: "Open", text: "Open" },  
  6.             { key: "Closed", text: "Closed" },  
  7.             { key: "On hold", text: "On hold" }  
  8.         ];  
  9.         return statusOptions;  
  10.     }      
  11. }  
Import ProjectTaskContants.ts file to your .tsx file as shown below 
  1. import ProjectTaskConstants from '../ProjectTaskConstants';  
Instantiate the class file as shown below:
  1. /*This to get all the constant values*/  
  2.   public Constants = new ProjectTaskConstants();  
Usage
 
In Render method, use the control as shown below: 
  1. <ChoiceGroup  
  2.      id="status"  
  3.      name="StatusOptions"  
  4.      defaultSelectedKey="Open"  
  5.      options={Constants.StatusOptions}  
  6.      onChange={this.onStatusChange.bind(this)}  
  7.      selectedKey={this.state.Status}         
  8.    />  
OnChange event:
  1. public onStatusChange(ev: React.FormEvent<HTMLInputElement>, option: any): void {  
  2.     this.setState({  
  3.       Status: option.key  
  4.     });  
  5. }  
In the above example, I have used "Status" state variable of type string. 
 
To disable the choice group:
  1. <ChoiceGroup  
  2.      id="status"  
  3.      name="StatusOptions"  
  4.      defaultSelectedKey="Open"  
  5.      options={Constants.StatusOptions}  
  6.      selectedKey={this.state.Status}  
  7.      disabled={true}  
  8.  />   
Please feel free to share your comments.
 
Hope this helps!!!!!