SPFX React webpart connecting external API

My “world news webpart”. I don’t believe I did this. Learnt many things while developing this.

In this blog we will see how to connect to an external anonymous API from SPFX webpart. This webpart will display latest world news in it using office UI fabric controls (Document Card) and the no. of news count can be controlled through the webpart property pane

Step 1: Create SPFX React webpart

md Connectapi

cd Connectapi

Select “React” as framework while creating the webpart. Once the webpart is created open it with visual code

Step 2: Add fields to webpart property pane

We need to pass the external news API URL and the count of news from the webpart property pane, so let’s add a “Text” control and a “Slider” control into the property pane.

Open “ConnectapiWebPart.ts” file and add the below code into “getPropertyPaneCofiguration” method.

Declare them in props interface and set property control values to props so that we can pass the values entered in webpart property pane

Step 3: Connect to external news API

For this blog I have used “newsapi”, its free. You need to register and “Get API Key”. Don’t worry its quick and easy less than a minute.

Open “Connectapi.tsx” file and create a interface making all parts of one news panel

Create another interface to declare state elements

Initialize state using a constructor inside default class

Now add the actual code which will retrieve data from the news API using fetch operation

The above method will be called before render using “componentDidMount”. So, add the below code.

We need the same method to be called whenever we change the news count in the slider, so call it in “componentDidUpdate”

We are ready with the data retrieval part. Let’s move on to how to display them in the webpart.

Step 4: Add Office UI fabric Document Card

For more details refer Microsoft site here

Add below import statements in ‘Connectapi.tsx’

One last thing I also added the css into “Connectapi.module.scss” so that to fit 2 images in one row.

Ready to go. Hit Gulp serve. Add the webpart in the local workbench. Edit property to open webpart property pane and add the below news api URL in “News API URL” field in webpart property

“https://newsapi.org/v2/top-headlines?country=gb&apiKey=insertyourkeyhere”

Its great to see my world news webpart loading. Thanks for reading my blog. #sharingiscaring. Referred Walkdek blog which helped me a lot.