gauravbytes.com is now codefoundry.dev.
Showing posts with label Full-stack development. Show all posts

In the previous post, We created a BlogPost application rendering content on server-side with Next.js. We will be changing the same application to use SSG (Static Generation) capability of Next.js.

What will we create and which Next.js functions will we use?

We will create an application which will have index page to list all the available blog links and statically generated blog posts. We will use getStaticProps and getStaticPaths functions from Next.js.

getStaticProps function is called by Next.js at build time and pre-renders the page.

getStaticPaths function is also called by Next.js at build time. If you are using getStaticProps and there are dynamic paths then you define those in getStaticPaths

Update index.tsx

import React from 'react';
import { GetStaticProps, GetStaticPropsContext } from 'next';
import BloggerService from '../service/BloggerService';
import styles from '../App.module.css'

/* Line 1*/ interface IndexPageProps {
  blogLinks: Array<{ id: string, title: string }>
}


export default function IndexPage(props: IndexPageProps) {
  /* Line 2 */ return (
    <div className={ styles['blog-container'] }>
      <ul className={ styles['blog-posts'] }>
      {props.blogLinks.map(blogLink => <li key={blogLink.id}><a href={`/posts/${encodeURIComponent(blogLink.id)}`}>{blogLink.title}</a></li>)}
      </ul>
    </div>
  );
}

/* Line 3 */ export const getStaticProps: GetStaticProps = async (context: GetStaticPropsContext<any>) => {
  const bloggerPosts = await BloggerService.getAllPosts();
  const blogLinks = bloggerPosts.posts.map(post => {
    const splittedId = post.id.split('-')
      return {
        id: splittedId[splittedId.length - 1],
        title: post.title
      }
  });

  return {
    props: {
      blogLinks
    }
  }
}

At line 1, we defines the props type expected by IndexPage function. At Line 2, we are returning React.Element. We are iterating on the blogLinks passed as props to this component and returns a list. This property is passed from getStaticProps function at build time. At Line 3, we are defining getStaticProps function. We are calling BloggerService and retrieving blog feeds from https://codefoundry.dev. Then, we are extracting two properties id and title and are returning those from this method.

At the build time, Next.js will call this function on server-side and will pass these properties to IndexPage function and will generate static HTML on server. That static HTML will be served everytime.

Creating [slug].tsx to catch all the routes

Next step is to create [slug].tsx under pages/posts folder. This component will catch all the dymaically generated URL and will open the statically generated HTML if found otherwise endup showing 404 page.

import React from 'react';
import { GetStaticPaths, GetStaticProps, GetStaticPropsContext } from 'next';
import IBlogPost from '../../models/IBlogPost';
import BloggerService from '../../service/BloggerService';
import BlogPost from '../../components/BlogPost';
import styles from '../../App.module.css';

/* Line 1 */ interface IServerProps {
  post: IBlogPost
}

export default (props: IServerProps) => {
  /* Line 2 */ return (
    <>
      <div className={styles['App-Container']}>
        <BlogPost post={props.post} />
      </div>
    </>
  );
}

/* Line 3 */ export const getStaticPaths: GetStaticPaths = async() => {
  const bloggerPosts = await BloggerService.getAllPosts();
  const paths = bloggerPosts.posts.map(post => {
    const splittedId = post.id.split('-')
    const slug = splittedId[splittedId.length - 1]
    return {
      params: {
        slug
      }
    }
  });

  return {
    paths,
    fallback: false
  }
}

/* Line 4 */ export const getStaticProps: GetStaticProps = async(context: GetStaticPropsContext<any>) => {
  const slug = context?.params?.slug ?? 'na'
  const bloggerPosts = await BloggerService.getAllPosts();

  const post = bloggerPosts.posts.find( post => post.id.endsWith(slug))
  return {
    props: {
      post
    }
  }
} 

At Line 1, we are creating type for props this component takes. At Line 2, we are returning React.Element. We are passing post property from props to BlogPost component. This property is passed by getStaticProps function at build time.

At Line 3, we are defining getStaticPaths function. This function returns the list of dynamic paths this page will handle.

At Line 4, we are defining getStaticProps function. This function reads the slug property from context's params property. This proeprty is generated by getStaticPaths function(Line3) and then get the post from BloggerService and finally this post property is passed to this page (Line 2).

I have modified existing code for this example. Let's cleanup code which is not required.

First, remove unwanted libraries with npm remove @reduxjs/toolkit react-redux next-on-netlify command. Remove BlogSearch.tsx, BlogListing.tsx, BlogPosts.tsx and BlogPosts.module.css from src/components folder. Remove index.css and index.tsx from src folder. Update _app.tsx under src/pages and remove redux store and provider. That's it.

Let's run the application.

Click on any link and you will see statically generated blog page.

That's it :). You can download the full code from github.

Recap

In this post, we introduced getStaticPaths and getStaticProps methods of Next.js for Static site generation. We used both methods in [slug].tsx for dynamic path generation. At last, we removed unwanted files from last code example.

What's next?

In the next post, we will deploy Next.js project (Static Generation and SSR) on Netlify.

In the previous post, we created a BlogPost application with React and Redux and managed global state with Redux. We will extend the same application and will introduce Next.js for server-side rendering. The bigger benefit of using Next.js is pre-rendering of the page along with automatic code-splitting, static site export, CSS-in-JS.

Next.js functions

Next.js exposes three functions for data fetching and these are getStaticProps, getStaticPaths and getServerSideProps. First two functions are used for Static generation and the last function getServerSideProps is used for Server-side rendering. Static generation means the HTML is generated at the build(project build) time whereas in Server-side rendering HTML is generated at each request.

Adding required libraries

Run npm i --save next @types/next from root of the project to add the required libraries for this example.

Update following commands under scripts in package.json.

"dev": "next dev",
"start": "next start",
"build": "next build"

Next.js is built around the concept of pages. A page is nothing but a React component exported in pages directory. For example; pages/welcome.tsx will be mapped to /welcome. You also have an option to have Dynamic routes.

Basic setup

Let's start with creating _document.tsx and _app.tsx under src/pages directory. In _document.tsx, you defines your skeleton structure of your html page generated by Next.js. You usually do this to add meta tags or loading scripts or styles from CDN. Consider _app.tsx as the root component of your React application. In our example, we provide redux store to the Provider in this component.

// _document.tsx


import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
    <Html lang="en">
      <Head>
        <meta content='https://www.codefoundry.dev/' property='og:url'/>
        <meta content='Tutorials for Java, Java 8, Spring, Spring Cloud, Spring Boot, React JS, Redux, Next.JS' property='og:description'/>
        <meta content='Gaurav Rai Mazra' name='Author'/>
        <meta content='https://www.codefoundry.dev/' property='og:url'/>
        <meta content='https://www.codefoundry.dev/favicon.ico' property='og:image'/>
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
    )
  }
}
// _app.tsx


import React from 'react';
import { AppProps } from 'next/app';
import { Provider } from 'react-redux';
import { store } from '../redux/store';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <React.StrictMode>
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    </React.StrictMode>
  )
}

export default MyApp;

Creating first page

Let's create our first page index.tsx under src/pages directory.

/* Line 1 */
interface IServerProps {
  bloggerPosts: {
    allTags: string[]
    posts: IBlogPost[]
  }
}

export default (props: IServerProps) => {
  /* Line 2 */ const dispatch = useDispatch();
  useEffect(() => {
    /* Line 3 */ dispatch(setPostsAsync(props.bloggerPosts));
  }, [dispatch, props.bloggerPosts])
  return (<App />)
}

/* Line 4 */ export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext<any>) => {
  /* Line 5 */const bloggerPosts = await BloggerService.getAllPosts();
  return {
    props: {
      bloggerPosts
    }
  }
} 

At Line 1, we have defined type of prop field of this functional component. At line 2, We are using useDispatch hook from redux to get reference of dispatch function. Inside useEffect hook, at line 3, we are dispatching the bloggerPosts that were computed on server-side by Next.js(Line 4).

At Line 4, we are defining getServerSideProps function which gets executed on every request by Next.js on the server-side and the result is passed onto this functional component.

At Line 5, we are calling BloggerService's getAllPosts function which is retrieving the posts from blogger(http://codefoundry.dev)'s feed. Let's create this service(BloggerService.ts) as well under src/service.

/* Line 1 */ declare type BloggerEntry = {
  id: {
    $t: string
  },
  updated: {
    $t: string
  },
  published: {
    $t: string
  },
  category: Array<{scheme: string, term: string}>,
  title: {
    $t: string
  },
  summary: {
    $t: string
  },
  author: Array<{name: { $t: string }}>,
  link: Array<{ rel: string, href: string }>
}

const getAllPosts = async() => {
  /* Line 2 */ const response = await fetch('https://www.blogger.com/feeds/5554118637855932326/posts/summary?alt=json&start-index=1&max-results=100')
  const result = await response.json();
  const categories = result?.feed?.category ?? [];
  const allTags = (categories as Array<{term: string}>).map(category => category.term)
  const entries = result?.feed?.entry ?? [];
  const posts = (entries as Array<BloggerEntry>).map(entry => {
    const id = entry.id.$t;
    const datePublishedOrUpdated = entry.updated.$t || entry.published.$t;
    const tags = entry.category.map(cat => cat.term);
    const title = entry.title.$t;
    const content = entry.summary.$t;
    const author = entry.author.map(a => a.name.$t).join(', ')
    const postLink = entry.link.find(l => l.rel === 'alternate');
    const postUrl = !!postLink ? postLink.href : '';

    /* Line 3 */ return {
      id,
      tags,
      title,
      content,
      author,
      postUrl,
      postedOn: datePublishedOrUpdated
    }
  })
  return { allTags, posts };
}

export default { getAllPosts }

At Line 1, we declared a type BlogEntry which refers to entry sent by the blogger's feed. At Line 2, we are using fetch api to retrieve summary feed from blogger(http://codefoundry.dev) and we are transforming and returning it to the type that our reducer store understands (At Line 3).

Cleanup App.tsx and BlogPosts.tsx

Earlier, we hard-coded posts(POSTS array) in App.tsx and were passing to BlogPosts component. Let's clean it up.

// App.tsx
function App() {
  return (
    <>
      <div className={styles['App-Container']}>
        <BlogPosts />
      </div>
    </>
  );
}

export default App;
// BlogPosts.tsx
function BlogPosts() {
  return (
    <div className={styles["blog-container"]}>
      <BlogPost/>
      <BlogListing/>
    </div>
  );
}

Let's run the application with command npm run dev.

That's it :). You can download the full code from github.

Recap

In this post, we first added required set of libraries (next and @types/next). Then, we added scripts to build, run and start project with next.js. Then, we did basic setup for next.js application e.g. Setting up _document.tsx and _app.tsx. Then, we created our first page index.tsx and created getServerSideProps method for server-side rendering. At last, we cleaned up App.tsx and BlogPosts.tsx file and ran the application.

What's next?

In the next post, we will use Next.js to generate static site along with Dynamic routing in static site. So, stay tuned!

Introduction

React was first introducted to general public in May 2013; roughly three years after the first release of Angular JS (October 2010). Soon, it picked up the momentum and now is the highest stared(~150K) and forked(29.2K) repository on Github. The positive point of React with its contemporary libraries was the backward compatibility in all the released versions. It started as a class based library (extending React.Component) to pure functional library with React Hooks; still keeping backward compatibility. Now, new features include asyncronous rendering with Suspense. React's ecosystem is very vast with lots of frameworks available to choose from. We will start with building first simple a.ka. Welcome react application and then build full-stack application with React, Redux, reselect, Next.JS, express JS and Node.JS. So, stay tuned :)

Building your first React application

You can create React application with project like create-react-app or can create customize project intialiting the project with npm and then pick and choose libraries of your choice. In this post, we will use create-react-app.

create-react-app conviently configures the tools like webpack, babel and testing libraries, so that you can concentrate purely on application code.

npx create-react-app my-first-react-app

npx is a package runner tool that comes with npm 5.2+ and higher.

This single line of code will setup Javascript based project, configures webpack, babel and testing libraries.

my-first-react-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    ├── logo.svg
    └── serviceWorker.js
    └── setupTests.js

It will also configure commands in package.json to start, build, test and eject (A command to remove transitive dependencies of webpack, babel, testing libraries and copies directly to package.json so that you can customize accordingly).

Let's run the application with npm run start and visit localhost:3000 on browser.

Creating first React component

Let's start with creating a component.

Create a new file Welcome.js and Welcome.css under src folder.

Add following lines to Welcome.js

import React from 'react';
import './Welcome.css';

function Welcome() {
  return <div className='welcome'>Welcome! My first react app</div>
}

export default Welcome;

Here, we have created a functional component which is equivalent to extending React.Component class and adding render function in it.

import React from 'react';
import './Welcome.css';

class Welcome extends React.Component {
  render() {
    return <div className='welcome'>Welcome! My first react app</div>
  }
}

export default Welcome;

Now, the first React component; let's add it to App.js

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Welcome />
      </header>
    </div>
  );
}

Now, go to localhost:3000 and you will see the component loaded.

Creating Typescript based first React application

Typescript is a typed superset of Javascript which compiles to plain Javascript. It provides the type safety to Javascript. create-react-app provides convenient way to change template for generating React skeleton project. Just pass the template parameter with value as follows.

npx create-react-app my-first-react-app --template typescript

Adding first typed component

Create a new file Welcome.tsx and Welcome.css under src folder.

Add following lines to Welcome.tsx

import React from 'react';
import './Welcome.css';

interface IWelcomeProps {
  message?: string
}

function Welcome(props: IWelcomeProps) {
  const message = props?.message ?? 'Welcome! My first React app with Typescript.'
  return (<div className='welcome'>{message}</div>);
}

export default Welcome;

We have defined the interface IWelcomeProps with single optional field message. In the functional component, we have used the Nullish coalescing added in Typescript 3.7.

Let's add this component to App.tsx

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Welcome />
        <Welcome message="Welcome Reader! My first react app with Typescript."/>
      </header>
    </div>
  );
}

We have added Welcome twice; with and without message field. The output after running the application will look like this.

Recap

We created our first React application using create-react-app project. We added first React component Welcome.js and Welcome.tsx in Javascript and Typescript based projects respectively.

What's next?

In the next post, we will build a BlogPost application using React's functional component and React hooks. We will use useState hook for state management. So, stay tuned!