22
loading...
This website collects cookies to deliver better user experience
npm run dev
//OR
yarn dev
localhost:3000
:export const news = [
{
id: "1",
tag: "breaking",
title:
"Facebook running special center to respond to content on Israeli-Gaza conflict - Reuters",
excerpt:
"Facebook Inc (FB.O) set up a 24-7 special operations center last week to respond to content posted on its platform about the ...",
content:
"Streaks of lights are seen from Ashkelon as rockets are launched from the Gaza Strip towards Israel, May 15, 2021. REUTERS/Amir Cohen/File PhotoFacebook Inc (FB.O) set up a 24-7 special operations. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
},
// some more data
]
pages
directory, create a new index.js
file in the pages/news/
directory. In this file, we'll fetch our news data and display the headlines so users can click through to read any news article of their choosing.// pages/news/index.js
import Footer from "@components/Footer";
import styles from "../news/News.module.css";
import Link from "next/link";
export default function NewsHome({ news }) {
return (
<div className="container">
<main>
<h1>All News Headlines</h1>
{news.map((article, index) => (
<div key={index} className={styles.card}>
<div className={styles.container}>
<Link href={`/news/${article.id}`}>
<a>
<h4>
<b>{article.title}</b>
</h4>
</a>
</Link>
<p>{article.excerpt}</p>
</div>
</div>
))}
</main>
<Footer />
</div>
);
}
export async function getStaticProps() {
const res = await fetch(process.env.DATA)
const news = await res.json();
return {
props: {
news,
},
};
}
getStaticProps()
function runs at build time to fetch our news data and pass it to NewsHome()
via props for rendering. Also, you may have noticed that I'm using Next.js's Link
component to route to /news/${article.id}
when any of the news items is clicked. In accordance with Next.js's pattern of handling dynamic routes, let's create a new [id].js
file in the same directory as our index file.// pages/news/[id].js
import Footer from "@components/Footer";
export default function NewsDetail({ news }) {
return (
<div>
<main>
<h3>{news.title}</h3>
<p> {news.content} </p>
</main>
<Footer />
</div>
);
}
export async function getStaticPaths() {
const res = await fetch(process.env.DATA);
const newsItems = await res.json();
const breakingNews = newsItems.filter((news) => news.tag == "breaking");
const paths = breakingNews.map((news) => ({
params: { id: news.id.toString() },
}));
/*
console.log(paths)
[
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
]
The paths above will be generated at build time
*/
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
const res = await fetch(`${process.env.DATA}/${params.id}`);
const news = await res.json();
return { props: { news } };
}
getStaticPaths()
function is how we tell Next.js which routes to generate at build time. Here, we are specifically telling Next.js to generate only the breaking news routes by:breaking
tag (i.e our breaking news).paths
to the function's return statement along with the fallback value of false. This will cause the site to 404 when a page that hasn't been generated is requested.news/1
, news/2
, news/3
) we see the news content and read it. However, if we request for any other news item (e.g archived news - news/4 or /5
etc) then we get a 404 page.fallback
to 'blocking'
or true
in the getStaticPaths()
function like this:// pages/news/[id].js
import Footer from "@components/Footer";
export default function NewsDetail({ news }) {
return (
<div>
<main>
<h3>{news.title}</h3>
<p> {news.content} </p>
</main>
<Footer />
</div>
);
}
export async function getStaticPaths() {
const res = await fetch(process.env.DATA);
const newsItems = await res.json();
const breakingNews = newsItems.filter((news) => news.tag == "breaking");
const paths = breakingNews.map((news) => ({
params: { id: news.id.toString() },
}));
/*
console.log(paths)
[
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
]
The paths above will be generated at build time
*/
return { paths, fallback: "blocking" };
}
export async function getStaticProps({ params }) {
const res = await fetch(`${process.env.DATA}/${params.id}`);
const news = await res.json();
return { props: { news } };
}
fallback:"blocking"
or fallback:true
means that we are telling Next.js to use an On-demand builder function to generate any paths that are not already pre-generated and specified in the getStaticPaths()
function. If we test this again, we should be able to see archived news (e.g news/4
and above):