관리 메뉴

Silver Library (Archived)

What is possible and not : Next.js + some example 본문

Fundamental of CS/Knowledge

What is possible and not : Next.js + some example

Ayin Kim 2022. 11. 13. 15:37
반응형

This page is a summary of an article written by Reed Barger, for personal use.

 

Does:

  • Page-based routing (create a page by putting components in /pages)
  • A built-in router (no need to install React Router)
  • API routes (write backend code using Node.js in /pages/api)
  • Super fast builds for development / production (see saved changes instantly)
  • Image and font optimization
  • Built-in ESLint and TypeScript support
  • + tons more (all outlined in the Next.js documentation)

Does not:

  • Authentication (I recommend using the package Next-Auth)
  • Testing (I recommend using Playwright or Cypress for your E2E tests)
  • State management (I recommend Zustand or Redux Toolkit)

list of similarity and table of contents (for this page):

- useRouter (router and route from react-router-dom)

- Link (Link from react-router-dom, but little different here e.g. href)

- useSWR (route API data)

- GetServerSideProps (to fetch data, use async)

 

tl;dr

This Next.js includes the following:

- Express.js, react-router-dom, SSR(Server Side Rendering).

 

 

Get Started with Next.js – The React Library Your Project Needs

I've composed this guide to give you a practical overview of perhaps the most important React library you will use to build 90% of your projects: Next.js. The goal of this tutorial is to get you started using Next.js as easily as possible. This is not a co

www.freecodecamp.org

 

Example:

How to use react-router-dom like feature in nextjs? useRouter

 

Want to add an About page to your app?

Just drop your component in /pages/about.js (.tsx if you're using TypeScript):

// No React import needed up here! 😳

export default function About() {
  return <div>About</div>
}

For example, to display blog posts according to a particular slug, we could drop a "blog" folder in pages with the filename: [nikonikoni].js:

import { useRouter } from 'next/router'

// if we navigate to localhost:3000/blog/123...
export default function BlogPost() {
  const router = useRouter()
  const { nikonikoni } = router.query

  return <p>Post: {nikonikoni}</p> // ...you'll see "Post: 123"
}

 

Links, Navigation

 

import Link from "next/link";

export default function About() {
  return (
    <div>
      <h1>About Me</h1>
      
      <div>
        <Link href="/">
          <a>Home</a>
        </Link>
        <Link href="/blog/123">
          <a>My Blog Post</a>
        </Link>
      </div>
    </div>
  );
}

href is the only required prop for the Link component and data can be passed to it as an object as well:

import Link from "next/link";

export default function About() {
  return (
    <div>
      <h1>About Me</h1>

      <div>
        <Link href={{ pathname: "/about" }}>
          <a>Home</a>
        </Link>
        <Link
          href={{
            pathname: "/blog/[slug]",
            query: { slug: "123" },
          }}
        >
          <a>My Blog Post</a>
        </Link>
      </div>
    </div>
  );
}

And finally, Route changes can also be done using the useRouter hook, primarily using the .push() method to push to a different route programmatically.

export default function Login() {
  const router = useRouter()
    
  function onSubmit(event) {
    event.preventDefault();
    const email = event.target.elements.email.value;  
    await sendLoginEmail(email);    
    // push user to /verify-email page
    router.push('/verify-email');
  }
    
  return (
    <div>
      <h1>Log in here</h1>

      <form onSubmit={onSubmit}>
        <input name="email" placeholder="Your email address" />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

And API routes?

Probably this is the reason why market demand for next.js is high.

// syntax is very similar to the "Express" Node.js framework

// here we are responding to every request with an OK (200) code and sending JSON data back (our name)

export default function handler(req, res) {
  res.status(200).json({ name: "Reed Barger" });
}

And another example. Instead of using the following example as you and I do in react:

// react!
import Link from "next/link";
import { useEffect, useState } from "react";

export default function About() {
  const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("api/about")
      .then((res) => res.json())
      .then((data) => {
        setData(data);
        setLoading(false);
      });
  }, []);

  if (isLoading) return <p>Loading...</p>;
  if (!data) return <p>No about data</p>;

  return (
    <div>
      <h1>My name is: {data.name}</h1>
    </div>
  );
}

using SWR:

import useSWR from "swr";

const fetcher = (...args) => fetch(...args).then((res) => res.json())

export default function About() {
  const { data, error } = useSWR("/api/about", fetcher)

  if (error) return <div>Error fetching data</div>
  if (!data) return <div>Loading...</div>

  return (
    <div>
      <h1>{data.name}</h1>
    </div>
  )
}

GetServerSideProps (literally)

getServerSideProps runs on every page visit. As a result, it is very helpful on pages with dynamic data or needs requests to be performed every time, such as getting authenticated user data.

export default function About({ name }) {
  return (
    <div>
      <h1>My name is: {name}</h1>
    </div>
  );
}

export function getServerSideProps() {
  return {
    props: { name: "Reed Barger" },
  };
}

If we wanted to fetch data from the server, we could do so by making getServerSideProps async using the async keyword.

export default function About({ name }) {
  return (
    <div>
      <h1>My name is: {name}</h1>
    </div>
  );
}

export async function getServerSideProps() {
  const data = await fetch("https://randomuser.me/api").then((res) =>
    res.json()
  );

  return {
    props: { name: data.results[0].name.first },
  };
}

 

'Fundamental of CS > Knowledge' 카테고리의 다른 글

react-query 에 대한 배경 정보  (0) 2022.11.29
GraphQL (GQL) 에 대한 기록.  (0) 2022.11.21
Lexical environment?  (0) 2022.11.11
Docker 사용의 기준점.  (0) 2022.11.05
What can I do with AWS amplify?  (0) 2022.11.05