Next.js for Beginners (Part 3): Pages and Components with Tailwind CSS

·

·

Introduction

In this part of our Next.js beginner series, we’ll dive into creating pages and reusable components, and then integrate Tailwind CSS to style them efficiently. Mastering these fundamentals will enable you to build scalable, well-structured applications.

Understanding Pages in Next.js

In Next.js, every file inside the `pages` directory becomes a route automatically. For example, `pages/about.js` will be accessible at `/about`. This file-based routing makes it easy to build pages.

Creating Your First Page

1. Go to the `pages` folder.
2. Create a new file named `about.js`.
3. Add the following code:

javascript

export default function About() {
  return <h1>About Page</h1>;
}

Creating Reusable Components

Components allow you to reuse UI elements across different pages. Place them in a `components` folder.

Example:
`components/Header.js`

javascript

export default function Header() {
  return <header><h1>My Website</h1></header>;
}

Using Tailwind CSS in Next.js

entity[“software”,”Tailwind CSS”,1] is a utility-first CSS framework that makes styling fast and consistent.

To install Tailwind CSS:

bash
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Then configure `tailwind.config.js` content section to include all your files:

javascript

content: [
  "./pages/**/*.{js,ts,jsx,tsx}",
  "./components/**/*.{js,ts,jsx,tsx}"
]

Finally, import Tailwind styles in `styles/globals.css`:
css

@tailwind base;
@tailwind components;
@tailwind utilities;

Styling Components with Tailwind

You can now add Tailwind classes directly in your JSX:

javascript

export default function Header() {
  return <header className="bg-blue-500 text-white p-4 text-center">My Website</header>;
}