// pages/index.js
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Welcome to our news site!</h1>
<ul>
<li>
<Link href="/news/1">
<a>News Article 1</a>
</Link>
</li>
<li>
<Link href="/news/2">
<a>News Article 2</a>
</Link>
</li>
<li>
<Link href="/news/3">
<a>News Article 3</a>
</Link>
</li>
</ul>
</div>
)
}
This code represents the homepage of a news site. Each news article is represented as a link to another page on the site. Next.js will automatically prefetch the JavaScript code for these pages due to the next/link
component.
// pages/news/[id].js
export async function getServerSideProps(context) {
const { id } = context.params
const response = await fetch(`https://api.example.com/news/${id}`)
const data = await response.json()
return {
props: { data }, // will be passed to the page component as props
}
}
export default function NewsArticle({ data }) {
return (
<div>
<h1>{data.title}</h1>
<p>{data.content}</p>
</div>
)
}
This code represents a dynamic page for a news article. The getServerSideProps
function fetches the data for the article from an API on the server-side. When navigating to this page, Next.js will fetch the data for the page when you navigate to it, even if the JavaScript code for the page was prefetched. The fetched data is passed as props to the page component and used to render the article's title and content.