Step 1: Define a Dynamic Route
Create a file that corresponds to the dynamic part of the path within the app
directory, such as app/posts/[id]/page.tsx
. The [id]
is the variable part of the route.
Step 2: Fetch Data for Dynamic Routes
Use getServerData
in your dynamic page to fetch data based on the route parameter.
// app/posts/[id]/page.tsx
import { getServerData } from 'next';
export async function getServerData(context) {
const { id } = context.params;
const post = await fetchPostData(id); // fetchPostData is a placeholder for your actual data fetching logic
return {
props: { post },
};
}
const Post = ({ post }) => {
// Render your post content
};
export default Post;
JavaScriptStep 3: Pass Data Between Components
If you have a list component that links to the dynamic route, you can pass data using Link
from next/link
and a state management solution like React Context, Redux, or simply prop drilling if the components are close in the tree.
// app/posts/page.tsx
import Link from 'next/link';
import { fetchPostsList } from '../../lib/posts'; // Your data fetching function
export async function getServerData() {
const posts = await fetchPostsList();
return {
props: { posts },
};
}
const PostsListPage = ({ posts }) => {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/posts/${post.id}`}>
<a>{post.title}</a>
</Link>
</li>
))}
</ul>
);
};
export default PostsListPage;
JavaScriptStep 4: Navigate with State
When navigating, you can pass state to the link destination:
<Link href={`/posts/${post.id}`} state={{ from: 'home' }}>
<a>{post.title}</a>
</Link>
JavaScriptStep 5: Access State in the Dynamic Page
Within the dynamic route component, you can access the passed state:
import { useRouter } from 'next/router';
const Post = () => {
const router = useRouter();
const { from } = router.state; // Access the passed state
// Render the component based on the state
};
export default Post;
JavaScript