Next. Js overall introduction

Next. Js is the React server rendering application framework for building SEO-friendly SPA applications.

  1. Support for two rendering methods, static generation and server-side rendering.
  2. A page-based routing system with zero routing configuration.
  3. Automatic code splitting, optimize page loading speed.
  4. Supports static export. You can export applications as static websites.
  5. Styled – JSX with the built-in CSS-in-JS library
  6. The solution is mature and can be used in a production environment and is used by many companies around the world.
  7. The application is easy to deploy, has its own deployment environment Vercel, and can be deployed in other environments.

Create the Next. Js project

  • create
npm init next-app mynext
Copy the code
  • run
npm run dev
Copy the code
  • access
localhost:3000
Copy the code

The following page appears to indicate that the project was successfully initialized.

A page-based routing system

Create the page

  • In next.js, pages are placed in the React component in the Pages folder.
  • Components need to be exported by default
  • There is no need to introduce React in component files
  • The page address corresponds to the file address

Create a list page

  1. Create a list.js file in the Pages folder
export default function List() {
    return (
        <div>
            <h1>Hello,Next!</h1>
        </div>)}Copy the code
  1. Access the following address under the route
http://localhost:3000/list
Copy the code

Page jump

Matters needing attention

  • The Link component uses JavaScript by default for page jumps, spa-style jumps.
  • If JavaScript is disabled in the browser, use the link jump
  • No attributes other than the href attribute should be added to the Link component; the remaining attributes are added to the A tag
  • The Link component automatically optimizes the application for best performance with prefetch capabilities.

Code to jump from the home page to the List page (default: go to the Pages folder to find the list)

import Link from 'next/link'
export default function Home() {
    return (
        <div >
            <Link href="/list"><a>List Page</a></Link>
        </div>)}Copy the code

Static access in Next. Js applications

The public folder in the application root is used to provide static resources and can be accessed by :(the/below represents the public folder)

The following code will access the css.png image in the public folder

<img src="/images/CSS.png" alt="" />
Copy the code

Modify metadata on the page

Modify metadata through the Head component. The main purpose of the Head component is to add HTML tags to the page Head.

  • Home.js
import Link from 'next/link'
import Head from 'next/head'
export default function Home() {
    return (
        <div >
            <Head>
                <title>My Next</title>
            </Head>
            <Link href="/list"><a>List Page</a></Link>
            <img src="/images/CSS.png" alt="" />
        </div>)}Copy the code
  • list.js
import Head from 'next/head'
export default function List() {
    return (
        <div>
            <Head>
                <title>List Page</title>
            </Head>
            <h1>Hello,Next!</h1>
        </div>)}Copy the code

The way to add styles

styled-jsx

Styled JSX is built into Next, which is a CSS-in-JS library that allows you to write CSS in the React component, which only acts inside the component.

  • Modify the link style that jumps to the list page
import Link from 'next/link'
import Head from 'next/head'
export default function Home() {
    return (
        <div >
            <Head>
                <title>My Next</title>
            </Head>
            <Link href="/list"><a className="demo" >List Page</a></Link>
            <style jsx>
                {`
                    .demo {
                        color: red;
                    }
                `}
            </style>
        </div>)}Copy the code

CSS styles

CSS module

By using the CSS module function, you can write the CSS styles of components in a separate CSS file. The CSS module conventions that the name of the style file must be the name of the component file. Module.css

# list.js
import Head from 'next/head'
import styles from './list.module.css';
export default function List() {
    return (
        <div>
            <Head>
                <title>List Page</title>
            </Head>
            <h1 className={styles.demo}>Hello,Next!</h1>
        </div>
    )
}

# list.module.css
.demo {
    color: blueviolet;
}
Copy the code

Add global styles

  1. Create a new _app.js file in the Pages folder and add the following code.
  2. Create a styles folder under the project root and create global.css in it
  3. Import global.css in _app.js with import
  4. Restart the development server

Note: The following fixed code needs to be added to _app.js

export default function App({ Component, pageProps }) {
    return <Component {. pageProps} / >
}
Copy the code

pre-rendered

What is pre-rendering?

  • Prerendering is the stitching of data and HTML on the server side ahead of time
  • Pre-rendering can make SEO much friendlier
  • Pre-rendering makes for a better user experience, allowing you to view your application’S UI without running JS

Two forms of pre-rendering

  • Two forms of pre-rendering are supported in next.js: static generation and server-side rendering.
  • Static generation and server-side rendering are different times to generate HTML trees.
  • Static generation: Static generation generates HTML at build time, and each subsequent request shares the HTML generated at build time.
  • Server-side rendering: Server-side rendering generates HTML on request, which is regenerated on each request.

Two options for pre-rendering

  • Next. Js allows developers to choose different pre-rendering methods for each page. Different pre-rendering methods have different characteristics and should be rendered according to the scene.
  • Most pages are recommended to be generated statically.
  • Generate a build statically, use it repeatedly, and access is fast because the pages are pre-generated. Application scenario: marketing pages, blog posts, e-commerce product listings, help, and documentation.
  • Server-side rendering access is not as fast as static generation, but because it is re-rendered on every request, it is suitable for pages where data is frequently updated or where page content changes with requests.

Implementing static generation

Static generation of no data and data.

  • If the component doesn’t need to fetch data from anywhere else, generate it statically.
  • If the component needs to fetch data elsewhere, at build time, next.js prefetches the data the component needs and then statically generates the component.

Static generation of no data

  1. Let’s delete the.next folder

  2. Run the build command

npm run build
Copy the code

There is static generation of data

The getStaticProps method is an asynchronous function that needs to be exported inside the component. In development mode, getStaticProps runs on each request instead.

import Head from 'next/head'
import styles from './list.module.css';
import { readFile } from 'fs';
import { promisify } from 'util';
import { join } from 'path'

const read = promisify(readFile);
export default function List({data}) {
    return (
        <div>
            <Head>
                <title>List Page</title>
            </Head>
            <h1 className={styles.demo}>Hello,Next!</h1>
            <h2>The console prints {data}</h2>
        </div>)}export async function getStaticProps () {
    let data = await read(join(process.cwd(),'pages'.'_app.js'),'utf-8');
    console.log(data)
    return {
        props: {
            data
        }
    }
}
Copy the code

NPM start vs. NPM run dev

  • Start starts the code in production
  • Dev launches the code in the development environment

Realize static generation based on dynamic routing

Generate HTML pages for page components based on parameters, and produce as many HTML pages as there are parameters. In application construction, obtain all routing parameters accessible to users, then obtain specific data according to routing parameters, and then generate static HTML according to the data.

  1. Create a page component file based on dynamic routing and name it with [], such as [id].js

  1. Export the asynchronous function getStaticPaths to get route parameters accessible to all users.

  2. Export the asynchronous function getStaticProps to obtain specific data based on route parameters.

Note: getStaticProps and getStaticPaths only run on the server side, never on the client side, and are not even packaged into client-side JavaScript, which means you can play around with server-side code like querying databases.

[id].js

export default function Post({data}) {
    return (
        <div>
            <span>{data.id}</span>
            <span>{data.title}</span>
        </div>)}// Returns all route parameters accessible to the user
export async function getStaticPaths() {
    return {
        paths: [{params: {id: '1'}}, {params: {id: '2'}}].fallback: false}}// Return the specific data corresponding to the route parameter
export async function getStaticProps({params}) {
    const id = params.id;
    let data;
    switch (id) {
        case '1':
            data = {id: "1".title: 'Hello'};
            break;
        case '2':
            data = {id: "2".title: 'World'};
            break;
        default:
            data = {};
    }
    return {
        props: {
            data
        }
    }
}
Copy the code

What the Fallback option does

If fallback is set to false, a 404 page will be returned if the requested parameter is not in the specified parameter range. If fallback is set to true, the requested data will be fetched and the corresponding static page will be generated.

Here is the code for [id].js when fallback is true

import { useRouter } from 'next/router'
export default function Post({data}) {
    const router = useRouter();
    if (router.isFallback) return <div style={{color: 'red'}} >Loading...</div>
    return (
        <div>
            <span>{data.id}</span>
            <span>{data.title}</span>
        </div>)}// Returns all route parameters accessible to the user
export async function getStaticPaths() {
    return {
        paths: [{params: {id: '1'}}, {params: {id: '2'}}].fallback: true}}// Return the specific data corresponding to the route parameter
export async function getStaticProps({params}) {
    const id = params.id;
    let data;
    switch (id) {
        case '1':
            data = {id: "1".title: 'Hello'};
            break;
        case '2':
            data = {id: "2".title: 'World'};
            break;
        case '3':
            data = {id: '3'.title: 'Hello World'};
            break;
        default:
            data = {};
    }
    return {
        props: {
            data
        }
    }
}
Copy the code

Customize 404 pages

To create a custom 404 page, create a 404.js file in the Pages folder.

export default function Custom404() {
    return (
        <h1>404 Not Found</h1>)}Copy the code

API Routers

API Routers can be defined as interfaces. Clients send requests to servers for data, and the Next. Js application allows React developers to write server-side code to create data interfaces.

Implement the API Routers

  1. Create an API Routes file in the Pages/API folder, such as user.js
  2. The request handler function is exported in the file by default. The function takes two parameters, req for the request object and res for the response object.
  3. Access API Routes: localhost:3000/ API /user

Note: Do not access API interfaces from the getStaticProps or getStaticPaths functions, as these functions run on the server side and can be directly written to the server side.

Here is/pages/API/user. Js

export default (req, res) => {
    res.send({ name: 'hello'})}Copy the code