Pre-rendering Dynamic Routes with getStaticProps
Pre-render dynamic routes using getStaticProps and demonstrate how to use getStaticPaths to define a list of paths to be statically generated.
export async function getStaticPaths() {
// Fetch the list of item ids
const items = await fetchListOfItems();
// Generate the paths we want to pre-render based on items
const paths = items.map(item => ({
params: { id: item.id.toString() },
}));
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false };
}
Defines a list of paths that have to be rendered to HTML at build time. getStaticPaths is used in dynamic pages to specify which paths will be pre-rendered.
export async function getStaticProps({ params }) {
// Fetch necessary data for the page using params.id
const itemData = await fetchItemData(params.id);
// The returned 'props' will be passed to the page component
return { props: { itemData } };
}
Fetches the necessary data for each page based on the dynamic route and passes the data to the page under 'props'. This function runs at build time.
function Item({ itemData }) {
// Render item data
return (
<div>
<h1>{itemData.title}</h1>
<p>{itemData.description}</p>
</div>
);
}
export default Item;
The page component that receives the static props and renders the page's content based on the pre-fetched data.