reactjsoffice-ui-fabricoffice-fabric

How do I stop Office Fabric Dropdown from selecting first element on focus?


I am using the Dropdown from Office Fabric in React. I have many dropdowns that I am happy to select the first element by default, but I have some that I do not want this behavior. When I put a breakpoint in the debugger onDropdownChange() is being called when I click onto the dropdown for the first time.

I was able to trace the event to Dropdown.base.js, where I see this code, which seems to force a focus on the first element if none are selected:

        _this._onFocus = function (ev) {
            var _a = _this.state, isOpen = _a.isOpen, selectedIndices = _a.selectedIndices;
            var multiSelect = _this.props.multiSelect;
            var disabled = _this._isDisabled();
            if (!disabled) {
                if (!isOpen && selectedIndices.length === 0 && !multiSelect) {
                    // Per aria
                    _this._moveIndex(ev, 1, 0, -1);
                }
                if (_this.props.onFocus) {
                    _this.props.onFocus(ev);
                }
                _this.setState({ hasFocus: true });
            }
        };

Here is my dropdown rendering code:

        return <Dropdown
            selectedKey={selected}
            placeholder={placeholder}
            ariaLabel={this.props.ariaLabel || this.props.label}
            label={this.props.label}
            onChange={this.onDropdownChange}
            options={this.getDropdownOptions()}
        />

Is there a way that I can get around this? I see others use office fabric and not have this behavior, such as VSO with their Columns Options pane (which is what I am building for my own site), but I don't see what I need to do or if they somehow custom handled it. The only idea I have so far as to put a blank entry as an option and then pre-select it. It is not only that it selects the first entry, but when I click the dropdown of the combo box for the first time it just selects the first option and doesn't pop open the dropdown.


Solution

  • Indeed, this is the default behavior, on focus event the first available dropdown option is getting selected. One option to override this behavior would be:

    a) to introduce a default option

     <Dropdown componentRef={this.dropdownRef}
          styles={dropDownStyles}
          onFocus={this.handleDrownDownFocus}
          options={[
            { key: "All", text: "", disabled: true },
            { key: "A", text: "Option A" },
            { key: "B", text: "Option B" }
          ]}
     />
    

    b) and force it to get selected on focus event

    private handleDrownDownFocus(ev: React.FormEvent<HTMLDivElement>) {
       const dropDown = this.dropdownRef.current;
       if(dropDown && !this.selectedDefault){
         dropDown.setSelectedIndex(ev,0);
         this.selectedDefault = true
       }
    }
    

    Here is a demo