SPFx – Office UI Fabric React – TagPicker – Item Limit

Inside Office UI Fabric React you could find TagPicker. For example, you could use it for country picker. In this scenario you would like to allow single selection mode on it.

In a correlation with office-ui-fabric-react fix #1304 they added property itemLimit on the basePicker and logic to not render the autofill “input” if the itemLimit is defined and equal to internal item count.

But inside last SPFx Yeoman Web Part template there is not yet this fix included in sp-office-ui-fabric-core, so you have to implement it by yourself. In example below I want to share with you my solution for this problem.

In TSX file of React Component you have to import TagPicker from Office UI Fabric React first:

import { TagPicker } from 'office-ui-fabric-react/lib/components/pickers/TagPicker/TagPicker';

Then you define property isPickerDisabled as state of React Component:

export interface ISpeakerSubmissionState {
  isPickerDisabled: boolean;
}

In constructor of React Component set default value for this property:

constructor(props: ISpeakerSubmissionProps) {
    super(props);

    this.state = {
      isPickerDisabled: false
    };
}

Then add TagPicker element inside render() method and bind isPickerDisabled property with disabled property of element:

<TagPicker ref={(input) => { this.sCountry = input; }}
    onResolveSuggestions={ this.Country_onFilterChanged }
    onChange={ this.Country_onChange }
    getTextFromItem={ this.Country_getTextFromItem }
    pickerSuggestionsProps={
      {
        suggestionsHeaderText: 'Suggested Items',
        noResultsFoundText: 'No Items Found'
      }
    }
    disabled={ this.state.isPickerDisabled }
    inputProps={ {
      onBlur: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onBlur called'),
      onFocus: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onFocus called')
    } }
/>

And the last step is to define Country_onChange method wich is binded to onChange event of TagPicker. In this method you have to check how many items we have currently selected.

@autobind
private Country_onChange(tagList: { key: string, name: string }[]) {
    if (tagList && tagList.length >= 1) {
      this.setState({
        isPickerDisabled: true
      });
    } else {
      this.setState({
        isPickerDisabled: false
      });
    }
}

[ Complete code on GitHub ]

Cheers!
Gašper Rupnik

{End.}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: