search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Why RSS Feeds Aren't Directly Usable in React
Step 1: Fetch and Parse the RSS Feed
Option A: Use a CORS Proxy (Quick & Simple)
Option B: Use a Serverless Function (Recommended)
Step 2: Display the Feed in Your Component
Bonus Tips
Summary
Home Backend Development XML/RSS Tutorial Consuming and Displaying an RSS Feed in a React Application

Consuming and Displaying an RSS Feed in a React Application

Sep 23, 2025 am 04:08 AM
react RSS feed

To add RSS feed to React applications, you need to resolve CORS limitations and parse XML data through a server-side proxy. The specific steps are as follows: 1. Use CORS proxy (development stage) or create server functions (production environment) to obtain RSS feed; 2. Use DOMParser to convert XML into JavaScript objects; 3. Request this interface in the React component to obtain parsed JSON data; 4. Render the data to display the title, link, date and description, and safely process the HTML content; 5. It is recommended to add load status, error handling, entry restrictions and server-side cache to optimize the experience. The ultimate implementation integrates external content without a third-party API.

Consuming and Displaying an RSS Feed in a React Application

Adding an RSS feed to a React application can be a great way to pull in external content—like blog posts, news updates, or podcasts—without relying on a traditional API. While RSS isn't JSON, you can still consume and display it effectively with a few extra steps. Here's how to do it in a practical, real-world way.

Consuming and Displaying an RSS Feed in a React Application

Why RSS Feeds Aren't Directly Usable in React

RSS feeds are XML, not JSON. Browsers and JavaScript don't parse XML as easily as JSON, and modern fetch() doesn't handle XML natively. Plus, many RSS feeds are hosted on domains that may not allow direct cross-origin requests (CORS), so you can't just fetch() them from the frontend directly.

So, you need two things:

Consuming and Displaying an RSS Feed in a React Application
  1. A way to convert XML to a usable JavaScript object.
  2. A way to bypass CORS—either via a proxy or a serverless function.

Step 1: Fetch and Parse the RSS Feed

Since you can't reliably fetch RSS from the client due to CORS, one common solution is to use a proxy service or a serverless function .

Option A: Use a CORS Proxy (Quick & Simple)

For development or low-traffic apps, use a public CORS proxy like //m.sbmmt.com/link/eb852fa9d9e60316fa715602baf5bc05 :

 const fetchRssFeed = async () => {
  const proxyUrl = '//m.sbmmt.com/link/eb852fa9d9e60316fa715602baf5bc05/get';
  const rssUrl = 'https://example.com/feed.xml';

  try {
    const response = await fetch(`${proxyUrl}?url=${encodeURIComponent(rssUrl)}`);
    const data = await response.json();
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(data.contents, 'text/xml');

    const items = Array.from(xmlDoc.querySelectorAll('item')).map(item => ({
      title: item.querySelector('title')?.textContent || '',
      link: item.querySelector('link')?.textContent || '',
      pubDate: item.querySelector('pubDate')?.textContent || '',
      description: item.querySelector('description')?.textContent || '',
    }));

    return items;
  } catch (error) {
    console.error('Error fetching RSS feed:', error);
    return [];
  }
};

⚠️ Note: Public proxies can be slow or unreliable. Don't use them in production.

Create a simple backend endpoint (eg, using Vercel, Netlify, or Express) that fetches the RSS feed server-side:

Example with Vercel API function ( /api/rss.js ):

 export default async function handler(req, res) {
  const rssUrl = 'https://example.com/feed.xml';

  try {
    const response = await fetch(rssUrl);
    const xmlText = await response.text();
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlText, 'text/xml');

    const items = Array.from(xmlDoc.querySelectorAll('item')).map(item => ({
      title: item.querySelector('title')?.textContent || '',
      link: item.querySelector('link')?.textContent || '',
      pubDate: item.querySelector('pubDate')?.textContent || '',
      description: item.querySelector('description')?.textContent || '',
    }));

    res.status(200).json(items);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch RSS feed' });
  }
}

Then in your React component:

 const [posts, setPosts] = useState([]);

useEffect(() => {
  const loadFeed = async () => {
    const res = await fetch('/api/rss');
    const data = await res.json();
    setPosts(data);
  };
  loadFeed();
}, []);

Step 2: Display the Feed in Your Component

Once you have the parsed data, rendering it is straightforward:

 function RssFeed() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadFeed = async () => {
      try {
        const res = await fetch('/api/rss');
        const data = await res.json();
        setPosts(data);
      } catch (error) {
        console.error('Failed to load feed');
      } finally {
        setLoading(false);
      }
    };
    loadFeed();
  }, []);

  if (loading) return <p>Loading feed...</p>;

  Return (
    <div className="rss-feed">
      <h2>Latest Posts</h2>
      <ul>
        {posts.map((item, index) => (
          <li key={index}>
            <h3>
              <a href={item.link} target="_blank" rel="noopener noreferrer">
                {item.title}
              </a>
            </h3>
            <p className="date">{new Date(item.pubDate).toLocaleDateString()}</p>
            <div
              className="description"
              dangerouslySetInnerHTML={{ __html: item.description }}
            />
          </li>
        ))}
      </ul>
    </div>
  );
}

Bonus Tips

  • Sanitize HTML in descriptions : RSS descriptions often contain HTML. Using dangerouslySetInnerHTML works, but consider using a sanitizer like DOMPurify if security is a concern.
  • Cache the feed : RSS doesn't change every second. Cache the result on the server side (eg, with Redis or in-memory cache) to reduce load and avoid rate limits.
  • Add error fallbacks : Show a friendly message if the feed fails to load.
  • Limit items : Don't render 100 posts. Use .slice(0, 5) to show just the latest few.

Summary

Consuming an RSS feed in React involves:

  1. Getting around CORS (proxy or serverless function).
  2. Parsing XML into JavaScript objects.
  3. Displaying the data in your component.

It's not as simple as calling a JSON API, but with a small backend helper, it's totally doable and useful for pulling in external content without third-party dependencies.

Basically, just move the fetch to the server, parse the XML, and treat the result like any other data source.

The above is the detailed content of Consuming and Displaying an RSS Feed in a React Application. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure Nginx for a React application? How to configure Nginx for a React application? Sep 18, 2025 am 01:56 AM

TodeployaReactapponNginx,servestaticfilesandconfigureroutingfallbacktoindex.html.First,buildtheappusingnpmrunbuild,thentransferthebuildfilestotheserverdirectory(e.g.,/var/www/my-react-app).Next,createanNginxserverblockpointingtothisdirectory,usingtry

How to run a React application in a Docker container? How to run a React application in a Docker container? Sep 16, 2025 am 02:41 AM

TorunaReactappinDocker,createaDockerfiletodefinethebuildandserveprocess,copysourcecode,installdependencies,buildtheapp,anduseaserverlikeserveorNginxtoservestaticfiles.

Consuming and Displaying an RSS Feed in a React Application Consuming and Displaying an RSS Feed in a React Application Sep 23, 2025 am 04:08 AM

To add RSSfeed to React applications, you need to resolve CORS restrictions and parse XML data through a server-side proxy. The specific steps are as follows: 1. Use CORS agent (development stage) or create server functions (production environment) to obtain RSSfeed; 2. Use DOMParser to convert XML into JavaScript objects; 3. Request this interface in the React component to obtain parsed JSON data; 4. Render the data to display the title, link, date and description, and safely process the HTML content; 5. It is recommended to add load status, error handling, entry restrictions and server-side cache to optimize the experience. The ultimate implementation integrates external content without a third-party API.

How to Create a Custom RSS Feed for a WordPress Site How to Create a Custom RSS Feed for a WordPress Site Sep 16, 2025 am 12:36 AM

Use the add_feed() function to register a custom feed in functions.php; 2. Create a feed-custom.php template file and customize query parameters such as classification, author or custom fields; 3. Refresh the permalink to refresh the rewrite rules; 4. Optionally use plug-ins to simplify the process; 5. Test the correctness of the feed through the browser and verification tools to ensure that the content, links and dates are correct and not affected by cache, and ultimately achieve full control of WordPress custom RSSfeed.

Programming variable naming rules and programming word abbreviation dictionary Programming variable naming rules and programming word abbreviation dictionary Sep 08, 2025 pm 03:48 PM

Variable naming is an indispensable skill during programming. In order to help programmers better naming variables, this article has compiled common naming rules and programming word abbreviation dictionaries for your reference! (✿◡‿◡)O(∩_∩)OH! Naming Rules: Currently, there are four nomenclature rules in the industry: Camel nomenclature, Hungarian nomenclature, Pascal nomenclature and underscore nomenclature. The first three are more popular nomenclatures. (1) Camel nomenclature. As its name refers to the name of a mix of upper and lower case letters to form variables and functions. For example, the following is the same function named using camel nomenclature and underscore method respectively: printEmployeePaychecks(); print_employeepa

React Server Components vs. Client Components: A Complete Guide React Server Components vs. Client Components: A Complete Guide Oct 12, 2025 am 02:40 AM

ServerComponents are rendered on the server, do not increase the size of the client, and are suitable for data acquisition and static content; ClientComponents run in the browser, supporting interaction and state management. 1. ServerComponents cannot use hooks such as useState and can directly access the database; 2. ClientComponents need to be declared with 'useclient' to handle events and side effects; 3. Client components can be embedded in server components, but not vice versa; 4. Prioritize using ServerComponents to reduce JS packaging volume and improve performance; 5. Use ClientComponents when interaction is required. Correct points

Building an RSS Feed Reader with JavaScript and the Fetch API Building an RSS Feed Reader with JavaScript and the Fetch API Sep 10, 2025 am 12:41 AM

You can use JavaScript and FetchAPI to build an RSS reader. First, you can obtain RSSXML text through the CORS proxy, then parse it into a DOM structure with DOMParser, then extract the title, link, publishing time and description in the item, and finally render it to the page. 1. Use the RSSURL after fetch to request proxy and get the response JSON data; 2. Extract XML strings from data.contents and parse them into XML documents with DOMParser; 3. Query all item nodes and extract the required fields to store them into an array; 4. Map the data into HTML strings and insert them into the page container; 5. Add loading status and error handling to improve

Creating a PubSubHubbub-enabled RSS feed for real-time updates Creating a PubSubHubbub-enabled RSS feed for real-time updates Oct 03, 2025 am 03:11 AM

To create an RSSfeed that supports PubSubHubbubbub, you must first make sure that the feed is formatted correctly and publicly accessible, and then add the hub to the channel part of the feed to find that the link points to public hubs such as https://pubsubhubbub.appspot.com; then, when there is a subscription request, the server must be able to handle the GET verification challenge initiated by the hub and complete ownership verification by returning the provided challenge value; then, every time new content is published, a POST request is sent to the hub to notify it to push updates; finally, use tools such as SuperfeedrConsole or PuSHValidator to test the entire process

Related articles