Home > Software design >  Getting selection from Fluent UI dropdown in React project
Getting selection from Fluent UI dropdown in React project

Time:08-04

I am printing to the console a user selection from a Fluent UI dropdown. The only challenge I'm running into is grabbing the actual selection. I don't see how FLUENT is handling that, as it's not mentioned in their documentation.

My code looks like this:

<Dropdown
  placeholder="Select Reason"
  label="Send to History with Reason"
  onChange={(selectedKey) => this.onReasonChange(selectedKey)}
  options={this.graveyardReasons}
  onRenderLabel={this.onRenderLabel}
  styles={{
    root: {
      maxWidth: 300,
      minWidth: 300,
    },
  }}
/>

And here's the function that gets called on a selection being made:

onReasonChange = (selection) => {
  console.log('selection.target: ', selection.target);
};

This is what prints to the console:

<div data-is-focusable="true" id="Dropdown23" tabindex="0" role="listbox" aria-haspopup="listbox" aria-expanded="false" aria-labelledby="Dropdown23-label Dropdown23-option" ><span id="Dropdown23-option"  aria-live="polite" aria-atomic="true" aria-invalid="false" role="option" aria-setsize="4" aria-posinset="2" aria-selected="true">Selection 1</span></div>

How do I pull the value Selection 1 from this div? And, is there a simpler way to get the value that I'm simply missing?

CodePudding user response:

As Fluent UI docs says about onChange:

(
    event: React.FormEvent<HTMLDivElement>, 
    option?: IDropdownOption, 
    index?: number
) => void

Callback issued when the selected option changes.

So selected value is the second parameter. Let me show an example:

const DropdownBasicExample: React.FunctionComponent = () => {
  const onReasonChange = (e, selection) => {
      console.log('selection: ', selection);
  };
  
  return (
    <Stack tokens={stackTokens}>
      <Dropdown
        placeholder="Select an option 1"
        label="Basic uncontrolled example"
        onChange={onReasonChange}
        options={options}
        styles={dropdownStyles}
      />      
    </Stack>
  );
};
  • Related