In this tutorial, we’ll go over how to create dynamic pages in Next.js using React and REST API integration. This approach allows us to fetch data dynamically and render it on the page.
- Creating the REST API Endpoint in WordPress
First, we use WordPress to expose a REST API that provides our content. In this case, we are fetching portfolio items via the API endpoint:
https://creative-moon.com/wp-json/wp/v2/portfolio?per_page=100
This endpoint returns a list of portfolio items, which we can then use in Next.js to render pages dynamically.
- Fetching Data in Next.js with getStaticPaths and getStaticProps
Next, we use getStaticPaths and getStaticProps in Next.js to generate dynamic pages based on the fetched data.
// src/pages/works/[slug].tsx
import { GetStaticProps, GetStaticPaths } from 'next';
export const getStaticPaths: GetStaticPaths = async () => {
const res = await fetch('https://creative-moon.com/wp-json/wp/v2/portfolio?per_page=100');
const posts = await res.json();
// Generating paths based on the slug
const paths = posts.map((post: any) => ({
params: { slug: post.slug },
}));
return {
paths,
fallback: 'blocking', // The page will wait to be generated before serving
};
};
export const getStaticProps: GetStaticProps = async ({ params }) => {
const res = await fetch(`https://creative-moon.com/wp-json/wp/v2/portfolio?slug=${params?.slug}`);
const postData = await res.json();
if (!postData || postData.length === 0) {
return { notFound: true }; // Return 404 if no data is found
}
const post = postData[0];
return {
props: { post },
revalidate: 60, // Revalidate the page every 60 seconds
};
};
const WorkDetail = ({ post }: { post: any }) => {
if (!post) return <div>Loading...</div>; // Show loading if the data is still fetching
return (
<div>
<h1>{post.title.rendered}</h1>
<div>{post.content.rendered}</div> {/* Render the content fetched from the API */}
</div>
);
};
export default WorkDetail;
- Explanation of getStaticPaths and getStaticProps
- getStaticPaths: This function is responsible for generating dynamic routes. It fetches data from the REST API, extracts the slug for each post, and uses it to generate paths that Next.js will build statically.
- getStaticProps: This function fetches the data for a specific post based on the slug. It fetches content dynamically from the REST API and passes it as props to the page component.
- Rendering Dynamic Pages
With Next.js, dynamic pages are created based on the slug of each portfolio post. The title and content of each post are fetched from the API and displayed on the page.
// Inside the WorkDetail component
const WorkDetail = ({ post }: { post: any }) => {
if (!post) return <div>Loading...</div>;
return (
<div>
<h1>{post.title.rendered}</h1> // Dynamically render post title
<div>{post.content.rendered}</div> // Dynamically render post content
</div>
);
};
- Final Outcome
- When navigating to http://localhost:3000/works/{slug}, Next.js will fetch the data from the REST API and display the content dynamically on the page.
- This method allows Next.js to generate static pages based on dynamic data fetched from WordPress.
⸻
By using this method, you can easily fetch and render dynamic content from REST APIs in Next.js, making it ideal for headless CMS like WordPress. The combination of static generation and server-side rendering in Next.js powers this integration effectively.
I spent hours today troubleshooting a small issue with pages/works/[slug].tsx. It turned out to be a simple path problem, but after checking and fixing the file structure, everything started working as expected. It was frustrating but rewarding to finally resolve it!
Top comments (0)