Getting external data in the render function of a tsx file: A step-by-step guide

Currently, I am working on developing an ApplicationCustomizer SPFX extension for SharePoint Online using visual studio code and react with Typescript. My goal is to incorporate a commandbar fabric UI component in the header section to display a fabric UI drop-down menu. So far, I have successfully implemented this based on the available sample codes.

However, I now need to retrieve the menu items string from an external text file located in the SiteAssets folder on SharePoint. This text file contains the required menu items format. Can someone provide me with guidance on how to modify the code within the getItems() function to fetch the text from an external file? Below is an excerpt of my tsx code file:

import * as React from "react";  
import { Link } from 'office-ui-fabric-react/lib/Link';  
import { CommandBar } from 'office-ui-fabric-react/lib/CommandBar';  
import { SPHttpClient, SPHttpClientResponse, SPHttpClientConfiguration } from '@microsoft/sp-http'; 
  
export interface IReactHeaderProps {  }  
  
export default class ReactHeader extends React.Component<IReactHeaderProps> {  
  constructor(props: IReactHeaderProps) {  
    super(props);  
  }  
  
  public render(): JSX.Element {  
    
    return (  
      <div className={"ms-bgColor-themeDark ms-fontColor-white"}>  
       <CommandBar  items={this.getItems()}  />   
      </div>  
    );  
  }  
  
  // Data for CommandBar  
  private getItems = () => {      
    return [  
      **

{  
        key: 'menu1',  
        name: 'Main Menu 1',  
        cacheKey: 'myCacheKey', 
        iconProps: {  iconName: 'ChevronDown'  },  
        href: '#'  ,
        subMenuProps: {
          items: [
            {
              key: 'submenu1',
              name: 'Option 1',                                          
              href: '#',
            },
            {
              key: 'submenu2',
              name: 'Option 2',              
              href: '#',
            },
          ],
        },
      },  
      {
        key: 'menu2',
        name: 'Main Menu 2',
        cacheKey: 'myCacheKey', 
        iconProps: { iconName: 'ChevronDown' },
        href: '#',
        subMenuProps: {
          items: [
            {
              key: 'submenu3.1',
              name: 'Option 1',
              href: '#',
              subMenuProps: {
                items: [
                  {
                    key: 'submenu3.2',
                    name: 'Option 1.1',
                    href: '#',
                  },
                  {
                    key: 'submenu4.2',
                    name: 'Option 1.2',
                    href: '#',
                  },
                ],
              },
            },
            {
              key: 'submenu4',
              name: 'Option 2',
              href: '#',
            },
          ],
        },
      },          
    ];  
  }  
}

Answer №1

@Osden Pereira,

Please refer to the code snippet provided below:

import * as React from 'react';
import styles from './Externalfile.module.scss';
import { IExternalfileProps } from './IExternalfileProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { CommandBar } from 'office-ui-fabric-react/lib/CommandBar';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { IExternalfileState } from './IExternalfileState';

export default class Externalfile extends React.Component<IExternalfileProps, IExternalfileState> {

  constructor(props: IExternalfileProps) {
    super(props);
    this.state = {
      Items: []
    };
  }

  public render(): React.ReactElement<IExternalfileProps> {
    return (
      <div className={styles.externalfile}>
        <div className={"ms-bgColor-themeDark ms-fontColor-white"}>
          <CommandBar items={this.state.Items} />
        </div>
      </div>
    );
  }

  public componentDidMount() {
    this.getItems01();
  }

  // Data for CommandBar
  private getItems01() { 
    let url = this.props.ctx.pageContext.site.serverRelativeUrl + "/SiteAssets/testjson.txt";
    this.props.ctx.spHttpClient.get(url, SPHttpClient.configurations.v1).then(res => {
      return res.json();
    }).then(e => {
      this.setState({
        Items: e
      });
    });
  } 
}

IExternalfileState.ts:

export interface IExternalfileState {
  Items: [];
}

Json file: https://i.sstatic.net/RfgfD.png

[
   {
      "key":"menu1",
      "name":"Main Menu 1",
      "cacheKey":"myCacheKey",
      "iconProps":{
         "iconName":"ChevronDown"
      },
      "href":"#",
      "subMenuProps":{
         "items":[
            {
               "key":"submenu1",
               "name":"Option 1",
               "href":"#"
            },
            {
               "key":"submenu2",
               "name":"Option 2",
               "href":"#"
            }
         ]
      }
   },
   {
      "key":"menu2",
      "name":"Main Menu 2",
      "cacheKey":"myCacheKey",
      "iconProps":{
         "iconName":"ChevronDown"
      },
      "href":"#",
      "subMenuProps":{
         "items":[
            {
               "key":"submenu3.1",
               "name":"Option 1",
               "href":"#",
               "subMenuProps":{
                  "items":[
                     {
                        "key":"submenu3.2",
                        "name":"Option 1.1",
                        "href":"#"
                     },
                     {
                        "key":"submenu4.2",
                        "name":"Option 1.2",
                        "href":"#"
                     }
                  ]
               }
            },
            {
               "key":"submenu4",
               "name":"Option 2",
               "href":"#"
            }
         ]
      }
   }
]

https://i.sstatic.net/nQeyE.png

BR

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve all properties within a Typescript Class that includes optional properties?

If we have a scenario where: class ExampleType { item1?: string, item2?: string } and all the properties are OPTIONAL. Is there a way to generate an array of property names like: ["item1", "item2"] I attempted to use console.log( ...

The switch statement and corresponding if-else loop consistently produce incorrect results

I'm currently facing an issue where I need to display different icons next to documents based on their file types using Angular framework. However, no matter what file type I set as the fileExtension variable (e.g., txt or jpg), it always defaults to ...

Combine the outcomes of various AJAX requests into one variable

Looking to make 2 recursive API calls to create a JQuery datatables page with data from the range of 2016-2021. The API responses are split based on year filters to bypass the 5000 item list limit set by Sharepoint Online. Struggling to combine all API re ...

Using the watch flag in TypeScript across multiple projects - A comprehensive guide

In my project, I have the following scripts section in the package.json: "watch": "?", "build": "npm run build:compactor && npm run build:generator && npm run build:cleaner", "build:lambda": ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

Ensure that a function completes before moving on in JavaScript

I am attempting to modify the save method so that it waits for this.collection.create() to complete before running, in order to prevent a potential crash. class UserRepository extends BaseRepository<User> { constructor() { super(); ...

Exploring objects nested within other types in Typescript is a powerful tool for

My journey with TypeScript is still in its early stages, and I find myself grappling with a specific challenge. The structure I am working with is as follows: I have a function that populates data for a timeline component. The data passed to this function ...

The process of adding new files to an event's index

I'm trying to attach a file to an event like this: event.target.files[0]=newFile; The error I'm getting is "Failed to set an indexed property on 'FileList': Index property setter is not supported." Is there an alternative solution fo ...

What sets apart the symbols '!: ' and '?: ' in TypeScript object declarations?

Class Employee { firstName: string; lastName!: string; middleName?: string; } Can you explain the significance of the different field declarations within the Employee class? Check out a Live Example ...

Getter and setter methods in Angular Typescript are returning undefined values

I am facing a challenge in my Angular project where I need a property within a class to return specific fields in an object. Although I have implemented this successfully in .Net before, I am encountering an issue with getting an "Undefined" value returned ...

An issue occurred with npm resulting in exit code 2. The error is as follows: Command was unsuccessful: node_modules/.bin/vsce package --no

Here is the specific error displayed in cmd: TS1323: Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'. E ...

Can you explain the distinction between `any[]` and `{ [s: string]: any }`?

I was attempting to make this code snippet function properly: test(a: any[]) { let b: string[][] = []; b.push(Object.keys(a[0])); b.push(...a.map(e => Object.values(e))); } However, the compiler is throwing an error for the b.push(...a.ma ...

Saving the link to the search results for future reference

Procedure: onSearch(searchString) { if (this.props.history) { this.props.history.push( "/details?search=" + encodeURIComponent(searchString) ); } } Explore Bar: <Search onKeyPress={(event) => ...

What's the best way to invoke this specific TypeScript function?

I have come across a library that includes the following function declaration: import { Auth0JwtStrategy } from './strategy/auth0-jwt.strategy'; import { Auth0Service } from './auth0.service'; import { Auth0Options } from './auth0. ...

Using Flickity API in Vue 3 with Typescript Integration

I have encountered an issue with implementing Flickity in my Vue 3 application. Everything works perfectly fine when using a static HTML carousel with fixed cells. However, I am facing difficulties when attempting to dynamically add cells during runtime us ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

Sort through nested objects

Trying to filter an array of movies by genre using a function but encountering a TypeError: TypeError: movie.genres.some is not a function. (in 'movie.genres.some(function(item){return item.name === genre;})', 'movie.genres.some' is und ...

Create a new WebSocket package for Node.js that allows for segregating connections into

I am currently exploring ways to implement a feature similar to "rooms" using the npm 'ws' package, inspired by how rooms function in socket.io. I want to avoid using socket.io, but I am faced with the challenge of retrieving user/room informatio ...

Guide on how to utilize jest for mocking MongoDB manager in typescript

Is there a way to return a mongodb.connection.db() type value and mock its collection for testing purposes? I have implemented a mongoClient connection and use its db() function. If everything is set up correctly, I should be able to access the collections ...

guide on transferring csv information to mongoDB using Angular and Node.js

I have a CSV file that contains data which I need to transfer into MongoDB using Angular and Node.js. Seeking assistance with reading the data from the CSV file using Angular, parsing it, and storing it in MongoDB. import { Injectable } from '@ang ...