Build a News Aggregator Using Next.js
Last Updated :
29 Jul, 2024
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
Build a News Aggregator Using Next.jsPrerequisites
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
Folder StructureDependencies
"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
Build a News Aggregator Using Next.js
Similar Reads
Build a News Portal Using Next.js In this article, we will explore how to build a news portal using Next.js, a popular React framework for server-side rendering and static site generation. The news portal will allow users to publish and categorize news articles, providing a seamless user experience with fast page loads and dynamic c
8 min read
Build a Movie APP Using Next.js We will create a movie database app using Next.js and an external movie API (such as The Movie Database API). The app will enable users to view movies, search for specific movies, and view detailed information about each movie, including the title, release date, rating, brief description, and a list
7 min read
Build a Task Management App using Next JS A Task management app is a useful web application that assists in efficiently organizing and managing tasks. It provides various functionalities such as creating tasks, assigning prioritieÂs and deadlines, marking complete tasks, and enabling task search based on keÂywords and priorities.Preview of
5 min read
Build a Recipe Manager Using Next.js A Recipe Manager is a web application that allows users to manage and share their recipes. This application enables users to add new recipes, view a list of recipes, manage recipe and search for recipes by title. Built with Next.js, this app leverages server-side rendering for better performance. Us
10 min read
Build a Job Board with Next.js In this article, we will guide you through creating a dynamic job board application using Next.js. A job board application helps job seekers browse, filter, and apply for job openings while enabling employers to post job listings.Project PreviewBuild a Job Board with Next.jsPrerequisites:ReactJSNext
7 min read