Introduction
Checkboxes are a great way to choose one or multiple options within many choices. Office UI Fabric/Flunet UI controls provides the simplest checkbox implementation that can be used in the SharePoint Framework. When clicked, the checkbox fires the "onChange" event. However, grouping them is a challenge.
In this article, we will explore dynamically grouping the checkboxes, and handle the selection event for them.
Checkbox implementation in SPFx
Imports for Checkbox control:
- import { Checkbox} from 'office-ui-fabric-react/lib/Checkbox';
Use Checkbox in render method.
- <Checkbox label="Choices" onChange={_onChange} />
The onChange is invoked on Checkbox’s value change.
- function _onChange(ev: React.FormEvent<HTMLElement>, isChecked: boolean) {
- console.log(“The selection ${isChecked}.”);
- }
Now, when we check/uncheck the Checkbox, it fires the onChange event which helps detect the changed value. We can have multiple checkboxes, each implementing an onChange event.
Dynamic Checkboxes
In the real world, we have to dynamically create Checkboxes and group them based on the business logic.
Let us consider the below data to build dynamic Checkboxes.
- const options: ICheckboxInput[] = [
- { ID: 1, Title: 'Apple' },
- { ID: 2, Title: 'Banana' },
- { ID: 3, Title: 'Fig' },
- { ID: 4, Title: 'Grape' },
- { ID: 5, Title: 'Kiwi' },
- { ID: 6, Title: 'Melon' },
- { ID: 7, Title: 'Orange' },
- { ID: 8, Title: 'Pineapple' }
- ];
Inside the render method, we will use this data to dynamically build a Checkbox to group them together.
- options.map((checkBoxItem: ICheckboxInput) => {
- return (
- <Checkbox label={checkBoxItem.Title} title={checkBoxItem.Title} onChange={this._onChange} />
- );
- })
The dynamic listing of Checkboxes can be seen as shown below:
Each dynamic checkbox when clicked raises an onChange event, which is our common method. This means that inside the common method, it is difficult to get the exact Checkbox that raised the event.
Solution
React.FormEvent parameter to onChange event contains the information about Checkbox control checked/unchecked. The “currentTarget” property is our friend.
Update the onChange event as follows:
- private _onChange(ev: React.FormEvent<HTMLInputElement>, isChecked: boolean) {
- console.log(`The option ${ev.currentTarget.title} is changed to ${isChecked}.`);
- }
As we have set the “title” property on the Checkbox, we were able to get it back from currentTarget.
Summary
The Fluent UI /Office UI Fabric controls have the simplest implementation of Checkbox. With dynamic Checkbox collection, it's a bit tricky to get the selection. The property set on Checkbox during the control creation can be retrieved from currentTarget to get the selection.
Code Sample
The code sample developed during this article can be found
here.