Search code examples
reactjsfluent-ui

React FluentUI Component Not Updating


I've got a FluentUI Dropdown component in a Sharepoint webpart that's acting strangely, it's defined as follows:

<Dropdown
  defaultSelectedKey={new Date().getMonth()}
  options={getMonthSelection()}
  styles={dropdownStyles}
  onChange={this.handleTimePeriodChange}
  selectedKey={this.state.month}
/>

When the onChange event fires it calls the following function:

private handleTimePeriodChange(event, option, index) {
    this.setState({
        month: option.key
    });
}

Everything works totally fine except that the Dropdown UI element doesn't change to reflect the new selection. If I remove the call to setState() then the UI element updates to reflect the selection but then the state isn't updated.

Can anyone see where I'm going wrong and if there's a way I can update the state properties without breaking the UI element?


Solution

  • The issue is in the definition of the Dropdown component itself and is due to the defaultSelectedKey property. I think what's happening here is that instead of setting an initial value for the dropdown, it seems to be binding the control to the passed in object; the result in the above code is that the Dropdown value is bound to the new Date().getMonth() even though the selectedKey is bound to the 'month' state property.

    The solution is to set the defaultSelectedKey to the state property directly on initialisation and then set the state property to the current month like so:

    <Dropdown
        defaultSelectedKey={this.state.month}
        options={getMonthSelection()}
        styles={dropdownStyles}
        onChange={this.handleTimePeriodChange}
    />
    

    When I do this, the Dropdown selection is now bound to the state property itself and thus any changes to the state property are reflected in the UI element.