Search code examples
javascriptreactjsarraysobjectspfx

Dynamically add values to specific property in object - Fluent UI React ContextualMenu


I have the following ContextualMenu structure inside my SPFx Extension build with Fluent UI React:

const menuProps: IContextualMenuProps = {
  items: [
    {
      key: 'Access',
      itemType: ContextualMenuItemType.Section,
      sectionProps: {
        topDivider: true,
        bottomDivider: true,
        title: 'Sites you have access to',
        items: [
          { key: 'DynamicValue1.1', text: 'DynamicValue1.2' },
          { key: 'DynamicValue2.1', text: 'DynamicValue2.2' },
        ],
      },
    },
  ],
};

I also a MS Graph call running getting me some SharePoint Sites & Teams.

I would now like to push those dynamic responses to the to the menuProps at the right place.

So basically add the dynamic array into the nested items object.

items: [
          { key: 'DynamicValue1.1', text: 'DynamicValue1.2' },
          { key: 'DynamicValue2.1', text: 'DynamicValue2.2' },
        ],

How can I target that "object"? (hope I understand correctly and items is an object...)

Is there a way to do this using array.push()?


Solution

  • To make this library agnostic, it would look something like this:

     const obj = {
      items: [
        {
          key: 'Access',
          itemType: '',
          sectionProps: {
            topDivider: true,
            bottomDivider: true,
            title: 'Sites you have access to',
            items: [
              { key: 'DynamicValue1.1', text: 'DynamicValue1.2' },
              { key: 'DynamicValue2.1', text: 'DynamicValue2.2' },
            ],
          },
        },
      ],
    };
    
    
    obj.items[0].sectionProps.items.push({ key: 'DynamicValue3.1', text: 'DynamicValue3.2' })
    
    console.log(obj.items[0].sectionProps.items)
    

    Your console.log would return this:

    [
      { key: 'DynamicValue1.1', text: 'DynamicValue1.2' },
      { key: 'DynamicValue2.1', text: 'DynamicValue2.2' },
      { key: 'DynamicValue3.1', text: 'DynamicValue3.2' }
    ]
    

    If you can access menuProps: IContextualMenuProps, then just replace obj with the necessary variable.