0

I have a requirement to add custom data attributes to the Fluent UI dropdown. In javascript/html I could add them like this.

option data-passign="true" data-minpt="3" data-maxpt="6" value="7">Data Quality</option

Can someone help me achieve this in Fluent UI + React?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tok2vb
  • 3
  • 4
  • Should these custom attributes be visible as HTML attributes, or just data attributes (visible to JavaScript only)? Note that if you look at the dropdown control, there are no ` – Nikolay Jun 13 '21 at 18:31
  • This is for the JS/TS to read from HTML attributes. This helps me from making 2nd API call and get all data elements in one call. This is not for UI automation. Hope this helps. – tok2vb Jun 18 '21 at 17:31

1 Answers1

1

In FluentUI/React, it's much easier than that, no need for data- attributes, you can just add your custom data directly to the options list (and get it back in the event handlers, or as the selected value if you are using "controlled" scenario). Means, if you don't have a specific requirement to store additional item data in the HTML data attributes for "something else" (like ui-automation tool), then you could go with something like this (note the data property):

const YourComponent = (props) => {

  const options = [
    { key: '7', 
      text: 'Data Quality', 
      data: { passign: true, minpt: 3, maxpt: 7 } 
    },
    { key: '42', 
      text: 'Weather Quality',
      data: { passign: true, minpt: 100500, maxpt: 42 } 
    },
  ];
  
  const onChange = (evt, item) => {
    const itemData = item.data;
    console.log(item.key, item.text, itemData);
  };
  
  return (
    <Dropdown 
      label="Select something" 
      options={options} 
      defaultSelectedKey='7'
      onChange={onChange} 
    />
  );
}

If you want a "controlled" control instead (this one is "uncontrolled"), check out the sample page for the Dropdown: https://developer.microsoft.com/en-us/fluentui#/controls/web/dropdown

Nikolay
  • 10,752
  • 2
  • 23
  • 51