Search code examples
reactjsspfxfluent-ui

Custom data attributes on Fluent UI dropdown


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?


Solution

  • 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