Created
March 28, 2019 14:57
-
-
Save devangbhavsar89/ff0de2b0ff6df82150a358c691671078 to your computer and use it in GitHub Desktop.
Extending RssReaderWebPart SPFx web part to use 'rss-parser' module to render RSS feeds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Step-1: Add 'rss-parser' module as a dependency to package.json and import it inside RssReaderWebPart.ts file | |
import Parser from 'rss-parser'; | |
export default class RssReaderWebPart extends BaseClientSideWebPart<IRssReaderWebPartProps> { | |
// Step-2: Add a new private loadRSSFeedAsync() method inside RssReaderWebPart class of RssReaderWebPart.ts file | |
private loadRSSFeedAsync(): void { | |
(async (properties, domElement) => { | |
const parser = new Parser(); | |
// Note: some RSS feeds can't be loaded in the browser due to CORS security. | |
// To get around this, you can use a proxy. | |
const CORS_PROXY = "https://cors-anywhere.herokuapp.com" | |
parser.parseURL(`${CORS_PROXY}/${properties.feedUrl}`, (err, feed) => { | |
if (!!err) { | |
// Log error message to console | |
console.error(`[RssReaderWebPart.loadRSSFeedAsync()] => ${err}`); | |
} | |
else { | |
if (!!feed) { | |
// Build RSS feed markup by iterating RSS feed items | |
let rssContent = ``; | |
rssContent += `<ul>`; | |
let maxCount = properties.maxCount < feed.items.length ? properties.maxCount : feed.items.length; | |
for (let i = 0; i < maxCount; i++) { | |
const item = feed.items[i]; | |
rssContent += `<li>`; | |
rssContent += `<a href="${item.link}">${item.title}</a>`; | |
// TODO: Code for rendering description, publishing date... | |
rssContent += `</li>`; | |
} | |
rssContent += `</ul>`; | |
// Insert content of RSS feed markup into DOM | |
domElement.innerHTML = rssContent; | |
} | |
else { | |
console.warn('Feeds are not available!'); | |
} | |
} | |
}); | |
})(this.properties, this.domElement); | |
} | |
// Step-3: Invoke newly created loadRSSFeedAsync() method from render() of RssReaderWebPart class inside RssReaderWebPart.ts file | |
public render(): void { | |
// Fetch RSS feeds and insert its content into DOM | |
this.loadRSSFeedAsync(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment