Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First time using react. How to get rss items into a component?

This is the first time I am using react. I am coming from jQuery to React this feels like a big jump. If anybody can help me refactor this to work the React way I will be forever in your debt! :)

I am trying to parse an RSS feed, where I want to grab the most recent post title and link to render into a component.

https://www.npmjs.com/package/rss-parser - Using this to get the parser.

When viewing my app in the browser the async function is spitting out the rss feed into the console, which is a good start I guess!

    // src/App/index.tsx
    import * as React from 'react';
    import * as Parser from 'rss-parser';
    // Types
    import { string } from 'prop-types';

    let parser = new Parser();

    // blueprint for the properties
    interface Props {
      name: string;
    }

    // Component state
    interface State {
        //feed: any[];
    }


    (async () => {

      let feed = await parser.parseURL('https://www.reddit.com/.rss');
      console.log(feed.title);

      feed.items.forEach((item: { title: string; link: string; }) => {
        console.log(item.title + ':' + item.link)
      });

    })();


    export default class App extends React.Component<Props, State> {
      render() {
        return (
          <div>
            <h1>RSS Feed</h1>
            <div>
              <h1>item.title</h1>
              <a href="">item.link</a>
            </div>
          </div>
        );
      }
    }
like image 649
BennKingy Avatar asked Sep 06 '25 03:09

BennKingy


1 Answers

If I understand you right, you need something like this:

export default class App extends React.Component<Props, State> {
    constructor(props: {}) {
         super(props);
         this.state = { feed: [] };
    }

    async componentDidMount() {
        const feed = await parser.parseURL('https://www.reddit.com/.rss');
        this.setState({ feed });
    }

    render() {
        return (
        <div>
            <h1>RSS Feed</h1>
            this.state.feed.map((item, i) => (
                <div key={i}>
                    <h1>item.title</h1>
                    <a href="">item.link</a>
                </div>
            ))
        </div>
        );
    }
}
like image 115
Julia Shestakova Avatar answered Sep 07 '25 23:09

Julia Shestakova