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.
- PS C:\XXXX\SPFxSolutions\SpFxRichTextEditor>npm install --save office-ui-fabric-react
Import "
office-ui-fabric-react" to your
.tsx file as shown below.
- 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
- import { ChoiceGroup } from 'office-ui-fabric-react';
- export default class ProjectTaskConstants{
- static get StatusOptions(){
- const statusOptions: IChoiceGroupOption[] = [
- { key: "Open", text: "Open" },
- { key: "Closed", text: "Closed" },
- { key: "On hold", text: "On hold" }
- ];
- return statusOptions;
- }
- }
Import ProjectTaskContants.ts file to your
.tsx file as shown below
- import ProjectTaskConstants from '../ProjectTaskConstants';
Instantiate the class file as shown below:
-
- public Constants = new ProjectTaskConstants();
Usage
In Render method, use the control as shown below:
- <ChoiceGroup
- id="status"
- name="StatusOptions"
- defaultSelectedKey="Open"
- options={Constants.StatusOptions}
- onChange={this.onStatusChange.bind(this)}
- selectedKey={this.state.Status}
- />
OnChange event:
- public onStatusChange(ev: React.FormEvent<HTMLInputElement>, option: any): void {
- this.setState({
- Status: option.key
- });
- }
In the above example, I have used "Status" state variable of type string.
To disable the choice group:
- <ChoiceGroup
- id="status"
- name="StatusOptions"
- defaultSelectedKey="Open"
- options={Constants.StatusOptions}
- selectedKey={this.state.Status}
- disabled={true}
- />
Please feel free to share your comments.