// pages/about.js (1)
export default function About() {
return <div>About Page</div>
}
// pages/about/index.js (2)
export default function About() {
return <div>About Page</div>
}
// pages/index.js (3)
export default function Index() {
return <div>Index Page</div>
}
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link href="/">Home</Link>
</li>
<li>
<Link href="/about">About Us</Link>
</li>
<li>
<Link href="/blog/hello-world">Blog Post</Link>
</li>
</ul>
)
}
export default Home
import { useRouter } from 'next/router'
function Home() {
return (
<ul>
<li onClick={() => {router.push("/")}}>Home</li>
<li onClick={() => {router.push("/about")}}>About Us</li>
<li onClick={() => {router.push("/blog/hello-world")}}>Blog Post</li>
</ul>
)
}
export default Home
// pages/post/[id]
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { id } = router.query
return <p>Post: {id}</p>
}
export default Post
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}
// pages/api/test/[id].js
export default function handler(req, res) {
const { query } = req;
const { id } = query;
res.status(200).json({ name: "test", id });
}
Rendering
Pre-rendering
Server-Side Rendering(SSR), Static-Site generation(SSG)
// pages/ssr/[id].js
import { useRouter } from "next/router";
const Post = ({ post }) => {
const router = useRouter();
const { id } = router.query;
return (
<div>
Post: {id}
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
);
};
export default Post;
export async function getServerSideProps(context) {
const { params } = context;
const { id } = params;
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
const post = await response.json();
return {
props: {
post,
},
};
}
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
// pages/posts/[id].js
export async function getStaticPaths() {
return {
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
fallback: false, // false, true, "blocking"
}
}
export async function getStaticProps(context) {
return {
props: { post: {} },
}
}
export default function Post({ post }) {
// ...
}