Shankar Nanda
Shankar Nanda

Reputation: 139

How to build semantic-ui dropdown which includes header dynamically?

I have dropdown options as

const options = [
    { key: '1', text: 'Example 1', value: 'Example 1', type:'ABC' },
    { key: '2', text: 'Example 2', value: 'Example 2', type:'XYZ' },
    { key: '3', text: 'Example 3', value: 'Example 3', type:'ABC' },
    { key: '4', text: 'Example 4', value: 'Example 4', type:'XYZ' },
  ];

I want to build semantic-ui dropdown dynamically such that ,each dropdown value will come under their respective 'type' value.

In this case Example 1,Example 3 will come under 'ABC' Header tag, and Example 2,Example 4 under 'XYZ' Header tag.

ABC
  Example 2
  Example 4
XYZ
  Example 2
  Example 4

Upvotes: 0

Views: 321

Answers (1)

Shankar Nanda
Shankar Nanda

Reputation: 139

I tried to solve it by following way. First get all distinct categories of array of option.

categories = options.reduce((acc,curr)=> !acc.includes(curr.type)? [...acc,curr.type]: [...acc]  ,[]).slice()

Then I need to map all possible json to it's respective type

categories.map(x=>{
  resOption[x]= options.filter(j => j.type===x).slice()
})

My full code here

 var resOption = {}
  var categories =[]

categories = options.reduce((acc,curr)=> !acc.includes(curr.type)? [...acc,curr.type]: [...acc]  ,[]).slice()

categories.map(x=>{
  resOption[x]= options.filter(j => j.type===x).slice()
})

return(
  <Dropdown  selection >
    <Dropdown.Menu>
      {
        Object.keys(resOption).map((type)=>(
          <React.Fragment>
          <Dropdown.Header content={type} style={{color:"#5aa7e6"}} />
            {
              resOption[type].map((option)=>(
                <Dropdown.Item text={option.text} value={option.value}  onClick={onChange} />
              ))
            }
          <Dropdown.Divider />
          </React.Fragment>
        ))
      }
    </Dropdown.Menu>
  </Dropdown>
)

Upvotes: 1

Related Questions