{post.title}
{post.content}
Building pages and components in Next.js
Creating pages and components in Next.js
// pages/index.tsx
import Head from 'next/head'
function HomePage() {
return (
Welcome to Next.js
Welcome
This is a Next.js page.
)
}
export default HomePage
// components/Layout.tsx
function Layout({ children }) {
return (
{children}
)
}
export default Layout
Methods for fetching data in Next.js pages
// pages/posts/[id].tsx
function Post({ post }) {
return (
{post.title}
{post.content}
)
}
export async function getStaticProps({ params }) {
const post = await getPost(params.id)
return {
props: { post }
}
}
export async function getStaticPaths() {
const posts = await getPosts()
const paths = posts.map((post) => ({
params: { id: post.id }
}))
return { paths, fallback: false }
}
export default Post
// pages/profile.tsx
function Profile({ user }) {
return (
Welcome {user.name}
Role: {user.role}
)
}
export async function getServerSideProps(context) {
const session = await getSession(context)
const user = await fetchUser(session.userId)
return {
props: { user }
}
}
export default Profile
Performance optimizations for Next.js pages
import Image from 'next/image'
function ProductCard({ product }) {
return (
{product.name}
{product.description}
)
}
import dynamic from 'next/dynamic'
const DynamicChart = dynamic(() => import('../components/Chart'), {
loading: () => Loading chart...
,
ssr: false // Disable server-side rendering
})
function Dashboard() {
return (
Analytics Dashboard
)
}