React API Tutorials

How to build a News App with React

How to use News API

Things are always changing in the world, and it can be very useful for all of us to be able to keep up with those changes. But there’s so much news out there, on so many different topics, that we need ways to filter all of it down to only what’s relevant and useful to us. Making apps and websites, using algorithms, and writing software components can be a great way to achieve this for many people, with only a little effort.

Using News and Media APIs can improve your app in several ways:

  • If you’re making a news app or website, you can use the News API as the primary source of your data, without all the manual legwork.
  • For news aggregation apps or sites, combining data fetched from multiple News APIs can give your news articles a good amount of variety.
  • When your app or website isn’t news-centered, articles from News APIs can add a touch of relevance and help keep your users up-to-date.

Tip: Not sure what an API is? Check out What is an API?

Trying out Bing News Search API

If you check out the News & Media category on RapidAPI, you’ll see a very interesting list of APIs that already do a lot of this legwork for us. There are aggregation APIs, search APIs, APIs produced by using AI, and many more.

One that sticks out as particularly interesting is an API from Microsoft Azure, called Bing News Search API, because it uses AI to ensure the most relevant possible search results.

Step 1: Subscribe to the API

Before we can test out the API endpoints, we need to subscribe to them. This API is Freemium, which means it has a basic free plan, which comes with a hard limit of 1000 requests / month.

For the amount of benefit this API gives, the costs of the higher tiers are well worth it. But for our purposes, we’re just going to stick to the Basic plan, which is plenty for our little React News app.

Tip: For more information about API requests, check out the article What is an API Request?

To start using this API:

  1. Head on over to the Bing News Search API page.
  2. Select the “Pricing” tab, which will look like the image above.
  3. Click “Select Plan” on the “Basic” option.

You may need to fill in payment information, but don’t worry, none of it will be used here, since there’s a hard limit on this plan. Since you won’t be able to go over the limit, your payment method will not be charged. Besides, if you decide to upgrade to a higher plan, you’ll have already done this step!

Note: For these steps to work, make sure you have a RapidAPI account! It’s free, and you instantly get access to many APIs.

Step 2: Find the Search API endpoint

The API endpoint we’re interested here is “News Search”. We give it a query string, and we get back a list of articles. Perfect for our needs! So select that particular endpoint on the left sidebar.

Tip: Not sure how API Endpoints fit into all this? Check out the article What is an API Endpoint?

Step 3: Fill out the required parameters

The only required parameter is the query string. Let’s fill it out right now with “react.js” as a sample parameter. This should give us back some data that will help us to understand the structure of this API’s response data.

Step 4: Test the API endpoint

Click “Test Endpoint”, and you’ll see something like this:

After inspecting this data in RapidAPI’s “Results” tab, we see a few interesting details:

  • There’s a list of results under the key value.
  • Each news item has a name, description, category, and datePublished.
  • Some of them have an image key for the article’s thumbnail.
  • All of them have a provider key, and some have their own thumbnail too.

Great, this will work perfectly to help us make the React Component.

What is React?

React, also called React.js, is a front-end JavaScript framework, used by increasingly more software professionals around the world. As websites and apps become more complex, the front-end code needs to adapt to that complexity. But older frameworks haven’t always kept up. That’s why React was created, to make writing front-end code simpler and quicker, especially for bigger apps and sites.

In React, you describe what your view should look like, given your React Component’s state and props. In other words, you describe what your JavaScript component should do and look like, without having to spend a ton of effort on describing how it should happen. React takes care of all the rest for you.

How to build a News app in React (React Tutorial)

In this blog post, we’re going to make a simple React Component that uses News APIs to show search results for any given query. At the end, this is what we’ll have:

Step 1: Setup our React app

Setting up a React app used to be more complicated, but thanks to Create React App, now it’s a breeze. Let’s use that utility to make our lives simpler:

  1. Open up your favorite terminal.
  2. Make sure you have NPM installed.
  3. Run npx create-react-app react-news-app --use-npm
  4. Go into the directory with cd react-news-app
  5. Start the React web server with npm start
  6. Open the project in your favorite IDE, for example VS Code.

Step 2: Find our JavaScript code snippet

On the Big News Search API page, grab the JavaScript code needed for React:

  1. Click the “Code Snippets” tab on the left.
  2. Select JavaScript in the language drop-down.
  3. Choose fetch from the JavaScript sub-menu.
  4. Click the “Copy Code” button on the left.

For now, just pay attention to the steps you would take. But for your convenience, I’ve improved on this code snippet with the following steps:

  1. Turned the code into an Async Function.
  2. Received the query string as a parameter of our new function.
  3. Encoded the URI-string so it can be passed into the URL.
  4. Filled in some optional parameters with useful default values.
  5. Returned the list of news articles from the response’s JSON.

This resulted in what has become the searchNews function in the code below (in Step 3).

Step 3: Add our React Component’s code

In the React project we created in Step 1, replace the contents of src/App.js with the following React code:

import React from 'react';
import './App.css';

async function searchNews(q) {
  q = encodeURIComponent(q);
  const response = await fetch(`https://bing-news-search1.p.rapidapi.com/news/search?freshness=Day&textFormat=Raw&safeSearch=Strict&q=${q}`, {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "bing-news-search1.p.rapidapi.com",
      "x-rapidapi-key": /* paste your RapidAPI key here */,
      "x-bingapis-sdk": "true"
    }
  });
  const body = await response.json();
  return body.value;
}

function App() {
  const [query, setQuery] = React.useState("docker");
  const [list, setList] = React.useState(null);

  const search = (e) => {
    e.preventDefault();
    searchNews(query).then(setList);
  };

  return (
    <div className="app">

      <form onSubmit={search}>
        <input
          autoFocus
          value={query}
          onChange={e => setQuery(e.target.value)}
        />
        <button>Search</button>
      </form>

      {!list
        ? null
        : list.length === 0
          ? <p><i>No results</i></p>
          : <ul>
            {list.map((item, i) => (
              <Item key={i} item={item} />
            ))}
          </ul>
      }
    </div>
  );
}

function Item({ item }) {
  const separateWords = s => s.replace(/[A-Z][a-z]+/g, '$& ').trim();
  const formatDate = s => new Date(s).toLocaleDateString(undefined, { dateStyle: 'long' });

  return (
    <li className="item">
      {item.image &&
        <img className="thumbnail"
          alt=""
          src={item.image?.thumbnail?.contentUrl}
        />
      }

      <h2 className="title">
        <a href={item.url}>{item.name}</a>
      </h2>

      <p className="description">
        {item.description}
      </p>

      <div className="meta">
        <span>{formatDate(item.datePublished)}</span>

        <span className="provider">
          {item.provider[0].image?.thumbnail &&
            <img className="provider-thumbnail"
              alt=""
              src={item.provider[0].image.thumbnail.contentUrl + '&w=16&h=16'}
            />
          }
          {item.provider[0].name}
        </span>

        {item.category &&
          <span>{separateWords(item.category)}</span>
        }
      </div>
    </li>
  );
}

export default App;

Note: You’ll need to paste your RapidAPI key into this code, within the searchNews function. You can find this in the original code snippet you copied earlier.

In this code, we did three simple things:

  1. Created a searchNews async function, which calls the News API and gets the news articles JSON back.
  2. Overrode the App component, with a search field and a button that calls searchNews, and displays each news item using Item.
  3. Added the Item component which shows each news item in a compact, organized, and aesthetic way.

In our App component:

  • We store the query in state using React Hooks, using a default value of "docker".
  • The list of results is similarly stored in the list variable.
  • We start out with a null list, to differentiate between “not yet searched” and “got empty results”.
  • Our React Form uses Controlled Component for the input field.

Our Item component may be longer, but it’s actually simpler:

  • We always show the item’s title, description, date, and provider.
  • If the article thumbnail, provider’s thumbnail, and category are present, we show them too.
  • We have two simple helper functions for formatting the date and category.
  • That’s it.

Step 4: Add our CSS styling code

Right now our app works. But it’s ugly. With just a little bit of modern CSS, we can make it look much more professional with almost no effort.

So paste the following code into your src/App.css file:

body {
  background: #f7f7f7;
}

* {
  margin: 0;
  padding: 0;
}

.app {
  width: 45em;
  display: grid;
  gap: 1em;
  margin: 3em;
}

form {
  display: grid;
  grid-template-columns: 1fr auto;
  gap: 1em;
}

button {
  background: #17f;
  color: #fff;
  font: inherit;
  border: none;
  border-radius: 3px;
  outline: none;
  padding: 0.5em 1.5em;
}

button:active {
  background-color: #05b;
}

input {
  border: 1px solid #999;
  border-radius: 3px;
  font: inherit;
  padding: 0.5em;
  outline: none;
}

input:focus {
  outline: auto #17f;
}

.item {
  padding: 1em;
  list-style-type: none;
  border-radius: 6px;
  margin-bottom: 1em;
  background: #fff;
  box-shadow: 0px 2px 6px 2px #0002;
}

.item .title {
  font-size: 100%;
}

.item .description {
  margin: 1em 0;
}

.item .thumbnail {
  float: right;
  box-shadow: 0px 1px 1px 1px #0002;
  border-radius: 12px;
  margin-left: 1em;
  margin-bottom: 1em;
}

.item .meta {
  font-size: 80%;
  font-weight: bold;
  color: #555;
}

.item .provider-thumbnail {
  margin-right: 0.5em;
}

.item .meta > *:not(:last-child) {
  margin-right: 2em;
}

Step 5: Try it out!

Now we have a professional, respectable little React News app!

Try searching for phrases like “Docker”, “Kubernetes”, “GitHub” or “Linux”.

Conclusion

Using News APIs is not hard, and can be a great data source for your news apps and sites. Or, if your app isn’t centered on news, adding a little news on the side can keep your users up-to-date in their particular field of interest. By using React, we can make our news apps even more quickly and easily, and add News APIs with almost no effort!

FAQ

How to use News APIs?

Things are always changing in the world, and it can be very useful for all of us to be able to keep up with those changes. But there’s so much news out there, on so many different topics, that we need ways to filter all of it down to only what’s relevant and useful to us. Making apps and websites, using algorithms, and writing software components can be a great way to achieve this for many people, with only a little effort. Using News and Media APIs can improve your app in several ways:

How to use the Bing News Search API?

1. Subscribe to the API. 2. Find the Search API endpoint. 3. Fill out the required parameters. 4. Test the API Endpoint.

How to build a News app in React?

1. Setup our React app. 2. Find our JavaScript code snippet. 3. Add our React Component's code. 4. Add our CSS styling code. 5. Try it out!

5/5 - (2 votes)

View Comments

Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

2 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

2 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

4 weeks ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago