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?

2
  • 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 <option>s, it's built out of <div>s and <button>s. So if it's for UI automation, it won't help much. Means the main question is the purpose of these attributes. Commented Jun 13, 2021 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. Commented Jun 18, 2021 at 17:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton Nikolay. It worked and saved from making 2nd API call.
you can accept the answer then, this will give me a warm feeling of accomplishment :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.