BACK TO HOME

Chapter 2. Introduction to Next.js | Delightful React

Published on Sat Sep 26 2020

As we discussed earlier in our first chapter Introduction to React , React in plain Javascript is pretty verbose and we write code in a modern syntax called JSX and use Babel, a transpiler that coverts such futuristic and custom syntaxes into ones that current browsers understand. We also talked about Webpack, mainly used to bundle JS files for usage in a browser.

However, if you're building a huge app which has lots of components, a plain HTML/Javascript setup we used earlier isn't good enough. You would need to use ES6, import/export api, http server along with Webpack, Babel etc.

This is where Next.js comes in.

Why Next.js?

Next.js is a React framework developed by the team at Vercel and is one of the best frameworks I've ever seen. Very few open-source projects are maintained well but Next.js is an exception.

1*htbUdWgFQ3a94PMEvBr_hQ.png

With Next.js you just write your modules as components and pages; and it automatically generates necessary HTML and JS files after converting JSX into browser-compatible code. One of its coolest features, "zero-config" allows developers to just start writing components and see them working in the http server, which I think is very helpful for beginners.

Beginners can quickly get into React, start writing components and eventually figure out what's going on behind the scenes. (Figuring out behind-the-scenes stuff like how webpack, babel work will come in a future chapter.) It also has a lot of other cool features like built-in routing, css-in-js support, fast-refresh and many others which we shall continue to explore.

Let's install Next.js

First of all, let us initialize an app as a node project.

yarn init -y

Next, lets add React, React-dom and Next as dependencies:

yarn add react react-dom next

Finally let's head over to package.json and add a few scripts:

"scripts" : {
  "dev":  "next",
  "build": "next build",
  "deploy": "vercel deploy"
}

Pages

We have seen how to use React with a simple file system approach with index.html where we create a component and it can be added to our HTML within a container DOM node. However, Next.js thinks of a web-app in terms of routes and pages. So the way to work with Next is that we tell it what appears on which page and it internally handles adding elements to the DOM container. Let's take a look with an example.

Let's create the home page for our Next.js webapp. To do that, we need to:

  1. we need to create a file at pages/index.js
  2. create a React component
  3. export the React component as a default export. We already saw how to create React components. So let's create a simple component for our Home page.
function Home() {
  return <p>Hello World</p>
}

export default Home;

Here, we are returning a paragraph element from the Home component, which will be rendered onto the screen.

Composition

Composition is simply a way for you to put in multiple elements, components together, one inside another, any levels deep and create a huge tree. For example:

function MyParagraph(){
  return <p>Hello World</p>
}
function Home() {
  return(
    <div>
      <MyParagraph></MyParagraph>
    </div>
  )
}
export default Home;

Here we have two components MyParagraph and Home. The way to render a component within another component is to just enclose the name of the component in opening and closing tags. So here, I'm enclosing "MyParagrah" within opening and closing tags and nesting it inside the Home component. Now, MyParagraph will be rendered within the Home component.

Let's render a few more paragraphs:

function MyParagraph(){
  return <p>Hello World</p>
}
function MyParagraph2(){
  return <p>Hello World2</p>
}
function MyParagraph3(){
  return <p>Hello World2</p>
}
function Home() {
  return (
    <div>
      <MyParagraph></MyParagraph>
      <MyParagraph2></MyParagraph2>
      <MyParagraph3></MyParagraph3>
    </div>
  )

}

Note that: 1. React expects you to return only one element/ component so you can't do something like this

return (
    <MyParagraph></MyParagraph>
    <MyParagraph2></MyParagraph2>
    <MyParagraph3></MyParagraph3>
)

So we always need to have a single root element/component returned in a component. So either we can wrap the paragraphs in another React element like <div>...</div> or we can wrap in a special convenience tag like so <>...</>.

return (
    <>
      <MyParagraph></MyParagraph>
      <MyParagraph2></MyParagraph2>
      <MyParagraph3></MyParagraph3>
    </>
)
  1. You probably guessed it: this code is quite repetitive. Except for the text inside, the three paragraph components we wrote are the same. We shall revisit this problem in the next post, where we would be talking about "props" in React.

Introduction to Routing in Next.js

Generally if you're working with react, routing is not so easy. You'll probably have to use a tool like react-router and configure you're routing components. But, it's much more easier with Next. You simply have to create a file inside the pages directory with that name. For example, if I want a page on /about route, I will simply have to create a file called about.js in the pages directory.

In this file, I will now create a component called About, return the jsx I want to render and export that component. Next js will take care of the rest!

function About() {
  return (
    <div>
      <h1>About me</h1>
      <h3>things I do in the React community</h3>
      <ul>
        <li>
          created a custom-hooks nam package called rooks to help make React development easier
        </li>
        <li>
          contributed to styled-components
        </li>
        <li>
          speak at various react events like: Fullstack Javascript Earth, React JS Bangalore, JS Lovers Mumbai Chapter etc.
        </li>
        <li>
          train teams in React, Javascript and Node
        </li>
        <li>
          teach students on Codementor
        </li>
        <li>
          make videos on Youtube
        </li>
        <li>
         writing a book on React
       </li>

      </ul>
    </div>
  )
}
export default About

If I now head over to http://localhost:3000/about, I will see the ui rendered on to the screen.

Here is a sandbox containing the code we worked on so far. Feel free to edit it for yourself.

Edit Intro to Next.js | Delightful React

You can also check out the site we built with Next.js here where you can go to the /about route and see the about page contents rendered. Or just simply click here.

There are a lot of other things we can do with Next.js routing like accessing route parameters, dynamic routes etc. which we are going to discuss in later posts.

That's it for today! I hope this was useful. Next up, we are going to discuss about two core features of react: props and state. Stay tuned!

====

So for each page in our app (for eg: home, about, blog list, single blog page etc) we describe what component is rendered in that page. Something like, "Hey Next.js! Render the component exported in index.js for / route, and render the component exported by about.js in about route etc".

To do that, create a folder called pages and create a file called index.js within it. This will be our homepage. Whatever we put in there will be rendered on the screen.

Sign up to my newsletter

Get latest news and tips in Fullstack web development right into your inbox!

No spam. I promise!

© 2020 Bhargav Ponnapalli. All rights reserved.