Book Image

Next.js Quick Start Guide

By : Kirill Konshin
Book Image

Next.js Quick Start Guide

By: Kirill Konshin

Overview of this book

Next.js is a powerful addition to the ever-growing and dynamic JavaScript world. Built on top of React, Webpack, and Babel, it is a minimalistic framework for server-rendered universal JavaScript applications. This book will show you the best practices for building sites using Next. js, enabling you to build SEO-friendly and superfast websites. This book will guide you from building a simple single page app to a scalable and reliable client-server infrastructure. You will explore code sharing between client and server, universal modules, and server-side rendering. The book will take you through the core Next.js concepts that everyone is talking about – hot reloading, code splitting, routing, server rendering, transpilation, CSS isolation, and more. You will learn ways of implementing them in order to create your own universal JavaScript application. You will walk through the building and deployment stages of your applications with the JSON API,customizing the confguration, error handling,data fetching, deploying to production, and authentication.
Table of Contents (9 chapters)

Introduction to React

In this section, we will create a simple React-based project and will learn how this library works and what its core concepts are.

Let's create an empty project folder and initialize NPM:

$ mkdir learn-react
$ cd learn-react
$ npm init
$ npm install react react-dom --save

The quickest way to get started with React is to use the react-scripts package:

$ npm install react-scripts --save-dev

Now, let's add a start script to package.json:

{
"scripts": {
"start": "react-scripts start"
}
}

NPM auto-binds CLI scripts installed in the node_modules/.bin directory along with the packages, so we can use them in package.json scripts directly.

The smallest possible setup for a React app is the following: we need a landing HTML page and one script with the app.

Let's start with the bedrock HTML:

<!--public/index.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Learn React</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

And here is the main JS file:

//src/index.js:
import React from "react";
import {render} from "react-dom";
render(
<h1>It works!</h1>,
document.getElementById('app')
);

This is it. Now, we can run the command to start the development server:

$ npm start

It will open port 3000 on the localhost. Open the URL http://localhost:3000 in your browser; the index.js script will be run and the render function will render an HTML page with "It works!" in it.

To learn more about React JSX, I encourage you to take a look at the official documentation:
https://reactjs.org/docs/introducing-jsx.html. This chapter will only briefly cover the main aspects that are essential for Next.js apps.

The simplest React component is just a function that takes props as an argument and returns JSX:

const Cmp = ({children, ...props}) => (<div {...props}>{children}</div>);

JSX is HTML with the ability to insert and execute JS in it. In this example, we inject variables into a tag as properties and as content.

A more complicated component may have state:

class Cmp extends React.Component {
state = {value: 'init'};
onClick = (event) => { this.setState({value: 'clicked'}); };
render() {
return (
<button onClick={this.onClick}>{this.state.value}</button>
);
}
}

Components may have static properties:

class Cmp extends React.Component {
static foo = 'foo';
}

or

Cmp.foo = 'foo';

These static properties are often used to describe some meta-information about the components:

import PropTypes from "prop-types";
Cmp.propTypes = {
propName: PropTypes.string
};

Next.js utilizes static properties heavily and we will show you how later.

The simplest way to achieve code splitting in a React application is to store the entire progressively-loaded component in the state:

class Cmp extends React.Component {
state = {Sub: null};
onClick = async (event) => {
const Sub = (await import('./path/to/Sub.js')).default;
this.setState({Sub});
};
render() {
const {Sub} = this.state;
return (
<div>
<button onClick={this.onClick}>Load</button>
<Sub/>
</div>
);
}
}
Do not use this straightforward way with Next.js, as it will not work in Server-Side Rendering mode. In the next chapter, we will show you how to do it properly.

Another way to achieve code splitting is to use the React Router.

All React components have life cycle hooks that can be utilized, for example, to load the data from a remote server:

class Cmp extends React.Component {
state = {data: null};
async componentWillMount() {
const data = await (await fetch('https://example.com')).json();
this.setState({data});
}
render() {
const {data} = this.state;
return (
<pre>
{JSON.stringify(data)}
</pre>
);
}
}

The React API is of course much bigger than what was covered here, so please refer to the official documentation for more info. The things mentioned here are absolutely essential for Next.js, which is why we mentioned them.