Xem thêm

How to Build a News App with React

In this tutorial, we will explore how to build a news app with React using News APIs. With the ever-changing world and the abundance of news on different topics, it is essential to have a...

In this tutorial, we will explore how to build a news app with React using News APIs. With the ever-changing world and the abundance of news on different topics, it is essential to have a way to filter and access relevant and useful information. By leveraging APIs and writing software components, we can create apps and websites that provide personalized and up-to-date news content with minimal effort.

Why Use News APIs

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

  • If you're creating a news app or website, the News API can serve as the primary data source, eliminating the need for manual data collection.
  • For news aggregation apps or sites, combining data from multiple News APIs can offer a wide range of news articles and increase variety.
  • Even if your app or website is not news-centered, integrating articles from News APIs can add relevance and keep your users informed.

Now, let's delve into the steps involved in building a News app with React.

Step 1: Subscribe to the API

Before we can test the API endpoints, we need to subscribe to the News API. There is a free plan available with a monthly request limit of 1000. Though higher-tier plans offer more benefits, the basic plan is sufficient for our React News app.

To get started with the API:

  1. Head over to the Bing News Search API page.
  2. Select the "Pricing" tab, which will provide you with the available options.
  3. Choose the "Basic" plan and click "Select Plan".

You may need to provide payment information, but rest assured that no charges will be made for the basic plan. Additionally, if you decide to upgrade to a higher plan, you will have already completed this step.

Step 2: Find the Search API Endpoint

The API endpoint we need is the "News Search" endpoint. This endpoint allows us to pass a query string and retrieve a list of relevant articles. To access this endpoint, select it from the left sidebar.

Step 3: Fill out the Required Parameters

The only required parameter for the News Search endpoint is the query string. Let's fill it out by using "react.js" as a sample parameter. This will provide us with data that will help us understand the structure of the API's response.

Step 4: Test the API Endpoint

Click on "Test Endpoint", and you will see the response data similar to the one below:

How to build a News App with React

After inspecting the data in RapidAPI's "Results" tab, we can gather essential details such as:

  • The response contains a list of articles under the "value" key.
  • Each news item includes information such as name, description, category, and datePublished.
  • Some articles have an image key representing the article's thumbnail.
  • All articles have a provider key, and some may have their own thumbnail.

What is React?

React, also known as React.js, is a front-end JavaScript framework widely used by software professionals around the world. As websites and apps become more complex, the need for adaptable front-end code arises. React was created to simplify and expedite front-end development, especially for larger applications and websites.

In React, you describe the desired view based on the state and props of your React Component. In other words, you focus on what your JavaScript component should look like and do, without worrying about implementation details. React takes care of the rest.

How to Build a News App in React (React Tutorial)

Now, let's get into the practical part of building a simple React Component that utilizes News APIs to display search results for any given query.

Step 1: Set Up Our React App

Thanks to Create React App, setting up a React app has become easy and straightforward. Follow these steps:

  1. Open your favorite terminal.
  2. Ensure that you have NPM installed.
  3. Run npx create-react-app react-news-app -use-npm.
  4. Change directory with cd react-news-app.
  5. Start the React web server with npm start.
  6. Open the project in your preferred IDE, such as VS Code.

Step 2: Obtain the JavaScript Code Snippet

On the Bing News Search API page, locate the JavaScript code snippet required for React:

  1. Click on 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 this tutorial, I've improved the code snippet by converting it into an Async Function, accepting the query string as a parameter, encoding the URI-string, providing default values for optional parameters, and returning the list of news articles from the JSON response. This is now represented by the searchNews function in the code below (in Step 3).

Step 3: Add Our React Component's Code

Replace the contents of src/App.js in your React project 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 (
    
setQuery(e.target.value)} />
{!list ? null : list.length === 0 ?

No results

:
    {list.map((item, i) => ( ))}
}
); } 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 (
  • {item.image && }

    {item.name}

    {item.description}

    {formatDate(item.datePublished)} {item.provider[0].image?.thumbnail && } {item.provider[0].name} {item.category && {separateWords(item.category)}}
  • ); } export default App;

    Please remember to paste your RapidAPI key into the searchNews function. You can find your key in the original code snippet you copied earlier.

    In the code above:

    • We create an async function called searchNews, which makes the API call and retrieves the news articles in JSON format.
    • The App component handles the user interface, including a search field, a button that triggers the search, and a display of the search results using the Item component.
    • The Item component renders each news item in a visually pleasing and organized manner.
    • Helper functions formatDate and separateWords aid in formatting date and category text.

    Step 4: Add CSS Styling Code

    The app is operational at this point, but it lacks visual appeal. With a touch of CSS, we can give it a more professional look effortlessly. Simply 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: Test the App

    We have now built a professional and respectable React News app! Feel free to search for phrases like "Docker," "Kubernetes," "GitHub," or "Linux."

    How to build a News App with React

    Conclusion

    Using News APIs can greatly enhance news apps and sites by providing access to a wide range of relevant content. Even if your app is not news-centered, integrating news articles can keep your users informed in their respective fields of interest. With React, building news apps becomes even more efficient, allowing for seamless integration of News APIs.

    FAQ

    1