Next.js Cheat Sheet

Here’s a Next.js cheat sheet covering key aspects of the Next.js framework for React:

Creating a Next.js App

Install Next.js:

npx create-next-app my-next-app

Navigate to the app directory:

cd my-next-app

Start the development server:

npm run dev

File System Routing

Pages are automatically mapped to routes based on the pages directory structure.

my-next-app
|-- pages
|   |-- index.js
|   |-- about.js
|   |-- contact
|       |-- index.js
  • / maps to pages/index.js
  • /about maps to pages/about.js
  • /contact maps to pages/contact/index.js

Linking Between Pages

import Link from 'next/link';

function MyComponent() {
  return (
    <div>
      <Link href="/about">
        <a>About Us</a>
      </Link>
    </div>
  );
}

Dynamic Routes

Create a file [id].js inside the pages directory.

// pages/post/[id].js
import { useRouter } from 'next/router';

function Post() {
  const router = useRouter();
  const { id } = router.query;

  return <p>Post ID: {id}</p>;
}

export default Post;

Access dynamic parameter using useRouter().

API Routes

Create an api directory. Files in this directory are treated as API routes.

my-next-app
|-- pages
|   |-- index.js
|-- api
|   |-- hello.js

Access the API route at http://localhost:3000/api/hello.

CSS Styling

Use styled-jsx for component-level styling.

const MyComponent = () => (
  <div>
    <style jsx>{`
      div {
        color: blue;
      }
    `}</style>
    Hello Next.js
  </div>
);

Layouts and Components

Create reusable layout components in the components directory.

// components/Layout.js
const Layout = ({ children }) => (
  <div>
    <header>Header</header>
    {children}
    <footer>Footer</footer>
  </div>
);

export default Layout;

Fetching Data

Use getStaticProps for static site generation or getServerSideProps for server-side rendering.

export async function getStaticProps() {
  const data = /* Fetch data from API or other source */;
  return {
    props: { data },
  };
}

function MyComponent({ data }) {
  return (
    <div>
      <p>{data}</p>
    </div>
  );
}

Deploying a Next.js App

Build the app:

npm run build

Deploy using platforms like Vercel, Netlify, or other hosting providers.

This cheat sheet provides an overview of essential concepts in Next.js. For more detailed information, refer to the official documentation: