avatarSudeep Timalsina

Summarize

Getting Started With Next.js and Create Your First Application Using Next.js

Source: pkj.no

Next.js is the powerful react framework that solves different problems like Server Side Rendering, Pre-rendering, SEO, etc. But it always keeps you very close with awesome library — react to develop your application. Next.js is bundled with plenty of built-in classes for better Developer Experience like:

  • Page based routing system (with support to custom routing)
  • Pre-rendering, both static generation and server side rendering
  • Client-side routing with optimized prefetching
  • Built-in CSS and Sass support
  • Development Environment which supports hot module replacement

Next.js has been trusted by the very big companies in the world. If you are from the react background, then you will find almost everything similar to react while using Next.js. Today, in this article, we will be developing a very simple Next.js application with some design and layouts and we will fetch api using pre-rendering. Let’s build the app then!

1. Create Project Directory Let’s create a project directory and name it as hello_next. Open up the project directory on your favorite Code Editor and I would prefer vscode for it.

2. Initialize package.json Open up the terminal containing the project directory and run following command that will create package.json file, which includes our project dependencies and scripts. Including -y on the command will generate the package file with all the defaults.

npm init -y

3. Install React, React Dom and Next Now, we install React, React Dom and Next for our project with the following command.

npm install --save react react-dom next

3. Change Scripts of package.json Add these scripts to the scripts section of package.json. Then, we can run the code with the command npm run dev.

//package.json
"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },

4. Routing Next.js has file-system based router built on concept of pages. So, we need to create a folder named pages and whatever the name of the file would be, the same would be the name of route. You will know better about it when we make use of this concept. We will be creating two pages, one would be the home page and another would be about page. So, let’s create index.js file inside the pages directory with simple welcome text.

//pages/index.js
const Index = () => {
    return (
            <div>
                <h1>Welcome to Next Application</h1>
            </div>
    );
}
export default Index;

Now, create about.js file inside same pages directory with following code.

//pages/about.js
const About = () => {
    return(
            <div>
                <h1>
                    About NextJS
                </h1>
                <p>Application to Demonstrate NextJS Basics</p>
            </div>
    );
}
export default About;

If you haven’t run the project yet, then run with npm run dev command. you will see the home page because index.js will take ‘/’ route. For now add ‘/about’ to the url to navigate to about page. We will build a navigation sections with bootstrap later on.

Home Page
About Page

5. Components We can create the components in Next.js same as of react. So, let’s create Navbar component and the Layout component which includes layout of our simple demo application. First, let’s create the Navbar Component. So, we create folder named components to the root of the project. Inside components folder, create navbar.js file which includes navigation menu for the project and also include bootstrap CDN for better design. Also, we are going to implement styled jsx just to demonstrate how they are used in next.js. These styles would be available to only this component.

//components/navbar.js
import Link from 'next/link';
const Navbar = () => {
    return(
        <div>
            <ul>
                <li><Link href="/"><a>Home</a></Link></li>
                <li><Link href="/about"><a>About</a></Link></li>
            </ul>
<style jsx>{`
                ul {
                    background: #333;
                    color: #fff;
                    list-style: none;
                    display: flex;
                }
ul li {
                    font-size: 22px;
                    margin-right: 50px;
                }
ul li a {
                    color: #fff;
                    text-decoration: none;
                }
            `}</style>
        </div>
    );
}
export default Navbar;

You can see how router navigation is done with next/link in the above code. Now, we need to create a layout for the project. So, we will create layout.js file inside the components folder and we will use the navbar component in layouts.

//components/layout.js
import Head from 'next/head';
import Navbar from './navbar';
const Layout = (props) => {
    return(
        <div>
            <Head>
                <title>Hello Next.js</title>
                <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" />
            </Head>
            <Navbar />
            <div className="container">
                {props.children}
            </div>
        </div>
    );
}
export default Layout;

Now, lets modify our index.js and about.js to make use of the available layout. We are going to apply very important feature of Next.js, which is `getInitialProps`. getInitialProps enables server-side rendering in a page and allows us to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO. It is an async function that can be added to any page as a static method. Let’s take a look at how we are going to fetch data for sample music api and display them in our home page. Also, we are going to add isomorphic-unfetch to fetch the api.

npm install --save isomorphic-unfetch

After adding this let’s modify our index.js. The full and final code in this page is done below.

//pages/index.js
import Layout from '../components/layout';
import fetch from 'isomorphic-unfetch';
const Index = ({musicData}) => {
    console.log(musicData)
    return (
        <Layout>
            <div>
                <h1>Welcome to Next Application</h1>
                <h3>Songs List</h3>
                {musicData.map((item, i) => {
                   return (
                   <li key={i}>{item.title}</li>
                   )
               })}
            </div>
        </Layout>
    );
}
Index.getInitialProps = async function() {
    const response = await fetch(`https://www.what-song.com/api/recent-movies`);
    const result = await response.json();
    return { musicData: result.data }
}
export default Index;

Also, let’s modify our about.js. The full and final code in this page is done below.

//pages/about.js
import Layout from '../components/layout';
const About = () => {
    return(
        <Layout>
            <div>
                <h1>
                    About NextJS
                </h1>
                <p>Application to Demonstrate NextJS Basics</p>
            </div>
        </Layout>
    );
}
export default About;

Demo

Now, our very simple Next.js application is ready to run. You can find the data fetched through the sample api and the pages as shown below:

Home page with list of songs
About page

This is very simple application developed using Next.js. You can gain the basic knowledge about how to install and work with next.js through this article. For more advanced things related to next.js, I will push myself to come up with the next article very soon. If you have any comments and queries you can feel free to ask on the comments below. If you are stuck somewhere and have confusions about the things that I explained, please refer to my github repository.

Stay Tuned!

Github Repository: https://github.com/SudeepTimalsina/hello_next

Nextjs
React
Server Side Rendering
SEO
Prerender
Recommended from ReadMedium