Open In App

Build a News Aggregator Using Next.js

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we’ll walk through the step-by-step process of creating a news aggregator application using Next.js. It gathers news articles from multiple sources and presents them in a unified interface. This project will fetch news data using the News API and display it in a structured format.

Project Preview

np
Build a News Aggregator Using Next.js

Prerequisites

Approach to Build a News Aggregator Using Next.js

  • Initialize a Next.js project using create-next-app.
  • Install necessary dependencies such as Axios for API requests.
  • Create a utility function (fetchNews.js) to fetch news articles from the News API using Axios.
  • Create a React component (Home.js) for the main page of the news aggregator.
  • We will use React's useState and useEffect hooks to manage state for news articles, search query, and pagination.
  • Display fetched news articles in a structured format using Bootstrap for styling.
  • We will implement filter functionality to filter news articles based on category.

Steps to Build a News Aggregator Using Next.js

Step 1: Initialized the Nextjs app and installing the required packages

npx create-next-app@latest news-aggregator 

Step 2: It will ask you some questions, so choose as the following.

√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... No
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? (recommended) ... Yes
√ Would you like to customize the default import alias (@/*)? ... No

Step 3: Install the necessary package for your project using the following command.

npm i axios bootstrap

Step 4: Create account on NewsAPI and get your API key.

Project Structure

s
Folder Structure

Dependencies

"dependencies": {
"axios": "^1.7.2",
"bootstrap": "^5.3.3",
"next": "14.2.5",
"react": "^18",
"react-dom": "^18"
}

Example: Create the required files and write the following code.

JavaScript
// page.js

"use client";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState, useEffect } from "react";
import { fetchNews } from "./lib/fetchNews";

export default function Home() {
    const [articles, setArticles] = useState([]);
    const [category, setCategory] = useState("sports");
    const [page, setPage] = useState(1);

    const categories = [
        "business",
        "entertainment",
        "general",
        "health",
        "science",
        "sports",
        "technology",
    ];

    useEffect(() => {
        const getNews = async () => {
            const data = await fetchNews(category, page);
            setArticles(data.articles);
        };
        getNews();
    }, [category, page]);

    return (
        <div className="container mt-4">
            <h1 className="text-center mb-4 text-success">GFG News Aggregator</h1>
            <div className="mb-3">
                <select
                    className="form-select"
                    value={category}
                    onChange={(e) => setCategory(e.target.value)}
                >
                    {categories.map((cat) => (
                        <option key={cat} value={cat}>
                            {cat.charAt(0).toUpperCase() + cat.slice(1)}
                        </option>
                    ))}
                </select>
            </div>
            <div className="row">
                {articles.map((article, index) => (
                    <div key={index} className="col-md-4 mb-4">
                        <div className="card">
                            <img
                                src={article.urlToImage || "https://via.placeholder.com/150"}
                                className="card-img-top"
                                alt={article.title}
                            />
                            <div className="card-body">
                                <h5 className="card-title">{article.title}</h5>
                                <p className="card-text">{article.description}</p>
                                <a
                                    href={article.url}
                                    className="btn btn-primary"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                >
                                    Read more
                                </a>
                            </div>
                        </div>
                    </div>
                ))}
            </div>
            <div className="d-flex justify-content-between mt-4">
                <button
                    className="btn btn-secondary"
                    onClick={() => setPage(page > 1 ? page - 1 : 1)}
                    disabled={page <= 1}
                >
                    Previous Page
                </button>
                <button className="btn btn-secondary" onClick={() => setPage(page + 1)}>
                    Next Page
                </button>
            </div>
        </div>
    );
}
JavaScript
// lib/fetchNews.js

import axios from "axios";

const apiKey = "YOUR_API_KEY";
const pageSize = 40;

export const fetchNews = async (category = "technology", page = 1) => {
    try {
        const url = `https://newsapi.org/v2/everything?q=$
        {category}&pageSize=${pageSize}&page=${page}&apiKey=${apiKey}`;
        const response = await axios.get(url);
        return response.data;
    } catch (error) {
        console.error("Error fetching news:", error);
        return { articles: [] };
    }
};

Start your application using the following command

npm run dev

Output

npg
Build a News Aggregator Using Next.js

Next Article

Similar Reads