React — Next.js
What is Next.js?
Next.js is a React framework for building server-rendered and static websites.
Creating a Next.js App
npx create-next-app@latest my-app
cd my-app
npm run dev
Project Structure
my-app/
├── pages/
│ ├── index.js
│ ├── about.js
│ └── api/
│ └── users.js
├── public/
├── styles/
├── package.json
└── next.config.js
Basic Page
// pages/index.js
function Home() {
return (
<div>
<h1>Welcome to Next.js!</h1>
<p>This is the home page.</p>
</div>
);
}
export default Home;
Link Component
import Link from 'next/link';
function Navbar() {
return (
<nav>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
</nav>
);
}
Next.js Examples
// Dynamic routes
// pages/posts/[id].js
function Post({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
export async function getServerSideProps({ params }) {
const post = await fetch(`https://api.example.com/posts/${params.id}`)
.then(res => res.json());
return { props: { post } };
}
// API routes
// pages/api/users.js
export default function handler(req, res) {
res.status(200).json({ name: 'John' });
}
// Static generation
// pages/blog/index.js
function Blog({ posts }) {
return (
<div>
<h1>Blog</h1>
{posts.map(post => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
}
export async function getStaticProps() {
const posts = await fetch('https://api.example.com/posts')
.then(res => res.json());
return {
props: { posts },
revalidate: 60, // Regenerate page every 60 seconds
};
}
Mini Practice
Write Next.js code that:
- Creates a basic page
- Adds navigation with Link
- Creates a dynamic route
- Implements API routes
Up Next
Congratulations! You've completed the React course.
Related Topics
Frequently Asked Questions about Next.js
What is Next.js in React?
Next.js is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Next.js?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Next.js.
Why is Next.js important in React?
Next.js is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.